在微信小程序中引用tensorflow.js坑向总结(一)

各种坑

    • 1. Error:No backend found in registry
    • 2. Error: This application has not registered any plugins yet
    • 3. Error:module "miniprogram_npm/@tensorflow/tfjs-core/crypto.js" is not defined 以及npm 构建@tensorflow/tfjs-core (编译tr46/index.js)卡死
    • 4. Error:Cannot read property 'setWebGLContext' of undefine
    • 5. 小程序开发者工具编译特别慢,经常卡死,内存占用特别多

1. Error:No backend found in registry

未在注册表中找到后端?但是我已经在package.json中以及安装了相关依赖

 "dependencies": {
    "@tensorflow/tfjs-backend-cpu": "^3.13.0",
    "@tensorflow/tfjs-backend-webgl": "^3.13.0",
    "@tensorflow/tfjs-converter": "^3.13.0",
    "@tensorflow/tfjs-core": "^3.13.0",
    "crypto-js": "^4.1.1",
    "fetch-wechat": "^0.0.3"
  }

解决方案:在 模型进行预测的js文件 中加上

require("@tensorflow/tfjs-backend-webgl")
require("@tensorflow/tfjs-backend-cpu")

成功解决!

2. Error: This application has not registered any plugins yet

插件未注册错误? 但是我已经注册了插件并且添加了appID

"plugins": {
    "tfjsPlugin": {
      "version": "0.1.0",
      "provider": "wx5b446950d438663b	"
    }
  },

解决方案:经过尝试,在微信开发者工具重新扫码登陆可以解决

3. Error:module “miniprogram_npm/@tensorflow/tfjs-core/crypto.js” is not defined 以及npm 构建@tensorflow/tfjs-core (编译tr46/index.js)卡死

  1. 这里先复现一下我的配置操作:
npm init -y
npm install @tensorflow/tfjs-core
npm install @tensorflow/tfjs-converter 
npm install fetch-wechat 
npm install @tensorflow/tfjs-backend-webgl 
npm install @tensorflow/tfjs-backend-cpu
npm install crypto-js (用于解决找不到crpyto.js 错误)
  1. 然后构建 npm,一直卡在 tr46/index.js 的编译上
  2. 然后删除miniprogram_npm 下tr46 包,重启开发工具
  3. 错误提示找不到crypto.js , 复制miniprogram_npm/crypto-js/index.js(代码文本) 到 miniprogram_npm/@tensorflow/tfjs-core/ 并重命名为crypto.js , 这一步仅仅是去掉了crypto.js 的报错
  4. 修改 app.js,参考代码
var fetchWechat = require('fetch-wechat');
var tf = require('@tensorflow/tfjs-core');
var plugin = requirePlugin('tfjsPlugin');
require("@tensorflow/tfjs-backend-webgl")
require("@tensorflow/tfjs-backend-cpu")
// app.js
App({
  onLaunch() {
    plugin.configPlugin({
      // polyfill fetch function
      fetchFunc: fetchWechat.fetchFunc(),
      // inject tfjs runtime
      tf,
      // provide webgl canvas
      canvas: wx.createOffscreenCanvas()
      
    });
    console.log('on launch')
    tf.tensor([1, 2, 3, 4]).print()
})

  1. 添加以下代码到 app.json
"plugins": {
    "tfjsPlugin": {
      "version": "0.1.0",
      "provider": "wx5b446950d438663b	"
    }
  },
  1. 最终开发者工具 console会显示输出

console输出

4. Error:Cannot read property ‘setWebGLContext’ of undefine

"plugins": {
    "tfjsPlugin": {
      "version": "0.0.6",
      "provider": "wx6afed118d9e81df9"
    }
  }

修改version版本为0.1.0即可解决

5. 小程序开发者工具编译特别慢,经常卡死,内存占用特别多

有可能是动态壁纸的问题,笔者这边关闭之后会好很多。。

你可能感兴趣的:(tensorflow,微信小程序,tensorflow,javascript)