Get the layers from one model and assign it to another model

旧街凉风 提交于 2019-12-04 06:22:11

问题


Given a model created using tf.sequential(), is it possible to get the layers and to use them to create another model using tf.model() ?

const model = tf.sequential();
model.add(tf.layers.dense({units: 32, inputShape: [50]}));
model.add(tf.layers.dense({units: 4}));

// get the layers
 layers
// use the layers to create another model
tf.model({layers})

回答1:


To get the layers of the model created using tf.sequential, one needs to use the property layers of the model

const model = tf.sequential();

// first layer
model.add(tf.layers.dense({units: 32, inputShape: [50]}));
// second layer
model.add(tf.layers.dense({units: 4}));

// get all the layers of the model
const layers = model.layers

// second model
const model2 = tf.model({
  inputs: layers[0].input, 
  outputs: layers[1].output
})

model2.predict(tf.randomNormal([1, 50])).print()
<html>
  <head>
    <!-- Load TensorFlow.js -->
    <script src="https://cdn.jsdelivr.net/npm/@tensorflow/tfjs@0.12.0"> </script>
  </head>

  <body>
  </body>
</html>

One can also use the apply method

const model = tf.sequential();

// first layer
model.add(tf.layers.dense({units: 32, inputShape: [50]}));
// second layer
model.add(tf.layers.dense({units: 4}));

var input = tf.randomNormal([1, 50])
var layers = model.layers
for (var i=0; i < layers.length; i++){
    var layer = layers[i]
    var output = layer.apply(input)
    input = output
    output.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/51483897/get-the-layers-from-one-model-and-assign-it-to-another-model

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