运行model_main_tf2.py报tensorflow compat模块无v2属性错误如何解决
问题排查记录
报错场景
运行目标检测模型训练命令:
!python 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_training_steps=200
执行后抛出错误,核心报错信息为:tensorflow._api.v1.compat.v2.compat' has no attribute 'v2
完整错误追踪栈:
Traceback (most recent call last): File "models/research/object_detection/model_main_tf2.py", line 113, in <module> tf.compat.v1.app.run() File "/tensorflow-1.15.2/python3.7/tensorflow_core/python/platform/app.py", line 40, in run _run(main=main, argv=argv, flags_parser=_parse_flags_tolerate_undef) File "/usr/local/lib/python3.7/dist-packages/absl/app.py", line 312, in run _run_main(main, args) File "/usr/local/lib/python3.7/dist-packages/absl/app.py", line 258, in _run_main sys.exit(main(argv)) File "models/research/object_detection/model_main_tf2.py", line 101, in main strategy = tf.compat.v2.distribute.MirroredStrategy() File "/tensorflow-1.15.2/python3.7/tensorflow_core/python/util/module_wrapper.py", line 193, in __getattr__ attr = getattr(self._tfmw_wrapped_module, name) AttributeError: module 'tensorflow._api.v1.compat.v2.compat' has no attribute 'v2'
当前环境配置
当前配置TensorFlow Object Detection API的代码如下,环境强制指定使用TensorFlow 1.x版本:
%tensorflow_version 1.x import os import pathlib # 若models仓库不存在则克隆 if "models" in pathlib.Path.cwd().parts: while "models" in pathlib.Path.cwd().parts: os.chdir('..') elif not pathlib.Path('models').exists(): !git clone --depth 1 https://github.com/cloud-annotations/models !pip install cloud-annotations==0.0.4 !pip install tf_slim !pip install lvis !pip install --no-deps tensorflowjs==1.4.0 %cd /content/drive/MyDrive/Object_Detecation/models/research !protoc object_detection/protos/*.proto --python_out=. pwd = os.getcwd() os.environ['PYTHONPATH'] += f':{pwd}:{pwd}/slim' !python object_detection/builders/model_builder_tf2_test.py
报错根因:版本不匹配。当前环境为TensorFlow 1.x,却运行了仅支持TensorFlow 2.x的训练脚本
model_main_tf2.py,TF1.x的compat.v2模块不包含脚本调用的TF2专属分布式策略接口,最终触发属性不存在错误。
解决方案
二选一即可:
- 方案1(推荐,匹配现有TF2训练脚本):切换到TensorFlow 2.x环境
- 将配置首行的
%tensorflow_version 1.x替换为%tensorflow_version 2.x,本地环境则直接卸载TF1.x,安装2.5~2.10区间的稳定TF2版本(该区间对Object Detection API兼容性最佳) - 重新执行依赖安装流程,移除
tensorflowjs==1.4.0的旧版本限制,安装适配TF2的tensorflowjs版本 - 重新执行proto编译、PYTHONPATH配置步骤,运行
model_builder_tf2_test.py确认所有测试用例通过后,再执行训练命令即可
- 将配置首行的
- 方案2(保留TF1.x环境):替换为TF1兼容的训练脚本
- 不要运行
model_main_tf2.py,改用同目录下TF1版本的训练脚本model_main.py - 替换pipeline配置文件为TF1兼容格式,不可直接复用TF2版本的
pipeline.config - 重新走TF1版本的API验证流程后再启动训练
- 不要运行
内容的提问来源于stack exchange,提问作者None -
相关产品推荐
相关产品推荐

