原文链接: tensorflowjs 简单使用
github
https://github.com/tensorflow/tfjs
引入和安装
简单引入js文件
<script src="https://cdn.jsdelivr.net/npm/@tensorflow/tfjs/dist/tf.min.js"> </script>
在js中即可使用tf变量
npm方式
1cnpm install @tensorflow/tfjs -D 2 3 4import * as tf from '@tensorflow/tfjs';
常见操作
https://js.tensorflow.org/api/latest/index.html
标量,默认是float类型
1 const scalar = tf.scalar(5); 2 console.log('scalar ', scalar); 3 scalar.print()

向量
1 const vector = tf.tensor([1, 2, 3, 4]) 2 vector.print() 3 console.log(vector) 4 for (let i of [vector.mean(), vector.max(), vector.min(), vector.sum()]) { 5 i.print() 6 }

矩阵的加减乘除与np类似
1 const mat = tf.tensor([[1, 2, 3], [4, 5, 6]]) 2 mat.print() 3 const s = tf.scalar(2) 4 mat.add(s).print() 5 mat.mul(s).print() 6 const mat2 = tf.tensor([[1, 2, 3], [4, 5, 6]]) 7 mat2.add(mat).print() 8 mat2.sub(mat).print() 9 mat2.mul(mat).print()

乘法和转置
1 // 矩阵乘法 2 const a1 = tf.tensor([[1, 2], [3, 4]]) 3 const a2 = tf.tensor([[1, 2], [3, 4]]) 4 a1.matMul(a2).print() 5 a1.transpose().print()

1 // 单位矩阵 2 const e = tf.oneHot(tf.tensor1d([0, 1, 2],'int32'),3) 3 e.print() 4 const e2 = tf.eye(3) 5 e2.print() 6

线性取点
tf.linspace(0, 9, 20).print();
