使用tf.random.set_seed仍报错:tensorflow模块无set_random_seed属性
解决TensorFlow设置随机种子报错问题
问题原因
你遇到的AttributeError本质是当前使用的TensorFlow版本与调用的API不匹配:
tf.random.set_seed是TensorFlow 2.x版本引入的标准API- 若你的环境是TensorFlow 1.x,根模块下仅提供
tf.set_random_seed方法,不存在tf.random.set_seed;部分早期不稳定的TF2.x版本也可能存在API未完善的情况。
解决方案
方案1:匹配TF版本修改代码
- 如果你使用的是TensorFlow 1.x,直接将代码替换为:
def __init__(self, log_name, heatmap_size, image_size, loss_type = 'SCE', is_training = True): tf.set_random_seed(0) - 若你确认要使用TF2.x的API风格,先检查当前TF版本:
若版本低于2.0,执行以下命令升级到稳定版:import tensorflow as tf print(tf.__version__)pip install --upgrade tensorflow
方案2:兼容TF1.x和TF2.x的通用写法
如果需要代码同时适配两个版本,可以加入版本判断逻辑:
import tensorflow as tf def __init__(self, log_name, heatmap_size, image_size, loss_type = 'SCE', is_training = True): if tf.__version__.startswith('2'): tf.random.set_seed(0) else: tf.set_random_seed(0)
内容的提问来源于stack exchange,提问作者Test
相关产品推荐
相关产品推荐

