Open In App

Tensorflow.js tf.layers getWeights() Method

Improve
Improve
Like Article
Like
Save
Share
Report

Tensorflow.js is an open-source library developed by Google for running machine learning models and deep learning neural networks in the browser or node environment. It also helps the developers to develop ML models in JavaScript language and can use ML directly in the browser or in Node.js.

The tf.layers.Layer.getWeights() function is used to get the values of the weights of a tensor.

Syntax:

getWeights( trainableOnly? )

Parameters:

  • trainableOnly(boolean): If true, the function will return only the values of weights that are trainable.

Return Value: It returns a tf.Tensor

Example 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()


Output:

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

Example 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()


Output:

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

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



Last Updated : 22 Apr, 2022
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads