我在使用其功能API(继承自tf.keras.Model)定义的Keras模型时遇到此错误:
AttributeError:’Model’对象没有属性’_output_tensor_cache’
我该怎么办呢?下面是重现它的最小代码片段,然后是错误的完整堆栈跟踪.调用Model.fit()时会发生错误,甚至在它进入Model .__ call __()的实现之前.
我正在使用tensorflow-gpu(1.7.0).
import tensorflow as tf
import numpy as np
# Using Keras functional API
class Model(tf.keras.Model):
def __init__(self):
super(Model, self).__init__()
self.inp = tf.keras.layers.Input(shape=(8,))
self.fc1 = tf.keras.layers.Dense(32)
self.fc2 = tf.keras.layers.Dense(10)
def __call__(self, inputs, trainig=False):
y = self.inp(inputs)
y = self.fc1(y)
y = self.fc2(y)
return y
if __name__ == '__main__':
# Just a random dataset, to try out the code
X = np.random.rand(512, 8)
y = np.random.randint(0, 9, size=(512,))
model = Model()
model.compile(loss=tf.keras.losses.categorical_crossentropy,
optimizer=tf.keras.optimizers.Adadelta(),
metric=['accuracy'])
model.fit(X, y, batch_size=64, epochs=1, verbose=2, validation_split=.2)
错误堆栈跟踪:
Traceback (most recent call last):
File "/home/fanta/workspace/wine-quality/minimal.py", line 29, in <module>
model.fit(X, y, batch_size=64, epochs=1, verbose=2, validation_split=.2)
File "/home/fanta/.local/python3.5/lib/python3.5/site-packages/tensorflow/python/keras/_impl/keras/engine/training.py", line 1150, in fit
batch_size=batch_size)
File "/home/fanta/.local/python3.5/lib/python3.5/site-packages/tensorflow/python/keras/_impl/keras/engine/training.py", line 704, in _standardize_user_data
self._set_inputs(x)
File "/home/fanta/.local/python3.5/lib/python3.5/site-packages/tensorflow/python/keras/_impl/keras/engine/training.py", line 880, in _set_inputs
self._symbolic_set_inputs(inputs, training=training)
File "/home/fanta/.local/python3.5/lib/python3.5/site-packages/tensorflow/python/keras/_impl/keras/engine/training.py", line 999, in _symbolic_set_inputs
outputs = self.call(self.inputs[0], training=training)
File "/home/fanta/.local/python3.5/lib/python3.5/site-packages/tensorflow/python/keras/_impl/keras/engine/network.py", line 631, in call
if cache_key in self._output_tensor_cache:
AttributeError: 'Model' object has no attribute '_output_tensor_cache'
Process finished with exit code 1
最佳答案 创建常规模型有什么问题吗?
def createModel():
inputs = tf.keras.layers.Input(shape=(8,))
outputs = tf.keras.layers.Dense(32)(inputs)
outputs = tf.keras.layers.Dense(10)(outputs)
return tf.keras.Model(inputs,ouptuts)