TensorFlow 2加载TF1 SavedModel出现变量警告的解决或屏蔽咨询
解决TensorFlow 2加载TF1 SavedModel时的Reference Variable警告
问题背景
你遇到的这个警告根源在于:TensorFlow 2.x默认使用Resource Variables,而你从TensorFlow Hub获取的TensorFlow 1.x构建的SavedModel,用的是旧版的Reference Variables,两者的兼容性差异触发了提示。另外你之前尝试的TF_CPP_MIN_LOG_LEVEL只能屏蔽TensorFlow底层C++的日志,对Python层的这个警告完全不起作用。
两种可行解决思路
思路一:彻底转换变量类型(推荐)
这个方法从根源解决警告,还能避免后续使用训练API时可能遇到的问题:
- 若加载本地SavedModel,可先加载再批量转换变量:
import tensorflow as tf def convert_ref_to_resource(obj): # 递归遍历模型结构,转换所有Reference Variable if isinstance(obj, tf.Variable) and obj.dtype._is_ref_dtype: return tf.Variable(obj.read_value()) elif isinstance(obj, dict): return {k: convert_ref_to_resource(v) for k, v in obj.items()} elif isinstance(obj, (list, tuple)): return type(obj)(convert_ref_to_resource(item) for item in obj) else: return obj # 加载原始模型 loaded_model = tf.compat.v1.saved_model.load_v2("path/to/your/savedmodel") # 完成变量转换 converted_model = convert_ref_to_resource(loaded_model)
- 若加载TensorFlow Hub的模型,操作更简单:用
tf.compat.v1.enable_resource_variables()上下文包裹加载过程,强制启用Resource Variables:
import tensorflow as tf import tensorflow_hub as hub with tf.compat.v1.enable_resource_variables(): model = hub.load("https://tfhub.dev/your/target/model")
思路二:精准屏蔽警告(仅消除提示)
如果暂时不需要修改变量类型,只想隐藏警告,可以通过TensorFlow的Python日志系统过滤:
import tensorflow as tf import logging # 获取TensorFlow的Python日志器 tf_logger = logging.getLogger('tensorflow') # 添加过滤器,专门过滤目标警告信息 class RefVarWarningFilter(logging.Filter): def filter(self, record): return "Unable to create a python object for variable" not in record.getMessage() tf_logger.addFilter(RefVarWarningFilter()) # 也可以更粗暴一点,直接把TensorFlow的日志级别设为ERROR(会屏蔽所有警告) # tf.compat.v1.logging.set_verbosity(tf.compat.v1.logging.ERROR)
注意:第二种方法只是隐藏警告,并没有修复变量兼容性问题,如果后续要对模型进行训练或微调,还是优先选择第一种方法更稳妥。
内容的提问来源于stack exchange,提问作者dendog
相关产品推荐
相关产品推荐

