安卓调用onnx模型并盘算

打印 上一主题 下一主题

主题 557|帖子 557|积分 1671

安卓平台可以通过调用onnx模型来举行盘算,这为移动设备提供了更多的盘算本事和应用场景。通过使用onnx模型,安卓设备可以举行复杂的盘算任务,比方图像识别、语音识别等。这为移动应用的功能和性能提拔提供了新的可能性。同时,开发者可以利用onnx模型来开发更加智能和高效的安卓应用,为用户提供更好的体验。总的来说,安卓调用onnx模型并举行盘算的本事为移动设备的发展带来了新的机会和挑战。
   

依赖

build.gradle

  1. plugins {
  2.     id 'com.android.application'
  3. }
  4. repositories {
  5.     jcenter()
  6.     maven {
  7.         url "https://oss.sonatype.org/content/repositories/snapshots"
  8.     }
  9. }
  10. android {
  11.     signingConfigs {
  12.         release {
  13.             storeFile file('myapp.keystore')
  14.             storePassword '123456'
  15.             keyAlias 'myapp'
  16.             keyPassword '123456'
  17.         }
  18.     }
  19.     packagingOptions {
  20.         pickFirst 'lib/arm64-v8a/libc++_shared.so'
  21.     }
  22.     configurations {
  23.         extractForNativeBuild
  24.     }
  25.     compileSdkVersion 28
  26.     buildToolsVersion "30.0.3"
  27.     defaultConfig {
  28.         applicationId "com.mobvoi.myapp"
  29.         minSdkVersion 21
  30.         targetSdkVersion 28
  31.         versionCode 1
  32.         versionName "1.0"
  33.         testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
  34.         externalNativeBuild {
  35.             cmake {
  36.                 targets "myapp", "decoder_main"
  37.                 cppFlags "-std=c++11", "-DC10_USE_GLOG", "-DC10_USE_MINIMAL_GLOG", "-DANDROID", "-Wno-c++11-narrowing", "-fexceptions"
  38.             }
  39.         }
  40.         ndkVersion '21.3.6528147'
  41.         ndk {
  42.             abiFilters 'arm64-v8a'
  43.         }
  44.     }
  45.     buildTypes {
  46.         release {
  47.             minifyEnabled false
  48.             signingConfig signingConfigs.release
  49.             proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
  50.         }
  51.     }
  52.     externalNativeBuild {
  53.         cmake {
  54.             path "src/main/cpp/CMakeLists.txt"
  55.         }
  56.     }
  57.     compileOptions {
  58.         sourceCompatibility JavaVersion.VERSION_1_8
  59.         targetCompatibility JavaVersion.VERSION_1_8
  60.     }
  61.     ndkVersion '21.3.6528147'
  62. }
  63. dependencies {
  64.     implementation 'androidx.appcompat:appcompat:1.2.0'
  65.     implementation 'com.google.android.material:material:1.2.1'
  66.     implementation 'androidx.constraintlayout:constraintlayout:2.0.4'
  67.     testImplementation 'junit:junit:4.+'
  68.     androidTestImplementation 'androidx.test.ext:junit:1.1.2'
  69.     androidTestImplementation 'androidx.test.espresso:espresso-core:3.3.0'
  70.     implementation 'org.pytorch:pytorch_android:1.10.0'
  71.     extractForNativeBuild 'org.pytorch:pytorch_android:1.10.0'
  72.     implementation group: 'com.microsoft.onnxruntime', name: 'onnxruntime-android', version: '1.15.1'
  73. }
  74. task extractAARForNativeBuild {
  75.     doLast {
  76.         configurations.extractForNativeBuild.files.each {
  77.             def file = it.absoluteFile
  78.             copy {
  79.                 from zipTree(file)
  80.                 into "$buildDir/$file.name"
  81.                 include "headers/**"
  82.                 include "jni/**"
  83.             }
  84.         }
  85.     }
  86. }
  87. tasks.whenTaskAdded { task ->
  88.     if (task.name.contains('externalNativeBuild')) {
  89.         task.dependsOn(extractAARForNativeBuild)
  90.     }
  91. }
复制代码
准备好onnx放在assert目录下


api介绍

地点

