安卓平台可以通过调用onnx模型来举行盘算,这为移动设备提供了更多的盘算本事和应用场景。通过使用onnx模型,安卓设备可以举行复杂的盘算任务,比方图像识别、语音识别等。这为移动应用的功能和性能提拔提供了新的可能性。同时,开发者可以利用onnx模型来开发更加智能和高效的安卓应用,为用户提供更好的体验。总的来说,安卓调用onnx模型并举行盘算的本事为移动设备的发展带来了新的机会和挑战。
依赖
build.gradle
准备好onnx放在assert目录下
api介绍
地点
api文档https://javadoc.io/doc/com.microsoft.onnxruntime/onnxruntime/latest/index.html
常用的api
api | 作用 | - OrtEnvironment.getEnvironment()
复制代码 | 创建onnx上下文的运行环境 | - new OrtSession.SessionOptions()
复制代码 | | - environment.createSession(bytes, options)
复制代码 | - 创建会话,第一个参数是模型数据,第二个是配置的参数
复制代码 | - LongBuffer.wrap(inputValues)
复制代码 | 将输入转换成onnx识别的输入,输入是模型识别的数据 | - OnnxTensor.createTensor(environment, wrap, new long[]{1, inputValues.length})
复制代码 | 创建tensor,第一个参数是上面定义的环境,第二个参数是输入转换成模型的格式,第三个根据实际设置,为入参的矩阵格式 | | 推理,map是整合起来的数据 | - (long[][]) output.get(1).getValue()
复制代码 | 获取推理结果,这里以二维数组为例 | 使用案例
- private String getOnnx(String text) {
- OrtEnvironment environment = OrtEnvironment.getEnvironment();
- AssetManager assetManager = getAssets();
- try {
- // 创建会话
- OrtSession.SessionOptions options = new OrtSession.SessionOptions();
- // 读取模型
- InputStream stream = assetManager.open("youonnx.onnx");
- ByteArrayOutputStream byteStream = new ByteArrayOutputStream();
- byte[] buffer = new byte[4096];
- int bytesRead;
- while ((bytesRead = stream.read(buffer)) != -1) {
- byteStream.write(buffer, 0, bytesRead);
- }
- byteStream.flush();
- byte[] bytes = byteStream.toByteArray();
- OrtSession session = environment.createSession(bytes, options);
- String vocab = "vocab";
- String puncVocab = "punc_vocab";
- Map<String, Integer> vocabMap = getFormFile(vocab, new String[]{"<UNK>", "<END>"});
- Map<String, Integer> puncVocabMap = getFormFile(vocab, new String[]{" "});
- DataSet.NoPuncTextDataset dataset = new DataSet.NoPuncTextDataset(vocabMap, puncVocabMap);
- List<Integer> list = dataset.word2seq(text);
- // 准备输入数据
- long[] inputValues = new long[list.size()];
- for (int i = 0; i < list.size(); i++) {
- inputValues[i] = list.get(i);
- }
- LongBuffer wrap = LongBuffer.wrap(inputValues);
- OnnxTensor inputTensor = OnnxTensor.createTensor(environment, wrap, new long[]{1, inputValues.length});
- long[] len = new long[]{inputValues.length};
- LongBuffer wrap2 = LongBuffer.wrap(len);
- OnnxTensor inputTensor_len = OnnxTensor.createTensor(environment, wrap2, new long[]{1});
- // 准备数据
- Map<String, OnnxTensor> map = new HashMap<>();
- map.put("inputs", inputTensor);
- map.put("inputs_len", inputTensor_len);
- // 运行推理
- OrtSession.Result output = session.run(map);
- // 获取输出结果
- long[][] value = (long[][]) output.get(1).getValue();
- // 处理输出结果
- // todo
- session.close();
- return "you_answer"
- } catch (IOException | OrtException e) {
- throw new RuntimeException(e);
- }
- }
复制代码 通过调用此函数,可以实现安卓调用onnx
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。 |