从一个模型获取图层并将其分配给另一个模型 [英] Get the layers from one model and assign it to another model

查看:48
本文介绍了从一个模型获取图层并将其分配给另一个模型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给定使用 tf.sequential()创建的模型,是否可以获取图层并使用它们通过 tf.model()创建另一个模型?

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})

推荐答案

要获取使用 tf.sequential 创建的模型的图层,需要使用属性 layers 模型的

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>

也可以使用应用方法

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>

这篇关于从一个模型获取图层并将其分配给另一个模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