• Stars
    star
    524
  • Rank 81,136 (Top 2 %)
  • Language
    TypeScript
  • Created almost 5 years ago
  • Updated about 1 month ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

WeChat Mini-program plugin for TensorFlow.js

TensorFlow.js 微信小程序插件

TensorFlow.js是谷歌开发的机器学习开源项目,致力于为javascript提供具有硬件加速的机器学习模型训练和部署。 TensorFlow.js 微信小程序插件封装了TensorFlow.js库,用于提供给第三方小程序调用。 例子可以看TFJS Mobilenet 物体识别小程序

添加插件

在使用插件前,首先要在小程序管理后台的“设置-第三方服务-插件管理”中添加插件。开发者可登录小程序管理后台,通过 appid [wx6afed118d9e81df9] 查找插件并添加。本插件无需申请,添加后可直接使用。

引入插件代码包

使用插件前,使用者要在 app.json 中声明需要使用的插件,例如:

代码示例:

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

引入TensorFlow.js npm

TensorFlow.js 最新版本是以npm包的形式发布,小程序需要使用npm或者yarn来载入TensorFlow.js npm包。也可以手动修改 package.json 文件来加入。

TensorFlow.js v2.0 有一个联合包 - @tensorflow/tfjs,包含了六个分npm包:

  • tfjs-core: 基础包
  • tfjs-converter: GraphModel 导入和执行包
  • tfjs-layers: LayersModel 创建,导入和执行包
  • tfjs-backend-webgl: webgl 后端
  • tfjs-backend-cpu: cpu 后端
  • tfjs-data:数据流

对于小程序而言,由于有2M的app大小限制,不建议直接使用联合包,而是按照需求加载分包。

  • 如果小程序只需要导入和运行GraphModel模型的的话,建议至少加入tfjs-core, tfjs-converter, tfjs-backend-webgl 和tfjs-backend-cpu包。这样可以尽量减少导入包的大小。
  • 如果需要创建,导入或训练LayersModel模型,需要再加入 tfjs-layers包。

下面的例子是只用到tfjs-core, tfjs-converter,tfjs-backend-webgl 和tfjs-backend-cpu包。代码示例:

{
  "name": "yourProject",
  "version": "0.0.1",
  "main": "dist/index.js",
  "license": "Apache-2.0",
  "dependencies": {
    "@tensorflow/tfjs-core": "3.5.0",
    "@tensorflow/tfjs-converter": "3.5.0",
    "@tensorflow/tfjs-backend-webgl": "3.5.0"
  }
}

参考小程序npm工具文档如何编译npm包到小程序中。

注意 请从微信小程序开发版Nightly Build更新日志下载最新的微信开发者工具,保证版本号>=v1.02.1907022.

Polyfill fetch 函数

如果需要使用tf.loadGraphModel或tf.loadLayersModel API来载入模型,小程序需要按以下流程填充fetch函数:

  1. 如果你使用npm, 你可以载入fetch-wechat npm 包
{
  "name": "yourProject",
  "version": "0.0.1",
  "main": "dist/index.js",
  "license": "Apache-2.0",
  "dependencies": {
    "@tensorflow/tfjs-core": "3.5.0",
    "@tensorflow/tfjs-converter": "3.5.0",
    "@tensorflow/tfjs-backend-webgl": "3.5.0"
    "fetch-wechat": "0.0.3"
  }
}
  1. 也可以直接拷贝以下文件到你的javascript源目录: https://cdn.jsdelivr.net/npm/[email protected]/dist/fetch_wechat.min.js

在app.js的onLaunch里调用插件configPlugin函数

var fetchWechat = require('fetch-wechat');
var tf = require('@tensorflow/tfjs-core');
var webgl = require('@tensorflow/tfjs-backend-webgl');
var plugin = requirePlugin('tfjsPlugin');
//app.js
App({
  onLaunch: function () {
    plugin.configPlugin({
      // polyfill fetch function
      fetchFunc: fetchWechat.fetchFunc(),
      // inject tfjs runtime
      tf,
      // inject webgl backend
      webgl,
      // provide webgl canvas
      canvas: wx.createOffscreenCanvas()
    });
  }
});

