每层的权重和预测

Weights and predictions of each layer

我正在尝试创建一个简单的神经网络查看器,如下图所示。我可以获得经过训练的权重,但是当预测具有 运行 时,节点值存储在张量流 js 层中的何处?换句话说,我可以获得线值,但不能获得圆圈值。在一个简单的网络中,这些就像传递给 fit 方法的 x 和 y 一样简单。

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 获得每一层的预测