tensorflow2在获取中间层输出的时候出现层未连接错误 Layer sequential_19 is not connected, no input to return.

原始代码:

# 训练
# def train():
# 构建网络
network = keras.Sequential([
    keras.layers.Dense(128,'relu'), # ,input_shape=(28*28,)
    keras.layers.Dense(10)
])

network.build(input_shape=(None,28*28))
# network.summary()

network.compile(optimizer=keras.optimizers.Adam(lr=0.01),
              loss = tf.losses.CategoricalCrossentropy(from_logits=True),
              # loss = keras.losses.SparseCategoricalCrossentropy(from_logits=True),      # 用这个不用tf.one_hot()
              metrics=['accuracy']
)
# 训练
history = network.fit(train_data,epochs=2,validation_data=test_data,validation_freq=1)
plt.plot(history.history['accuracy'],label='accuracy')
plt.plot(history.history['val_accuracy'],label='val_accuracy')
plt.xlabel('Epoch')
plt.ylabel('accuracy')
plt.ylim([0.5,1])
plt.legend(loc='lower right')
plt.show()
tf.saved_model.save(network,'./model_save/fashion_10/') 
print("保存模型成功")     
print(network.input)

出现错误如下:

AttributeError                            Traceback (most recent call last)
/tmp/ipykernel_6301/226924856.py in 
     30 tf.saved_model.save(network,'./model_save/fashion_10/')
     31 print("保存模型成功")
---> 32 print(network.input)

~/anaconda3/envs/tf2/lib/python3.8/site-packages/tensorflow/python/keras/engine/base_layer.py in input(self)
   1805     """
   1806     if not self._inbound_nodes:
-> 1807       raise AttributeError('Layer ' + self.name +
   1808                            ' is not connected, no input to return.')
   1809     return self._get_node_attribute_at_index(0, 'input_tensors', 'input')

AttributeError: Layer sequential_19 is not connected, no input to return.

就是在最后一句获取模型输出的时候出现层之间未连接的错误,在网上查阅资料发现,我们下输入的第一层我们必须显示的指定输入维度,即使后面调用了build函数,我们也需要进行显示的指定输入shape

修改之后代码入下:

# 训练
# def train():
# 构建网络
network = keras.Sequential([
    keras.layers.Dense(128,'relu',input_shape=(28*28,)), # ,input_shape=(28*28,)
    keras.layers.Dense(10)
])

network.build(input_shape=(None,28*28))
# network.summary()

network.compile(optimizer=keras.optimizers.Adam(lr=0.01),
              loss = tf.losses.CategoricalCrossentropy(from_logits=True),
              # loss = keras.losses.SparseCategoricalCrossentropy(from_logits=True),      # 用这个不用tf.one_hot()
              metrics=['accuracy']
)
# 训练
history = network.fit(train_data,epochs=2,validation_data=test_data,validation_freq=1)
plt.plot(history.history['accuracy'],label='accuracy')
plt.plot(history.history['val_accuracy'],label='val_accuracy')
plt.xlabel('Epoch')
plt.ylabel('accuracy')
plt.ylim([0.5,1])
plt.legend(loc='lower right')
plt.show()
tf.saved_model.save(network,'./model_save/fashion_10/') 
print("保存模型成功")     
print(network.input)

tensorflow2在获取中间层输出的时候出现层未连接错误 Layer sequential_19 is not connected, no input to return._第1张图片
可以看到现在模型是没有错误了的,也可以正常的获取输入与输出了。

你可能感兴趣的:(Python,图像处理,keras,深度学习,tensorflow)