问题
Given the following model, how to print all layers values ?
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 output = denseLayer2.apply(denseLayer1.apply(input));
const model = tf.model({inputs: input, outputs: output});
model.predict(tf.ones([2, 5])).print();
<html>
<head>
<!-- Load TensorFlow.js -->
<script src="https://cdn.jsdelivr.net/npm/@tensorflow/tfjs@0.12.0"> </script>
</head>
<body>
</body>
</html>
回答1:
You could so something like
for(var i = 0; i < tf.layers.length; i++)
model.predict(tf.layers[i].value).print();
// OR
model.predict(tf.layers[i].inputs).print();
I don't know how is the structure of your array, but something like that could work.
回答2:
To print layers, one needs to define the layers to output in the model configuration, using, outputs
property. Using destructuring assignement on model.predict()
one could retrieve the intermediate layers to output
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]));
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>
来源:https://stackoverflow.com/questions/51483285/print-all-layers-output