Reputation: 689
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)
Upvotes: 4
Views: 4169
Reputation: 1698
To access the weights (kernel and bias) of the first dense layer:
const model = tf.sequential();
model.add(tf.layers.dense({units: 4, inputShape: [8]}));
model.add(tf.layers.dense({units: 4}));
model.compile({ optimizer: 'sgd', loss: 'meanSquaredError' });
// kernel:
model.layers[0].getWeights()[0].print()
// bias:
model.layers[0].getWeights()[1].print()
Upvotes: 1
Reputation: 105
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());
}
Upvotes: 3
Reputation: 36
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.
Upvotes: 2