我正在尝试创建一个简单的神经网络查看器,如下图所示。我可以得到训练后的权重,但是运行预测后,节点值存储在tensorflow js 层中的什么位置?换句话说,我可以获取线值,但不能获取带圆圈的值。在简单的网络中,它们就像传递给fit方法的x和y一样简单。
答案 0 :(得分: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
那样获得对每一层的预测