支持模型localStorage缓存

采用localStorage缓存可以减少模型下载耗费带宽和时间。由于微信小程序对于localStorage有10MB的限制,这个方法适用于小于10MB的模型。 步骤如下:

  1. 在app.js中提供localStorageHandler函数.
var fetchWechat = require('fetch-wechat');
var tf = require('@tensorflow/tfjs-core');
var plugin = requirePlugin('tfjsPlugin');
//app.js
App({
  // expose localStorage handler
  globalData: {localStorageIO: plugin.localStorageIO},
  ...
});
  1. 在模型加载时加入localStorageHandler逻辑。
const LOCAL_STORAGE_KEY = 'mobilenet_model';
export class MobileNet {
  private model: tfc.GraphModel;
  constructor() { }

  async load() {

    const localStorageHandler = getApp().globalData.localStorageIO(LOCAL_STORAGE_KEY);
    try {
      this.model = await tfc.loadGraphModel(localStorageHandler);
    } catch (e) {
      this.model =
        await tfc.loadGraphModel(MODEL_URL);
      this.model.save(localStorageHandler);
    }
  }

支持模型保存为用户文件

微信也支持保存模型为文件。同localStorage, 微信小程序对于本地文件也有10MB的限制,这个方法适用于小于10MB的模型。由于最终模型是按 binary 保存,较 localstorage 保存为 base64 string 更为节省空间。

步骤如下:

  1. 在app.js中提供 fileStorageHandler 函数.
var fetchWechat = require('fetch-wechat');
var tf = require('@tensorflow/tfjs-core');
var plugin = requirePlugin('tfjsPlugin');
//app.js
App({
  // expose fileStorage handler
  globalData: {fileStorageIO: plugin.fileStorageIO},
  ...
});
  1. 在模型加载时加入 fileStorageHandler 逻辑。
const FILE_STORAGE_PATH = 'mobilenet_model';
export class MobileNet {
  private model: tfc.GraphModel;
  constructor() { }

  async load() {

    const fileStorageHandler = getApp().globalData.fileStorageIO(
        FILE_STORAGE_PATH, wx.getFileSystemManager());
    try {
      this.model = await tfc.loadGraphModel(fileStorageHandler);
    } catch (e) {
      this.model =
        await tfc.loadGraphModel(MODEL_URL);
      this.model.save(fileStorageHandler);
    }
  }
}

使用 WebAssembly backend

微信小程序在 Android 手机上提供 WebAssembly的支持。TensorFlow.js的WASM backend非常适合在中低端Android手机上使用。 中低端手机的GPU往往相对CPU要弱一些,而WASM backend是跑在CPU上的,这就为中低端手机提供了另一个加速平台。而且WASM的能耗一般会更低。 使用WASM backend需要修改package.json文件:

{
  "name": "yourProject",
  "version": "0.0.1",
  "main": "dist/index.js",
  "license": "Apache-2.0",
  "dependencies": {
    "@tensorflow/tfjs-core": "2.0.0",
    "@tensorflow/tfjs-converter": "2.0.0",
    "@tensorflow/tfjs-backend-wasm": "2.0.0",
    ...
  }
}

然后在app.js中设置 wasm backend, 你可以自行host wasm file以提高下载速度, 下面例子中的 wasmUrl可以替代成你host的URL。

    const info = wx.getSystemInfoSync();
    const wasmUrl = 'https://cdn.jsdelivr.net/npm/@tensorflow/[email protected]/wasm-out/tfjs-backend-wasm.wasm';
    const usePlatformFetch = true;
    console.log(info.platform);
    if (info.platform == 'android') {
      setWasmPath(wasmUrl, usePlatformFetch);
      tf.setBackend('wasm').then(() => console.log('set wasm backend'));
    }

注意 WASM backend is broken due to bundle imcompatible with WeChat npm loader, will update here when it is fixed.

注意 由于最新版本的WeChat的OffscreenCanvas会随页面跳转而失效,在app.js的 onLaunch 函数中设置 tfjs 会导致小程序退出或页面跳转之后操作出错。建议在使用tfjs的page的onLoad中调用 configPlugin 函数。 WeChat的12月版本会修复这个问题。

var fetchWechat = require('fetch-wechat');
var tf = require('@tensorflow/tfjs-core');
var plugin = requirePlugin('tfjsPlugin');
//index.js
Page({
  onLoad: function () {
    plugin.configPlugin({
      // polyfill fetch function
      fetchFunc: fetchWechat.fetchFunc(),
      // inject tfjs runtime
      tf,
      // provide webgl canvas
      canvas: wx.createOffscreenCanvas(),
      backendName: 'wechat-webgl-' + Date.now()
    });
    ...
  }
});

组件设置完毕就可以开始使用 TensorFlow.js库的API了。

使用 tfjs-models 模型库注意事项

模型库提供了一系列训练好的模型,方便大家快速的给小程序注入ML功能。模型分类包括

