TensorFlow.js是一个JavaScript库,用于在浏览器和Node.js中训练和部署机器学习模型
轻松写机器学习应用
想尝试机器学习给我们带来乐趣,即使不了解机器学习底层如张量或优化器这些细节。通过
建立在TensorFlow.js之上 ml5.js 可以轻松写机器学习的应用。ml5.js 以简洁、易懂的 API 让我们可以在在浏览器轻松使用机器学习算法和模型。
如果您对张量、层、优化器和损失函数等比较熟悉,想开发更多个性化,自定义模型,TensorFlow.js 因为熟悉 JavaScript 的您提供了支持。
设置
浏览器安装
要在浏览器端使用 TensorFlow.js 有两种方式
- 使用脚本标签引入 TensorFlow.js
- 也可以 NPM 安装或者使用 Parcel、WebPack 或 Rollup 等构建工具创建 TensorFlow.js 项目
如果你接触 web 开发时间不长,或者从未听说过 webpack 或 parcel 这样的工具,建议你使用脚本标签的方法来引入 TensorFlow.js。如果这些工具对你并不陌生,还是建议您使用构建工具。
标签引入方式安装 TensorFlow.js
使用如下标签来引入 TensorFlow.js
<script src="https://cdn.jsdelivr.net/npm/@tensorflow/tfjs@2.0.0/dist/tf.min.js"></script>
构建工具方式安装 TensorFlow.js
yarn add @tensorflow/tfjs
npm install @tensorflow/tfjs
Nodejs 安装
可以使用 npm 或者 yarn 安装 TensorFlow.js
- 第一种选择是安装绑定了 c++ 的 TensorFlow.js
yarn add @tensorflow/tfjs-node
npm install @tensorflow/tfjs-node
- 如果(仅适用 Linux 系统) 对于系统已经安装了 NVIDIA® GPU 可以安装支持 GPU 的 TensorFlow.js
yarn add @tensorflow/tfjs-node-gpu
npm install @tensorflow/tfjs-node-gpu
- 当然也可以直接安装 javascript 版本,这个版本相对上面两个版本性能要差一些
yarn add @tensorflow/tfjs
npm install @tensorflow/tfjs
TensorFlow
有关 TensorFlow 名字在这里给大家解释一下,TensorFlow 是由 Tensor 和 Flow 组成
Tensor 表示数据结构
- 常量 Scalar 例如 3
- 向量 Vector(数组,一维矩阵)[1,4,7]
- 矩阵 Matrix [[1,2[,[5,6]]
Flow
我们创建神经网络为图的结构,Flow 表示数据从图中进行流动。
TensorFlow 出现在 2011 ,google 在 2015 将其开源,随着深度学习一天一天火,TensorFlow 凭借自身优势也广受大家好评,作为首选学习和使用的深度学习框架。
2018 年 2 月 Deeplearn.js 成为 TensorFlow 的一部分,演变为 TensorFlow.js
<script src="https://cdn.jsdelivr.net/npm/@tensorflow/tfjs/dist/tf.min.js"> </script>
const t1 = tf.tensor([1,2,3,4])
console.log(t1)
图
const t2 = tf.tensor([1,2,3],[2,3])
console.log(t2)
可以通过 shape 为数据确定其结构或者说形状
const shape = [2,2,2]
const t2 = tf.tensor([1,2,3,2,3,2,5,6],shape)
console.log(t2)
图
const t2 = tf.tensor([1,2,3,2,3,2,5,6],shape,'int32')
tf.tensor(数据,形状,数据类型)
const shape = [5,3]
const val = []
for (let index = 0; index < 15; index++) {
val[index] = Math.random(0,100)
}
const t1 = tf.tensor(val,shape)
console.log(t1)
tf.scalar(3.12).print()
const t1 = tf.tensor(val,shape).dataSync()