api文档
https://javadoc.io/doc/com.microsoft.onnxruntime/onnxruntime/latest/index.html
常用的api

api作用
  1. OrtEnvironment.getEnvironment()
复制代码
创建onnx上下文的运行环境
  1. new OrtSession.SessionOptions()
复制代码
  1. 创建会话(配置)
复制代码
  1. environment.createSession(bytes, options)
复制代码
  1. 创建会话,第一个参数是模型数据,第二个是配置的参数
复制代码
  1. LongBuffer.wrap(inputValues)
复制代码
将输入转换成onnx识别的输入,输入是模型识别的数据
  1. OnnxTensor.createTensor(environment, wrap, new long[]{1, inputValues.length})
复制代码
创建tensor,第一个参数是上面定义的环境,第二个参数是输入转换成模型的格式,第三个根据实际设置,为入参的矩阵格式
  1. session.run(map)
复制代码
推理,map是整合起来的数据
  1. (long[][]) output.get(1).getValue()
复制代码
获取推理结果,这里以二维数组为例
使用案例

  1. private String getOnnx(String text) {
  2.         OrtEnvironment environment = OrtEnvironment.getEnvironment();
  3.         AssetManager assetManager = getAssets();
  4.         try {
  5.             // 创建会话
  6.             OrtSession.SessionOptions options = new OrtSession.SessionOptions();
  7.             // 读取模型
  8.             InputStream stream = assetManager.open("youonnx.onnx");
  9.             ByteArrayOutputStream byteStream = new ByteArrayOutputStream();
  10.             byte[] buffer = new byte[4096];
  11.             int bytesRead;
  12.             while ((bytesRead = stream.read(buffer)) != -1) {
  13.                 byteStream.write(buffer, 0, bytesRead);
  14.             }
  15.             byteStream.flush();
  16.             byte[] bytes = byteStream.toByteArray();
  17.             OrtSession session = environment.createSession(bytes, options);
  18.             String vocab = "vocab";
  19.             String puncVocab = "punc_vocab";
  20.             Map<String, Integer> vocabMap = getFormFile(vocab, new String[]{"<UNK>", "<END>"});
  21.             Map<String, Integer> puncVocabMap = getFormFile(vocab, new String[]{" "});
  22.             DataSet.NoPuncTextDataset dataset = new DataSet.NoPuncTextDataset(vocabMap, puncVocabMap);
  23.             List<Integer> list = dataset.word2seq(text);
  24.             // 准备输入数据
  25.             long[] inputValues = new long[list.size()];
  26.             for (int i = 0; i < list.size(); i++) {
  27.                 inputValues[i] = list.get(i);
  28.             }
  29.             LongBuffer wrap = LongBuffer.wrap(inputValues);
  30.             OnnxTensor inputTensor = OnnxTensor.createTensor(environment, wrap, new long[]{1, inputValues.length});
  31.             long[] len = new long[]{inputValues.length};
  32.             LongBuffer wrap2 = LongBuffer.wrap(len);
  33.             OnnxTensor inputTensor_len = OnnxTensor.createTensor(environment, wrap2, new long[]{1});
  34.             // 准备数据
  35.             Map<String, OnnxTensor> map = new HashMap<>();
  36.             map.put("inputs", inputTensor);
  37.             map.put("inputs_len", inputTensor_len);
  38.             // 运行推理
  39.             OrtSession.Result output = session.run(map);
  40.             // 获取输出结果
  41.             long[][] value = (long[][]) output.get(1).getValue();
  42.             // 处理输出结果
  43.             // todo
  44.             session.close();
  45.             return "you_answer"
  46.         } catch (IOException | OrtException e) {
  47.             throw new RuntimeException(e);
  48.         }
  49.     }
复制代码
通过调用此函数,可以实现安卓调用onnx

免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。

本帖子中包含更多资源

您需要 登录 才可以下载或查看,没有账号?立即注册

x
回复

使用道具 举报

0 个回复

倒序浏览

快速回复

您需要登录后才可以回帖 登录 or 立即注册

本版积分规则

慢吞云雾缓吐愁

金牌会员
这个人很懒什么都没写!

标签云

快速回复 返回顶部 返回列表