Tensorflow.js 核心概念

2020-08-31 17:45 更新

TensorFlow.js 是一个用于机器智能的开源基于 WebGL 加速的 JavaScript 库。 它将高性能机器学习构建块带到您的指尖,使您能够在浏览器中训练神经网络或在推理模式下运行预先训练的模型。 有关安装/配置TensorFlow.js的指南,请参阅 Tensorflow.js 安装

TensorFlow.js 为机器学习提供低级构建模块,以及构建神经网络的高级 Keras 启发式 API。 我们来看看库的一些核心组件。

一、张量:tensors

tensor 是 TensorFlow.js 的数据中心单元:由一组数值组成的一维或多维数组。Tensor 实例的 shape 属性定义了这个数组的形状(例如:数组的每个维度有多少个值)。

最主要的 Tensor 构造函数是 tf.tensor 函数

// 2x3 Tensor
const shape = [2, 3]; // 可以看做是两行三列组成
const a = tf.tensor([1.0, 2.0, 3.0, 10.0, 20.0, 30.0], shape);
a.print(); 
// Output: [[1 , 2 , 3 ],
//          [10, 20, 30]]

// The shape can also be inferred:
const b = tf.tensor([[1.0, 2.0, 3.0], [10.0, 20.0, 30.0]]);
b.print();
// Output: [[1 , 2 , 3 ],
//          [10, 20, 30]]

但是,在构建低阶张量时,为了提高代码的可读性,我们推荐使用下列的函数:

// 0阶张量,即标量
tf.scalar(3.14).print(); // 3.140000104904175, 默认dtype 是 float32
tf.scalar(3.14, 'float32').print(); // 3.140000104904175
tf.scalar(3.14, 'int32').print(); // 3
tf.scalar(3.14, 'bool').print(); // 1

// 1阶张量
tf.tensor1d([1, 2, 3]).print(); // [1, 2, 3]

// 2阶张量
// Pass a nested array.
tf.tensor2d([[1, 2], [3, 4]]).print();
// Pass a flat array and specify a shape.
tf.tensor2d([1, 2, 3, 4], [2, 2]).print();
// ouput
//    [[1, 2],
//   [3, 4]]

// 3阶张量
// Pass a nested array.
tf.tensor3d([[[1], [2]], [[3], [4]]]).print();
// Pass a flat array and specify a shape.
tf.tensor3d([1, 2, 3, 4], [2, 2, 1]).print();
// output
//    [[[1],
//      [2]],

//     [[3],
//      [4]]]

// 4阶张量
// Pass a nested array.
tf.tensor4d([[[[1], [2]], [[3], [4]]]]).print();
// Pass a flat array and specify a shape.
tf.tensor4d([1, 2, 3, 4], [1, 2, 2, 1]).print();
// output
//    [[[[1],
//       [2]],

//      [[3],
//       [4]]]]

上述 5个低阶张量的表示方法,除了 scalar 和 tensor1d 两方法没有 shape 属性外,其它的都会传入values、shape、dtype 三个参数,注意有无 shape 传入时,values 的表示方式。 TensorFlow.js 也提供了把 Tensor 实例中的所有元素的值重置为 0 和 1 方法:

// 3x5 Tensor with all values set to 0
const zeros = tf.zeros([3, 5]);
// Output: [[0, 0, 0, 0, 0],
//          [0, 0, 0, 0, 0],
//          [0, 0, 0, 0, 0]]

// 2X2 Tensor with all values set to 1
tf.ones([2, 2]).print(); 
// output 
//     [[1, 1],
//     [1, 1]]

在 TensorFlow.js 中,张量值是不可改变的;一旦创建,你就不能改变它的值。相反,如果你执行 operations(ops) 操作,就可以生成新的张量值。

二、变量:variables

variables 是用一个张量值初始化的。不像张量(tensor),值不可改变。你可以使用 assign 方法给一个存在的变量(variable)分配一个新的张量:

const initialValues = tf.zeros([5]);
const biases = tf.variable(initialValues); // 初始化偏差(距离原点的截距或偏移)
biases.print(); // output: [0, 0, 0, 0, 0]

const updatedValues = tf.tensor1d([0, 1, 0, 1, 0]);
biases.assign(updatedValues); // update values of biases
biases.print(); // output: [0, 1, 0, 1, 0]

变量(variable)主要是用于在模型训练时,进行数据的保存和更新。

三、操作:operations(ops)

tensors 可以用保存数据,而 operations 可以操作数据。TensorFlow.js 提供了多种适用于张量的线性代数和机器学习的运算的 operations。由于张量是不可改变的,所以 operations 操作并不会改变 tensors 的值,而是返回新的张量。

 1、operations 提供了类似 square 等一元运算:

