Python &引用;“层未连接”;如果模型是通过子分类构建的,则从自定义回调中访问中间层时出现问题
我有一个简单的模型,需要在自定义回调中访问中间层以获得中间预测Python &引用;“层未连接”;如果模型是通过子分类构建的,则从自定义回调中访问中间层时出现问题,python,tensorflow,machine-learning,keras,deep-learning,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.back
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.
在模型子分类的情况下,是什么导致了错误
TF版本:2.2.0看起来像一个潜在的bug,跟踪最新的更新..看起来像一个潜在的bug,跟踪最新的更新。。
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()])