uniapp引入Tensorflow.js所会发生的一些问题( 主要发布平台 微信小程序 )
迪丽瓦拉
2024-03-13 13:08:30
0

问题环境

python 环境

版本
tensorflow2.6.0
tensorflow-js3.18.0

uniapp(vue)

完整引入包

{"dependencies": {"@tensorflow/tfjs-core": "3.5.0","@tensorflow/tfjs-converter":"3.5.0","@tensorflow/tfjs-backend-webgl":"3.5.0","@tensorflow/tfjs-backend-cpu":"3.5.0","fetch-wechat": "0.0.3"}
}

问题一:Uniapp环境下如何引入Tensorflow.js包

在package.json下配置

{"dependencies": {"@tensorflow/tfjs-core": "3.5.0","@tensorflow/tfjs-converter":"3.5.0",}
}

PS: 许多文章都说只需要引入tensorflow.js 子包,但是子包所蕴涵的功能并不全面。如果你只是一个新手,最好是直接加载@tensorflow/tfjs。后续慢慢了解自己需要用到那几个模块再进行删减.

具体各个包的功能如下

功能说明
tfjs-core基础包(数据基本结构)
tfjs-converter模型导入
tfjs-layers自己构建模型
tfjs-data数据流
tfjs-backend-webgl作为前端使用时需要导入
tfjs-backend-cpu作为前端使用时需要导入

后续在目标项目的路径下打开命令行, 输入指令

 npm install

当然,你有更好的方法也可以指明或留言

问题:当在微信小程序环境出现错误“No backend found in registry”

单纯只是在web环境运行你的配置只需要

{"@tensorflow/tfjs-backend-webgl":"3.5.0"
}

如果你的代码需要在微信小程序上运行则需要同时引入两个包

{"@tensorflow/tfjs-backend-webgl":"3.5.0","@tensorflow/tfjs-backend-cpu":"3.5.0",
}

同时你所引入的这个包,需要在你对应的页面或者公共地方引入

	require('@tensorflow/tfjs-backend-webgl');require('@tensorflow/tfjs-backend-cpu')

问题: uniapp内没问题,微信小程序 错误:Cannot read property ‘fetch’ of undefined

如果你已经和引入fetchWetch , 并且在对应的页面已经引入。那么你估计是没有调用插件代码。
你需要在公共文件的onLaunch 内写下这段代码

var fetchWechat = require('fetch-wechat');var tf = require('@tensorflow/tfjs-core');var webgl = require('@tensorflow/tfjs-backend-webgl');var plugin = requirePlugin('tfjsPlugin');plugin.configPlugin({// polyfill fetch functionfetchFunc: fetchWechat.fetchFunc(),// inject tfjs runtimetf,// inject webgl backendwebgl,// provide webgl canvascanvas: wx.createOffscreenCanvas()});

但是这时候一般都会有问题,由于requirePlugin ,似乎是只有在微信小程序才会永远的功能。如果我们在现在调用会直接报错。
面对这种情况,我们只有两种方法

  1. 直接盲写代码,放弃在uniapp内调试。(如果采用这种,我觉得其实可以尝试一下直接在微信小程序开发工具直接开发。说不好能节省不少的时间)
  2. 对上面的方法进行加工,仅在微信小程序环境下进行调用
			// 获取平台基本信息let systemInfo = uni.getSystemInfoSync()// 获取当前的平台let uniPlatform = systemInfo.uniPlatformif (uniPlatform == "mp-weixin") {var fetchWechat = require('fetch-wechat');var tf = require('@tensorflow/tfjs-core');var webgl = require('@tensorflow/tfjs-backend-webgl');var plugin = requirePlugin('tfjsPlugin');plugin.configPlugin({// polyfill fetch functionfetchFunc: fetchWechat.fetchFunc(),// inject tfjs runtimetf,// inject webgl backendwebgl,// provide webgl canvascanvas: wx.createOffscreenCanvas()});}},

相关内容