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

使用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版本:
    import tensorflow as tf
    print(tf.__version__)
    
    若版本低于2.0,执行以下命令升级到稳定版:
    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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.01 14:45:58