Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting weights from tensorflow.js neural network

I have this sequential model:

this.model = tf.sequential()

this.model.add(tf.layers.dense({units : 16, useBias : true, inputDim : 7})) // input
this.model.add(tf.layers.dense({units : 16, useBias : true, activation: 'sigmoid'})) // hidden
this.model.add(tf.layers.dense({units : 3, useBias : true, activation: 'sigmoid'})) // hidden 2

I checked API for tensorflow.js, but there's nothing about getting weights(kernels) of neural network. So, how can I get weights and then change them, to apply new weights?(for unsupervised learning)

like image 682
ramazan793 Avatar asked Sep 13 '25 14:09

ramazan793


2 Answers

Here is a simple way to print off all the weights:

for (let i = 0; i < model.getWeights().length; i++) {
    console.log(model.getWeights()[i].dataSync());
}
like image 61
Brett L Avatar answered Sep 16 '25 12:09

Brett L


It seems like there is probably a simpler and cleaner way to do what you want, but regardless:

Calling this.model.getWeights() will give you an array of Variables that correspond to layer weights and biases. Calling data() on any of these array elements will return a promise that you can resolve to get the weights.

I haven't tried manually setting the weights, but there is a this.model.setWeights() method.

Goodluck.

like image 34
Dhruv Guliani Avatar answered Sep 16 '25 13:09

Dhruv Guliani