如何修改TensorFlow1.x代码使其兼容TensorFlow2.x并适配ResNet152
报错原因
TensorFlow 2.x 对生成器返回值的解析逻辑与1.x版本存在差异:
- Keras 2.2.4 / TF1.x 会识别生成器返回的嵌套列表,将第一层第一个元素的所有子项识别为模型输入,第一层第二个元素识别为标签
- TF2.x 版本会直接将生成器返回的最外层可迭代对象的所有元素,全部解析为独立的输入张量,因此你原代码返回的
[[feature, sequence], description]会被拆分为3个独立张量,和模型要求的2个输入不匹配,触发报错。
修复代码
1. 修改生成器返回结构
将输入部分用元组包裹,符合TF2.x的解析规则:
def data_generator(images, descriptions, resnet152) : while True : for i in range(0, len(images)) : feature = resnet152.predict(images[i]); #variable description includes what the people are doing in this image : ["a man is cooking"] description = descriptions[i]; #sequence includes things like ["a"ID, "man"ID, "is"ID, "cooking"ID], "xxx"ID is a digit of a word "xxx" sequence = make_sequence(description); # 仅修改yield行,用元组包裹输入集合 yield ((feature, sequence), description);
2. 适配TF2.x训练API
fit_generator 已在TF2.x中被弃用,直接使用fit方法即可,参数无需调整:
resnet_model = ResNet152(); model = my_model(); generator = data_generator(images, descriptions, resnet_model); # 替换fit_generator为fit model.fit(generator, epochs = 1, verbose = 1, steps_per_epoch = 1);
可选优化建议
生成器内每次循环调用模型推理特征的效率极低,建议提前将所有图像的ResNet152特征一次性推理完成后存储,训练时直接读取预计算的特征,可大幅提升训练速度。
内容的提问来源于stack exchange,提问作者Jonny0201
相关产品推荐
相关产品推荐

