我使用以下代码加载 imagenet 预训练的 VGG19 模型并适合我的自定义数据集。
from keras.applications.vgg19 import VGG19
optim = tf.keras.optimizers.RMSprop(momentum=0.9)
vgg19 = VGG19(include_top=False, weights='imagenet', input_tensor=tf.keras.layers.Input(shape=(224, 224, 3)))
vgg19.trainable = False
# x = keras.layers.GlobalAveragePooling2D()(model_vgg19_pt.output)
x = keras.layers.Flatten()(vgg19.output)
output = keras.layers.Dense(n_classes, activation='softmax')(x)
model_vgg19_pt = keras.models.Model(inputs=[vgg19.input], outputs=[output])
model_vgg19_pt.compile(optimizer=optim,
loss='categorical_crossentropy', metrics=['categorical_accuracy'])
callback = tf.keras.callbacks.LearningRateScheduler(scheduler)
model_vgg19_pt.fit(x_train, y_train, batch_size=20,
epochs=50, callbacks=[callback]
)
在 model.fit() 行上,我收到以下错误
KeyError: '优化器无法识别变量dense_1/kernel:0。这通常意味着您尝试调用优化器来分别更新模型的不同部分。请在训练循环之前调用
并提供可训练变量的完整列表,或使用旧版优化器 `tf.keras.optimizers.legacy.{self.class.name}.'optimizer.build(variables)
这是什么意思以及如何解决它?
我遇到了同样的错误
keras.applications.inception_v3
同样,当使用相同的实现方法时。
此外,这是在tensorflow cpu上使用jupyter笔记本文件,但是当在安装了tensorflow-gpu的远程计算机上运行时,我收到这些错误。
这适用于优化器 SGD,但不适用于 RMSprop。为什么?
补充 使用这个:
model_vgg19_pt.compile(optimizer=tf.keras.optimizers.RMSprop(momentum=0.9),
loss='categorical_crossentropy', metrics=['categorical_accuracy'])
而不是上面使用的作品。 但是有人可以解释一下为什么吗....
使用遗留优化器
tf.keras.optimizers.legacy.SGD(learning_rate=0.1)
当我使用tensorflow==2.11.0从Python 3.9.5升级到3.10.9时,
我在 Keras Sequential 模型中遇到了类似的错误
KeyError: 'The optimizer cannot recognize variable dense_24/kernel:0. This usually means you are trying to call the optimizer to update different parts of the model separately. Please call `optimizer.build(variables)` with the full list of trainable variables before the training loop or use legacy optimizer `tf.keras.optimizers.legacy.{self.__class__.__name__}.'
将库重命名为旧版优化器
来自
from tensorflow.keras.optimizers import SGD
到
from tensorflow.keras.optimizers.legacy import SGD
它起作用了。 #niran 评论是正确的
您安装了哪个版本的 Tensorflow GPU? TensorFlow 2.10 是在本机 Windows 上支持 GPU 的最后一个 TensorFlow 版本。请按照 GPU 支持的所有硬件/软件要求检查安装 TensorFlow 的链接。
回调中的 LearningRateScheduler 参数未定义,您在模型编译时传递。
从 model.fit() 中删除回调后,我能够训练模型。 (附上要点供大家参考)