  • 图像识别
  • 语音识别
  • 人体姿态识别
  • 物体识别
  • 文字分类

由于这些API默认模型文件都存储在谷歌云上,直接使用会导致中国用户无法直接读取。在小程序内使用模型API时要提供 modelUrl 的参数,可以指向我们在谷歌中国的镜像服务器。 谷歌云的base url是 https://storage.googleapis.com, 中国镜像的base url是https://www.gstaticcnapps.cn 模型的url path是一致的,比如

他们的 URL Path 都是 /tfjs-models/savedmodel/posenet/mobilenet/float/050/model-stride16.json

下面是加载posenet模型的例子:

import * as posenet from '@tensorflow-models/posenet';

const POSENET_URL =
    'https://www.gstaticcnapps.cn/tfjs-models/savedmodel/posenet/mobilenet/float/050/model-stride16.json';

const model = await posenet.load({
  architecture: 'MobileNetV1',
  outputStride: 16,
  inputResolution: 193,
  multiplier: 0.5,
  modelUrl: POSENET_URL
});

tfjs-examples tfjs例子库

tfjs API 使用实例。

版本需求

  • 微信基础库版本 >= 2.7.3
  • 微信开发者工具 >= v1.02.1907022
  • tfjs-core >= 1.5.2
  • tfjs-converter >= 1.5.2 如果使用localStorage模型缓存

注意 在微信开发者工具 v1.02.19070300 中,你需要在通用设置中打开硬件加速,从而在TensorFlow.js中启用WebGL加速。 setting

更新说明

