如果模型是通过子类构建的,则从自定义回调中访问中间层时出现“层未连接”问题

时间:2020-07-01 01:36:19

标签: python tensorflow machine-learning keras deep-learning

我有一个简单的模型,需要访问自定义回调中的中间层以获得中间预测。

import tensorflow as tf
import numpy as np

X = np.ones((8,16))
y = np.sum(X, axis=1)

class CustomCallback(tf.keras.callbacks.Callback):
    def on_epoch_end(self, epoch, logs=None):
        get_output = tf.keras.backend.function(
            inputs = self.model.layers[0].input,
            outputs = self.model.layers[1].output
        )
        print("\nLayer output: ", get_output(X))

如果我通过如下子类化构建模型:

class Model(tf.keras.Model):
    def build(self, input_shape):
        self.dense1 = tf.keras.layers.Dense(units=32)
        self.dense2 = tf.keras.layers.Dense(units=1)
        
    def call(self, input_tensor):
        x = self.dense1(input_tensor)
        x = self.dense2(x)
        return x

model = Model()
model.compile(optimizer='adam',loss='mean_squared_error', metrics='accuracy')
model.fit(X,y, epochs=2, callbacks=[CustomCallback()])

我收到以下错误:

<ipython-input-8-bab75191182e> in on_epoch_end(self, epoch, logs)
      2     def on_epoch_end(self, epoch, logs=None):
      3         get_output = tf.keras.backend.function(
----> 4             inputs = self.model.layers[0].input,
      5             outputs = self.model.layers[1].output
      6         )
.
.
AttributeError: Layer dense is not connected, no input to return.

如果我使用如下所示的功能性API构建模型,则它会按预期工作。

initial = tf.keras.layers.Input((16,))
x = tf.keras.layers.Dense(units=32)(initial)
final = tf.keras.layers.Dense(units=1)(x)

model = tf.keras.Model(initial, final)
model.compile(optimizer='adam',loss='mean_squared_error', metrics='accuracy')
model.fit(X,y, epochs=2, callbacks=[CustomCallback()])

是什么原因导致模型子分类错误?

TF版本:2.2.0

0 个答案:

没有答案