我正在尝试创建一个简单的神经网络查看器,如下图所示。我可以获得训练后的权重,但是当预测运行时,节点值存储在 tensorflow js层的哪里?换句话说,我可以得到线的值,但不能得到圈出来的值。在一个简单的网络中,这些就像传递给 fit 方法的 x 和 y 一样简单。
1 回答
1
getWeigths允许检索层的权重
使用tf.model,可以输出每一层的预测
const input = tf.input({shape: [5]});
const denseLayer1 = tf.layers.dense({units: 10, activation: 'relu'});
const denseLayer2 = tf.layers.dense({units: 2, activation: 'softmax'});
const output1 = denseLayer1.apply(input);
const output2 = denseLayer2.apply(output1);
const model = tf.model({inputs: input, outputs: [output1, output2]});
const [firstLayer, secondLayer] = model.predict(tf.ones([2, 5]));
console.log(denseLayer1.getWeights().length) // 2 W and B for a dense layer
denseLayer1.getWeights()[1].print()
console.log(denseLayer2.getWeights().length) // also 2
// output of each layer WX + B
firstLayer.print();
secondLayer.print()
<html>
<head>
<!-- Load TensorFlow.js -->
<script src="https://cdn.jsdelivr.net/npm/@tensorflow/tfjs@0.12.0"> </script>
</head>
<body>
</body>
</html>
也可以使用tf.sequential()
const model = tf.sequential();
// first layer
model.add(tf.layers.dense({units: 10, inputShape: [4]}));
// second layer
model.add(tf.layers.dense({units: 1}));
// get all the layers of the model
const layers = model.layers
layers[0].getWeights()[0].print()
<html>
<head>
<!-- Load TensorFlow.js -->
<script src="https://cdn.jsdelivr.net/npm/@tensorflow/tfjs@0.12.0"> </script>
</head>
<body>
</body>
</html>
但是,使用模型配置中传递的参数时,tf.sequential无法像tf.model使用output传递的参数那样获得每一层的预测。
于 2019-01-21T20:22:06.710 回答
