You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

TensorFlow目标检测API训练报错:AttributeError无legacy属性

问题描述

环境配置:

  • Python=3.10.9
  • TensorFlow=2.8.0
  • CUDA=11.2
  • CuDNN=8.1

已完成TensorFlow目标检测API(TFOD)配置并通过验证脚本,但执行训练命令时出现报错。

执行的训练命令:

python Tensorflow\models\research\object_detection\model_main_tf2.py --model_dir=Tensorflow\workspace\models\my_ssd_mobnet --pipeline_config_path=Tensorflow\workspace\models\my_ssd_mobnet\pipeline.config --num_train_steps=2000

报错信息:

C:\Users\vetran2\pyproj\tfodnew\lib\site-packages\tensorflow_addons\utils\ensure_tf_install.py:53: UserWarning: Tensorflow Addons支持的TensorFlow版本为2.9.0及以上、2.12.0以下(不支持夜间版)。你当前使用的TensorFlow版本是2.8.0,不在支持范围内。部分功能可能正常工作,部分可能失效。如果遇到bug,请勿提交issue。如需使用经过测试的兼容配置,请升级TensorFlow版本或更换TensorFlow Addons版本。
Traceback (most recent call last):
File "D:\ObjectDetection\TensorFlow Object Detection\TFODCourse\Tensorflow\models\research\object_detection\model_main_tf2.py", line 31, in
from object_detection import model_lib_v2
File "C:\Users\vetran2\pyproj\tfodnew\lib\site-packages\object_detection-0.1-py3.10.egg\object_detection\model_lib_v2.py", line 31, in
from object_detection import model_lib
File "C:\Users\vetran2\pyproj\tfodnew\lib\site-packages\object_detection-0.1-py3.10.egg\object_detection\model_lib.py", line 35, in
from object_detection.builders import optimizer_builder
File "C:\Users\vetran2\pyproj\tfodnew\lib\site-packages\object_detection-0.1-py3.10.egg\object_detection\builders\optimizer_builder.py", line 25, in
from official.modeling.optimization import ema_optimizer
File "C:\Users\vetran2\pyproj\tfodnew\lib\site-packages\tf_models_official-2.11.3-py3.10.egg\official\modeling\optimization_init_.py", line 21, in
from official.modeling.optimization.ema_optimizer import ExponentialMovingAverage
File "C:\Users\vetran2\pyproj\tfodnew\lib\site-packages\tf_models_official-2.11.3-py3.10.egg\official\modeling\optimization\ema_optimizer.py", line 24, in
class ExponentialMovingAverage(tf.keras.optimizers.legacy.Optimizer):
AttributeError: module 'tensorflow.keras.optimizers' has no attribute 'legacy'

解决方案

1. 修复TensorFlow Addons版本兼容性

当前TensorFlow 2.8.0与已安装的TensorFlow Addons版本不匹配,卸载现有版本后安装兼容版本:

pip uninstall tensorflow-addons -y
pip install tensorflow-addons==0.17.0

2. 降级tf_models_official版本

tf.keras.optimizers.legacy是TensorFlow 2.10及以上版本才有的属性,你安装的tf_models_official 2.11.3版本与TF2.8.0不兼容,需要降级到对应版本:

pip uninstall tf-models-official -y
pip install tf-models-official==2.8.0

3. 验证修复

重新执行训练命令,确认报错消失。

内容的提问来源于stack exchange,提问作者Lim Chin Hong

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.31 18:05:22