pytorch随机种子

随机种子对于结果影响较大。在代码中固定了随机种子,固定随机种子主要用于调整超参数、改进模型结构、优化算法:

为什么使用相同的网络结构,跑出来的效果完全不同,用的学习率,迭代次数,batch size 都是一样?固定随机数种子是非常重要的。但是如果你使用的是PyTorch等框架,还要看一下框架的种子是否固定了。还有,如果你用了cuda,别忘了cuda的随机数种子

def seed_torch(seed):
    # random.seed(seed)
    os.environ['PYTHONHASHSEED'] = str(seed)
    np.random.seed(seed)
    torch.manual_seed(seed)
    torch.cuda.manual_seed(seed)
    torch.cuda.manual_seed_all(seed)
    torch.backends.cudnn.deterministic = True
    torch.backends.cudnn.benchmark = False
    torch.backends.cudnn.enabled = False

seed_torch(args_dic['seed'])

这里固定种子为42:
pytorch随机种子_第1张图片

 来看一下每一步是什么意思:

os.environ['PYTHONHASHSEED'] = str(args_dic['seed'])
#os.environ['环境变量名称']='新环境变量值'

If this variable is not set or set to random, a random value is used to seed the hashes of str, bytes and datetime objects.
If PYTHONHASHSEED is set to an integer value, it is used as a fixed seed for generating the hash() of the types covered by the hash randomization.
Its purpose is to allow repeatable hashing, such as for selftests for the interpreter itself, or to allow a cluster of python processes to share hash values.
The integer must be a decimal number in the range [0,4294967295]. Specifying the value 0 will disable hash randomization.

PYTHONHASHSEED,如果该环境变量被设定为 random ,相当于 -R 命令行参数。 Python 会用一个随机的种子来生成 str/bytes/datetime 对象的 hash 值。 如果该环境变量被设定为一个数字,它就被当作一个固定的种子来生成 str/bytes/datetime 对象的 hash 值。在深度学习模型训练中,为了在同样的数据集上获得可复现的训练结果
,通常把该值设定为一个固定值。

np.random.seed(seed)
#函数用于生成指定随机数。

参考链接:np.random.seed()函数 - 知乎

torch.manual_seed(seed)
#设置 CPU 生成随机数的 种子 ,方便下次复现实验结果。
torch.cuda.manual_seed(seed)
#设置当前GPU的随机数生成种子
torch.cuda.manual_seed_all(seed)
#设置所有GPU的随机数生成种子
torch.backends.cudnn.deterministic = True
#将这个 flag 置为True的话,每次返回的卷积算法将是确定的,即默认算法。如果配合上设置 Torch 的随机种子为固定值的话,应该可以保证每次运行网络的时候相同输入的输出是固定的
torch.backends.cudnn.benchmark = False
#设置 torch.backends.cudnn.benchmark=True 将会让程序在开始时花费一点额外时间,为整个网络的每个卷积层搜索最适合它的卷积实现算法,进而实现网络的加速。适用场景是网络结构固定(不是动态变化的),网络的输入形状(包括 batch size,图片大小,输入的通道)是不变的,其实也就是一般情况下都比较适用。反之,如果卷积层的设置一直变化,将会导致程序不停地做优化,反而会耗费更多的时间。
torch.backends.cudnn.enabled = False
#禁用cudnn

 参考链接:torch.backends.cudnn.benchmark_Wanderer001的博客-CSDN博客_torch.backends.cudnn.benchmark

 

你可能感兴趣的:(Python,pytorch,python,深度学习)