📜  Tensorflow.js tf.layers getWeights() 方法

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

Tensorflow.js tf.layers getWeights() 方法

Tensorflow.js 是谷歌开发的一个开源库,用于在浏览器或节点环境中运行机器学习模型和深度学习神经网络。它还可以帮助开发人员用 JavaScript 语言开发 ML 模型,并且可以直接在浏览器或 Node.js 中使用 ML。

tf.layers.Layer.getWeights()函数用于获取张量的权重值。

句法:

getWeights( trainableOnly? )

参数:

  • trainableOnly(boolean):如果为真,该函数将仅返回可训练的权重值。

返回值:它返回一个 tf.Tensor

示例 1:

Javascript
// Creating a model
const model = tf.sequential();
  
// Adding layers
model.add(tf.layers.dense({units: 2, inputShape: [5]}));
model.add(tf.layers.dense({units: 3}));
  
model.compile({loss: 'categoricalCrossentropy', optimizer: 'sgd'});
  
// Printing the weights of the layers
model.layers[0].getWeights()[0].print()
model.layers[0].getWeights()[1].print()


Javascript
const tf = require("@tensorflow/tfjs")
  
// Creating a model
const model = tf.sequential();
  
// Adding layers
model.add(tf.layers.dense({units: 1, inputShape: [10]}));
model.add(tf.layers.dense({units: 3}));
  
// Setting new weights
model.layers[0].setWeights([tf.zeros([10, 1]), tf.ones([1])]);
  
model.compile({loss: 'categoricalCrossentropy', optimizer: 'sgd'});
  
// Printing the weights of the layers
model.layers[0].getWeights()[0].print()
model.layers[0].getWeights()[1].print()


输出:

Tensor
    [[-0.4756567, 0.2925433 ],
     [0.3505997 , -0.5043278],
     [0.5344347 , 0.2662918 ],
     [-0.1357223, 0.2435055 ],
     [-0.6059403, 0.1990891 ]]
Tensor
    [0, 0]

示例 2:

Javascript

const tf = require("@tensorflow/tfjs")
  
// Creating a model
const model = tf.sequential();
  
// Adding layers
model.add(tf.layers.dense({units: 1, inputShape: [10]}));
model.add(tf.layers.dense({units: 3}));
  
// Setting new weights
model.layers[0].setWeights([tf.zeros([10, 1]), tf.ones([1])]);
  
model.compile({loss: 'categoricalCrossentropy', optimizer: 'sgd'});
  
// Printing the weights of the layers
model.layers[0].getWeights()[0].print()
model.layers[0].getWeights()[1].print()

输出:

Tensor
    [[0],
     [0],
     [0],
     [0],
     [0],
     [0],
     [0],
     [0],
     [0],
     [0]]
Tensor
    [1]

参考:https://js.tensorflow.org/api/latest/#tf.layers.Layer.getWeights