【问题标题】:Get the layers from one model and assign it to another model从一个模型中获取层并将其分配给另一个模型
【发布时间】:2018-07-23 16:59:29
【问题描述】:

给定一个使用tf.sequential() 创建的模型,是否可以获取图层并使用它们创建另一个使用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})

【问题讨论】:

    标签: javascript tensorflow.js


    【解决方案1】:

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

    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>

    也可以使用apply方法

    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>

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-01-28
      • 1970-01-01
      • 2017-07-06
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多