  • 0.0.2 plugin不再映射TensorFlow.js API库,由小程序端提供。
  • 0.0.3 使用offscreen canvas,小程序无需加入plugin component。
  • 0.0.5 修改例子程序使用tfjs分包来降低小程序大小。
  • 0.0.6 支持 tfjs-core版本1.2.7。
  • 0.0.7 允许用户设置webgl backend name, 这可以解决小程序offscreen canvas会失效的问题。
  • 0.0.8 加入localStorage支持,允许小于10M模型在localStorage内缓存。
  • 0.0.9 加入fileSystem支持,允许小于10M模型在local file system内缓存。fixed missing kernel bug.
  • 0.1.0 支持 tfjs版本2.0.x。
  • 0.2.0 支持 tfjs版本3.x。

More Repositories

1

tensorflow

An Open Source Machine Learning Framework for Everyone
C++
181,486
star
2

models

Models and examples built with TensorFlow
Python
76,563
star
3

tfjs

A WebGL accelerated JavaScript library for training and deploying ML models.
TypeScript
18,104
star
4

tensor2tensor

Library of deep learning models and datasets designed to make deep learning more accessible and accelerate ML research.
Python
14,693
star
5

tfjs-models

Pretrained models for TensorFlow.js
TypeScript
13,679
star
6

playground

Play with neural networks!
TypeScript
11,585
star
7

tfjs-core

WebGL-accelerated ML // linear algebra // automatic differentiation for JavaScript.
TypeScript
8,491
star
8

examples

TensorFlow examples
Jupyter Notebook
7,681
star
9

tensorboard

TensorFlow's Visualization Toolkit
TypeScript
6,533
star
10

tfjs-examples

Examples built with TensorFlow.js
JavaScript
6,428
star
11

nmt

TensorFlow Neural Machine Translation Tutorial
Python
6,315
star
12

swift

Swift for TensorFlow
Jupyter Notebook
6,118
star
13

serving

A flexible, high-performance serving system for machine learning models
C++
6,068
star
14

docs

TensorFlow documentation
Jupyter Notebook
5,997
star
15

tpu

Reference models and tools for Cloud TPUs.
Jupyter Notebook
5,177
star
16

rust

Rust language bindings for TensorFlow
Rust
4,939
star
17

lucid

A collection of infrastructure and tools for research in neural network interpretability.
Jupyter Notebook
4,611
star
18

datasets

TFDS is a collection of datasets ready to use with TensorFlow, Jax, ...
Python
4,156
star
19

probability

Probabilistic reasoning and statistical analysis in TensorFlow
Jupyter Notebook
4,053
star
20

adanet

Fast and flexible AutoML with learning guarantees.
Jupyter Notebook
3,474
star
21

hub

A library for transfer learning by reusing parts of TensorFlow models.
Python
3,436
star
22

minigo

An open-source implementation of the AlphaGoZero algorithm
C++
3,428
star
23

skflow

Simplified interface for TensorFlow (mimicking Scikit Learn) for Deep Learning
Python
3,185
star
24

lingvo

Lingvo
Python
2,782
star
25

graphics

TensorFlow Graphics: Differentiable Graphics Layers for TensorFlow
Python
2,738
star
26

agents

TF-Agents: A reliable, scalable and easy to use TensorFlow library for Contextual Bandits and Reinforcement Learning.
Python
2,717
star
27

ranking

Learning to Rank in TensorFlow
Python
2,713
star
28

federated

A framework for implementing federated learning
Python
2,271
star
29

tfx

TFX is an end-to-end platform for deploying production ML pipelines
Python
2,073
star
30

privacy

Library for training machine learning models with privacy for training data
Python
1,862
star
31

fold

Deep learning with dynamic computation graphs in TensorFlow
Python
1,825
star
32

recommenders

TensorFlow Recommenders is a library for building recommender system models using TensorFlow.
Python
1,739
star
33

quantum

Hybrid Quantum-Classical Machine Learning in TensorFlow
Python
1,723
star
34

mlir

"Multi-Level Intermediate Representation" Compiler Infrastructure
1,720
star
35

addons

Useful extra functionality for TensorFlow 2.x maintained by SIG-addons
Python
1,677
star
36

tflite-micro

Infrastructure to enable deployment of ML models to low-power resource-constrained embedded targets (including microcontrollers and digital signal processors).
C++
1,629
star
37

haskell

Haskell bindings for TensorFlow
Haskell
1,558
star
38

mesh

Mesh TensorFlow: Model Parallelism Made Easier
Python
1,540
star
39

model-optimization

A toolkit to optimize ML models for deployment for Keras and TensorFlow, including quantization and pruning.
Python
1,459
star
40

workshops

A few exercises for use at events.
Jupyter Notebook
1,457
star
41

ecosystem

Integration of TensorFlow with other open-source frameworks
Scala
1,362
star
42

gnn

TensorFlow GNN is a library to build Graph Neural Networks on the TensorFlow platform.
Python
1,260
star
43

community

Stores documents used by the TensorFlow developer community
C++
1,239
star
44

model-analysis

Model analysis tools for TensorFlow
Python
1,234
star
45

text

Making text a first-class citizen in TensorFlow.
C++
1,194
star
46

benchmarks

A benchmark framework for Tensorflow
Python
1,130
star
47

tfjs-node

TensorFlow powered JavaScript library for training and deploying ML models on Node.js.
TypeScript
1,048
star
48

similarity

TensorFlow Similarity is a python package focused on making similarity learning quick and easy.
Python
994
star
49

transform

Input pipeline framework
Python
982
star
50

neural-structured-learning

Training neural models with structured signals.
Python
976
star
51

gan

Tooling for GANs in TensorFlow
Jupyter Notebook
907
star
52

compression

Data compression in TensorFlow
Python
820
star
53

swift-apis

Swift for TensorFlow Deep Learning Library
Swift
794
star
54

deepmath

Experiments towards neural network theorem proving
C++
779
star
55

data-validation

Library for exploring and validating machine learning data
Python
748
star
56

runtime

A performant and modular runtime for TensorFlow
C++
746
star
57

java

Java bindings for TensorFlow
Java
730
star
58

tensorrt

TensorFlow/TensorRT integration
Jupyter Notebook
723
star
59

tfjs-converter

Convert TensorFlow SavedModel and Keras models to TensorFlow.js
TypeScript
697
star
60

io

Dataset, streaming, and file system extensions maintained by TensorFlow SIG-IO
C++
686
star
61

docs-l10n

Translations of TensorFlow documentation
Jupyter Notebook
684
star
62

swift-models

Models and examples built with Swift for TensorFlow
Jupyter Notebook
644
star
63

decision-forests

A collection of state-of-the-art algorithms for the training, serving and interpretation of Decision Forest models in Keras.
Python
643
star
64

tcav

Code for the TCAV ML interpretability project
Jupyter Notebook
612
star
65

recommenders-addons

Additional utils and helpers to extend TensorFlow when build recommendation systems, contributed and maintained by SIG Recommenders.
Cuda
547
star
66

lattice

Lattice methods in TensorFlow
Python
519
star
67

model-card-toolkit

A toolkit that streamlines and automates the generation of model cards
Python
399
star
68

flutter-tflite

Dart
385
star
69

custom-op

Guide for building custom op for TensorFlow
Smarty
370
star
70

cloud

The TensorFlow Cloud repository provides APIs that will allow to easily go from debugging and training your Keras and TensorFlow code in a local environment to distributed training in the cloud.
Python
364
star
71

mlir-hlo

MLIR
361
star
72

tfjs-vis

A set of utilities for in browser visualization with TensorFlow.js
TypeScript
360
star
73

tflite-support

TFLite Support is a toolkit that helps users to develop ML and deploy TFLite models onto mobile / ioT devices.
C++
354
star
74

profiler

A profiling and performance analysis tool for TensorFlow
TypeScript
344
star
75

fairness-indicators

Tensorflow's Fairness Evaluation and Visualization Toolkit
Jupyter Notebook
330
star
76

moonlight

Optical music recognition in TensorFlow
Python
325
star
77

tfjs-tsne

TypeScript
309
star
78

estimator

TensorFlow Estimator
Python
295
star
79

embedding-projector-standalone

HTML
284
star
80

tfjs-layers

TensorFlow.js high-level layers API
TypeScript
283
star
81

build

Build-related tools for TensorFlow
Shell
248
star
82

kfac

An implementation of KFAC for TensorFlow
Python
195
star
83

tflite-micro-arduino-examples

C++
180
star
84

ngraph-bridge

TensorFlow-nGraph bridge
C++
138
star
85

profiler-ui

[Deprecated] The TensorFlow Profiler (TFProf) UI provides a visual interface for profiling TensorFlow models.
HTML
134
star
86

tensorboard-plugin-example

Python
134
star
87

tfx-addons

Developers helping developers. TFX-Addons is a collection of community projects to build new components, examples, libraries, and tools for TFX. The projects are organized under the auspices of the special interest group, SIG TFX-Addons. Join the group at http://goo.gle/tfx-addons-group
Jupyter Notebook
121
star
88

metadata

Utilities for passing TensorFlow-related metadata between tools
Python
102
star
89

networking

Enhanced networking support for TensorFlow. Maintained by SIG-networking.
C++
96
star
90

tfhub.dev

Python
71
star
91

tfjs-website

WebGL-accelerated ML // linear algebra // automatic differentiation for JavaScript.
CSS
69
star
92

java-models

Models in Java
Java
68
star
93

java-ndarray

Java
66
star
94

tfjs-data

Simple APIs to load and prepare data for use in machine learning models
TypeScript
66
star
95

tfx-bsl

Common code for TFX
Python
61
star
96

autograph

Python
50
star
97

model-remediation

Model Remediation is a library that provides solutions for machine learning practitioners working to create and train models in a way that reduces or eliminates user harm resulting from underlying performance biases.
Python
42
star
98

codelabs

Jupyter Notebook
36
star
99

tensorstore

C++
25
star
100

swift-bindings

Swift
25
star