const x = tf.tensor1d([1, 2, Math.sqrt(2), -1]);
x.square().print();  // or tf.square(x)
// [1, 4, 1.9999999, 1]

const x = tf.tensor1d([1, 2, 4, -1]);
x.sqrt().print();  // or tf.sqrt(x)
// [1, 1.4142135, 2, NaN]

2、operations 提供了类似 add、sub 等二元运算:

const a = tf.tensor1d([1, 2, 3, 4]);
const b = tf.tensor1d([10, 20, 30, 40]);

a.add(b).print();  // or tf.add(a, b)
// [11, 22, 33, 44]

3、支持链式操作:

const e = tf.tensor2d([[1.0, 2.0], [3.0, 4.0]]);
const f = tf.tensor2d([[5.0, 6.0], [7.0, 8.0]])
const sq_sum = e.add(f).square();
sq_sum.print();
// Output: [[36 , 64 ],
//          [100, 144]]

// 所有的操作都暴露在函数的命名空间中,也可以进行下面操作,得到相同的结果
const sq_sum = tf.square(tf.add(e, f));

四、模型和层

从概念上看,一个模型就是一个函数,给定相应输入得到期望的输出。 在 TensorFlow.js 中,有两种创建模型的方式:

 1、通过使用 ops 直接创建模型

// Define function
function predict(input) {
  // y = a * x ^ 2 + b * x + c
  return tf.tidy(() => {
    const x = tf.scalar(input);

    const ax2 = a.mul(x.square());
    const bx = b.mul(x);
    const y = ax2.add(bx).add(c);

    return y;
  });
}

// Define constants: y = 2x^2 + 4x + 8
const a = tf.scalar(2);
const b = tf.scalar(4);
const c = tf.scalar(8);

// Predict output for input of 2
const result = predict(2);
result.print() // Output: 24

这是一个二元方程式求解的表示法。 

2、也可以使用高级 API tf.model 来构建以层定义的模型,这在深度学习中是一种常用的抽象形式 

下面简单的线性回归的定义为例:

const model = tf.sequential();
model.add(
  tf.layers.simpleRNN({
    units: 20,
    recurrentInitializer: 'GlorotNormal',
    inputShape: [80, 4]
  })
);

const optimizer = tf.train.sgd(LEARNING_RATE);
model.compile({optimizer, loss: 'categoricalCrossentropy'});
model.fit({x: data, y: labels)});

上述例子中通过创建一个线性回归模型,调用 simpleRNN 层,通过 sgd 优化算法训练,得到期望效果。

在 TensorFlow.js 中有很多不同类型的层(layers)表示法,例如 tf.layers.simpleRNN, tf.layers.gru, 和 tf.layers.lstm 等等。

五、内存管理:dispose 和 tf.tidy

由于,tensorFlow.js 使用了 GPU 加速数学运算,在使用张量和变量时,管理 GPU 的内存是必不可少的。 TensorFlow.js 提供了 dispose 和 tf.tidy 两个函数来帮助处理内存:

 1、dispose 

你可以调用一个张量或变量来清除和释放它的 GPU 内存。

const x = tf.tensor2d([[0.0, 2.0], [4.0, 6.0]]);
const x_squared = x.square();

x.dispose();
x_squared.dispose();

2、tf.tidy 

在做大量张量操作时,使用 dispose 可能很笨重。TensorFlow.js 提供了另一个功能 tf.tidy,它在 JavaScript 中扮演着类似的角色,除了 gpu 支持的张量。 

tf.tidy 会执行一个功能,清除任何创建的中间张量,释放它们的 GPU 内存。但它不会清除内部函数的返回值。

// tf.tidy takes a function to tidy up after
const average = tf.tidy(() => {

// tf.tidy 会清除在这个函数内的张量使用的所有GPU内存,而不是返回的张量。
// 即使在像下面这样的一个简短的操作序列中,也会创建一些中间的张量。所以,把 ops 放在 tidy 函数中是一个好的选择

  const y = tf.tensor1d([1.0, 2.0, 3.0, 4.0]);
  const z = tf.ones([4]);

  return y.sub(z).square().mean();
});

average.print() // Output: 3.5

使用 tf.tidy 将有助于防止应用程序中的内存泄漏。当内存被回收时,它也可以用来更小心地控制。

3、两个注意点

  • 传递给 tf.tidy 函数是同步的,不会返回一个 Promise 对象。建议保留更新UI的代码,或者在tf.tidy之外发出远程请求。
  • tf.tidy 不会清理变量。变量通常贯穿于机器学习模型的整个生命周期中,在 TensorFlow.js 中,即使是在 tf.tidy 里创建,js 也不会清理它们;但是,你可以手动调用 dispose。




以上内容是否对您有帮助:
在线笔记
App下载
App下载

扫描二维码

下载编程狮App

公众号
微信公众号

编程狮公众号