如何修复Keras优化器报错:ValueError: decay参数已被弃用?
解决createSimpsonsModel中的decay弃用报错
问题原因
你使用的TensorFlow版本较新,其中Keras的新优化器已弃用decay参数,而createSimpsonsModel函数调用时传入了该参数,导致兼容性报错。
解决方法
方法一:使用旧版(legacy)优化器(匹配报错提示方案)
手动创建支持decay参数的旧版SGD优化器,再传入模型创建函数,替换原来的decay、learning_rate等参数:
import tensorflow as tf from tensorflow.keras.optimizers.legacy import SGD # 初始化旧版SGD优化器 optimizer = SGD(learning_rate=0.001, momentum=0.9, nesterov=True, decay=1e-7) # 创建模型时传入自定义优化器 model = canaro.models.createSimpsonsModel( IMG_SIZE=IMG_SIZE, channels=channels, output_dim=len(characters), loss='binary_crossentropy', optimizer=optimizer )
方法二:改用学习率调度器(符合新版TensorFlow规范)
移除decay参数,使用TensorFlow官方推荐的学习率调度器实现衰减效果:
import tensorflow as tf # 定义指数衰减学习率 initial_lr = 0.001 lr_schedule = tf.keras.optimizers.schedules.ExponentialDecay( initial_lr, decay_steps=100000, # 根据你的训练总步数调整 decay_rate=0.96, # 衰减速率,可根据需求微调 staircase=True ) # 初始化新版SGD优化器 optimizer = tf.keras.optimizers.SGD(learning_rate=lr_schedule, momentum=0.9, nesterov=True) # 创建模型 model = canaro.models.createSimpsonsModel( IMG_SIZE=IMG_SIZE, channels=channels, output_dim=len(characters), loss='binary_crossentropy', optimizer=optimizer )
额外提示
如果你的canaro版本较旧,也可以尝试升级到最新版,可能官方已经适配了新版TensorFlow的优化器参数。
内容的提问来源于stack exchange,提问作者Bubbles
相关产品推荐
相关产品推荐

