📜  Tensorflow.js tf.Sequential 类 .add() 方法

📅  最后修改于: 2022-05-13 01:56:52.796000             🧑  作者: Mango

Tensorflow.js tf.Sequential 类 .add() 方法

Tensorflow.js 是由谷歌开发的开源库,用于在浏览器或节点环境中运行机器学习模型以及深度学习神经网络。

.add()函数用于将层原型附加到层堆栈的最顶部。

句法:

add(layer)

参数:

  • layer:它是 layer 的声明原型,类型为 tf.layers.Layer。

返回值:返回void。

示例 1:

Javascript
// Importing the tensorflow.js library
import * as tf from "@tensorflow/tfjs"
  
// Defining model
const modl = tf.sequential();
  
// Calling add() method
modl.add(tf.layers.dense({units: 4, inputShape: [1]}));
modl.add(tf.layers.dense({units: 2, stimulation: 'relu'}));
modl.add(tf.layers.dense({units: 1, stimulation: 'relu'}));
  
// Printing output by calling predict
// method
modl.predict(tf.truncatedNormal([4, 1])).print();


Javascript
// Importing the tensorflow.js library
import * as tf from "@tensorflow/tfjs"
  
// Defining model
const modl = tf.sequential();
  
// Calling add() method
modl.add(tf.layers.maxPooling2d({batchInputShape:[1, 2, 3, 4],
     poolSize: 1,
     strides: 2}));
  
// Printing output by calling predictOnBatch
// method
modl.predictOnBatch(tf.randomNormal([1, 2, 3, 4])).print();


输出:在这里, layers.dense()方法用于生成完全密集的层, predict()方法用于生成有利于输入实例的输出预测,而truncatedNormal()方法用于生成具有从截断的正态分布中采样的值的帮助。

Tensor
    [[0.1687946 ],
     [-0.1382875],
     [-0.3894148],
     [0.1748937 ]]

示例 2:

Javascript

// Importing the tensorflow.js library
import * as tf from "@tensorflow/tfjs"
  
// Defining model
const modl = tf.sequential();
  
// Calling add() method
modl.add(tf.layers.maxPooling2d({batchInputShape:[1, 2, 3, 4],
     poolSize: 1,
     strides: 2}));
  
// Printing output by calling predictOnBatch
// method
modl.predictOnBatch(tf.randomNormal([1, 2, 3, 4])).print();

输出:这里, layers.maxpooling2d()方法有助于通过空间数据进行最大池化任务, predictOnBatch()方法 用于预测有利于特定的一组实例,以及randomNormal()方法 借助从正态分布中采样的值来生成 tf.Tensor。

Tensor
    [[[[0.9905863, 1.6736914, -1.2367558, -0.3343732],
       [0.2533375, 0.5539166, 0.6961272 , -0.3252741]]]]

参考: https://js.tensorflow.org/api/latest/#tf.Sequential.add