1# 使用MindSpore Lite开发AI应用 2 3## 使用场景 4 5开发者可以使用MindSpore Lite提供的JS API,在UI代码中直接集成MindSpore Lite能力,快速部署AI算法,进行AI模型推理。 6 7## 基本概念 8 9在进行开发前,请先了解以下概念。 10 11**张量**:它与数组和矩阵非常相似,是MindSpore Lite网络运算中的基本数据结构。 12 13**Float16推理模式**: Float16又称半精度,它使用16比特表示一个数。Float16推理模式表示推理的时候用半精度进行推理。 14 15## 接口说明 16这里给出MindSpore Lite推理的通用开发流程中涉及的一些接口,具体请见下列表格。更多接口及详细内容,请见[@ohos.ai.mindSporeLite (推理能力)](../../reference/apis-mindspore-lite-kit/js-apis-mindSporeLite.md)。 17 18| 接口名 | 描述 | 19| ------------------ | ----------------- | 20|loadModelFromFile(model: string, context?: Context): Promise<Model>|从路径加载模型。| 21|getInputs(): MSTensor[]|获取模型的输入。| 22|predict(inputs: MSTensor[]): Promise<MSTensor[]>|推理模型。| 23| getData(): ArrayBuffer | 获取张量的数据。 | 24| setData(inputArray: ArrayBuffer): void | 设置张量的数据。 | 25 26## 推理代码开发 27 28假设开发者已准备好`.ms`格式模型。模型推理流程包括读取、编译、推理和释放,具体开发过程及细节如下: 29 301. 创建上下文,设置线程数、设备类型等参数。 312. 加载模型。本文从路径读入模型。 323. 加载数据。模型执行之前需要先获取输入,再向输入的张量中填充数据。 334. 执行推理并读取输出。使用predict接口进行模型推理。 34 35```ts 36// 构造单例对象 37export class GlobalContext { 38 private constructor() {} 39 private static instance: GlobalContext; 40 private _objects = new Map<string, Object>(); 41 42 public static getContext(): GlobalContext { 43 if (!GlobalContext.instance) { 44 GlobalContext.instance = new GlobalContext(); 45 } 46 return GlobalContext.instance; 47 } 48 49 getObject(value: string): Object | undefined { 50 return this._objects.get(value); 51 } 52 53 setObject(key: string, objectClass: Object): void { 54 this._objects.set(key, objectClass); 55 } 56 57} 58``` 59 60```ts 61import { GlobalContext } from '../GlobalContext'; 62import mindSporeLite from '@ohos.ai.mindSporeLite'; 63import common from '@ohos.app.ability.common'; 64export class Test { 65 value:number = 0; 66 foo(): void { 67 GlobalContext.getContext().setObject("value", this.value); 68 } 69} 70let globalContext = GlobalContext.getContext().getObject("value") as common.UIAbilityContext; 71let inputBuffer : ArrayBuffer | null = null; 72let inputName: string = 'mnet_caffemodel_nhwc.bin'; 73 74globalContext.resourceManager.getRawFileContent(inputName).then((buffer : Uint8Array) => { 75 inputBuffer = buffer.buffer as object as ArrayBuffer ; 76 console.log('=========input bin byte length: ' + buffer.byteLength) 77}) 78// 1.创建上下文 79let context: mindSporeLite.Context = {}; 80context.target = ['cpu']; 81context.cpu = {} 82context.cpu.threadNum = 1; 83context.cpu.threadAffinityMode = 0; 84context.cpu.precisionMode = 'enforce_fp32'; 85 86// 2.加载模型 87let modelFile = '/data/storage/el2/base/haps/entry/files/mnet.caffemodel.ms'; 88let msLiteModel : mindSporeLite.Model = await mindSporeLite.loadModelFromFile(modelFile, context); 89 90// 3.设置输入数据 91let modelInputs : mindSporeLite.MSTensor[] = msLiteModel.getInputs(); 92if (inputBuffer != null) { 93 modelInputs[0].setData(inputBuffer as ArrayBuffer); 94} 95 96// 4.执行推理并打印输出 97console.log('=========MSLITE predict start=====') 98msLiteModel.predict(modelInputs).then((modelOutputs : mindSporeLite.MSTensor[]) => { 99 let output0 = new Float32Array(modelOutputs[0].getData()); 100 for (let i = 0; i < output0.length; i++) { 101 console.log(output0[i].toString()); 102 } 103 }) 104console.log('=========MSLITE predict success=====') 105``` 106 107## 调测验证 108 1091. 在DevEco Studio 中连接设备,点击Run entry,编译自己的hap,有如下显示: 110 111 ```shell 112 Launching com.example.myapptfjs 113 $ hdc uninstall com.example.myapptfjs 114 $ hdc install -r "path/to/xxx.hap" 115 $ hdc shell aa start -a EntryAbility -b com.example.myapptfjs 116 ``` 117 1182. 使用hdc连接设备,并将mnet.caffemodel.ms推送到设备中的沙盒目录。mnet_caffemodel_nhwc.bin在本地项目中的rawfile目录下。 119 120 ```shell 121 hdc -t your_device_id file send .\mnet.caffemodel.ms /data/app/el2/100/base/com.example.myapptfjs/haps/entry/files/ 122 ``` 1233. 在设备屏幕点击Test_MSLiteModel_predict触发用例,在HiLog打印结果中得到如下结果: 124 125 ```shell 126 08-27 23:25:50.278 31782-31782/? I C03d00/JSAPP: =========MSLITE predict start===== 127 08-27 23:25:51.487 31782-31782/? I C03d00/JSAPP: 0.10046602040529252 128 08-27 23:25:51.487 31782-31782/? I C03d00/JSAPP: 0.07535600662231445 129 08-27 23:25:51.487 31782-31782/? I C03d00/JSAPP: 0.06326554715633392 130 08-27 23:25:51.487 31782-31782/? I C03d00/JSAPP: 0.0015114173293113708 131 08-27 23:25:51.487 31782-31782/? I C03d00/JSAPP: -0.026745859533548355 132 08-27 23:25:51.487 31782-31782/? I C03d00/JSAPP: -0.055590517818927765 133 08-27 23:25:51.487 31782-31782/? I C03d00/JSAPP: -0.05325715243816376 134 08-27 23:25:51.487 31782-31782/? I C03d00/JSAPP: -0.04629542678594589 135 ... 136 08-27 23:25:52.881 31782-31782/? I C03d00/JSAPP: 0.23317644000053404 137 08-27 23:25:52.881 31782-31782/? I C03d00/JSAPP: 0.17999525368213654 138 08-27 23:25:50.372 31782-31782/? I C03d00/JSAPP: =========MSLITE predict success===== 139 ``` 140