TensorFlow 2.11.0保存VGG16迁移学习模型时遇get_config()参数错误
解决TensorFlow 2.11.0保存VGG16迁移学习模型时的TypeError错误
错误信息
TypeError: get_config() missing 1 required positional argument: 'self'
问题原因
你的代码在编译模型时,错误地传入了损失函数的类本身而非实例。具体来说,在_prepare_full_model方法的full_model.compile调用中,loss=tf.keras.losses.CategoricalCrossentropy传递的是类对象,而Keras要求传入的是损失函数的实例(需要调用类生成对象)。当模型保存时需要序列化损失函数配置,类本身没有绑定实例,调用get_config()时就会缺少self参数,触发报错。
修复代码
修改_prepare_full_model方法中的compile部分,将损失函数改为实例形式(添加括号):
full_model.compile( optimizer=tf.keras.optimizers.SGD(learning_rate=learning_rate), loss=tf.keras.losses.CategoricalCrossentropy(), # 添加括号创建实例 metrics=["accuracy"] )
额外验证提示
- 确认损失函数匹配任务标签格式:如果标签是独热编码,使用
CategoricalCrossentropy()是正确的;如果是整数标签,需替换为SparseCategoricalCrossentropy()。 - 你已确认路径和模型实例有效性,这部分无需调整。
内容的提问来源于stack exchange,提问作者tenoob
相关产品推荐
相关产品推荐

