Getting weights from tensorflow.js neural network

Deadly 提交于 2020-01-02 17:31:18

问题


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)


回答1:


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.




回答2:


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());
}



回答3:


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


来源:https://stackoverflow.com/questions/50091466/getting-weights-from-tensorflow-js-neural-network

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!