Python随机数
random随机数
在导入random模块时,会在模块内部执行语句_inst = Random(),其中类Random为模块random内部定义的类。模块random提供的seed、randint和choice等函数为_inst实例的成员函数。
seed需为非负整数
numpy随机数
在导入numpy.random模块时,会在模块numpy.random.mtrand内部执行语句_rand: RandomState,其中类RandomState为模块numpy.random.mtrand内部定义的类。模块numpy.random提供的seed、randint和choice等函数为_rand实例的成员函数。
seed需为非负整数
cupy随机数
同numpy随机数
torch随机数
在导入torch模块时,会在模块torch._C.__init__和torch.cuda.__init__内部分别执行语句default_generator:Generator和default_generators:Tuple[torch._C.Generator]=(),其中类Generator为模块torch._C.__init__内部定义的类。模块torch提供的seed、manual_seed和initial_seed等函数为default_generator实例的成员函数。模块torch.cuda提供的seed、manual_seed和manual_seed_all等函数会调用default_generators元组中对应实例的对应成员函数。
import os
import random
import numpy as np
import torch
# 为了禁止hash随机化,用于python中的某些hash操作
os.environ['PYTHONHASHSEED'] = str(seed)
# 为random设置随机种子
random.seed(seed)
# 为numpy设置随机种子
np.random.seed(seed)
# 为torch设置随机种子
torch.manual_seed(seed)
torch.cuda.manual_seed(seed)
# if you are using multi-GPU.
torch.cuda.manual_seed_all(seed)
# cudnn中对卷积操作进行了优化,牺牲了精度来换取计算效率
torch.backends.cudnn.benchmark = False
torch.backends.cudnn.deterministic = True
若seed为负整数,则值会被转为对应的64位无符号整数
tensorflow随机数
tf.random.set_seed用法_仁义礼智信达的博客-优快云博客
tensorlow随机种子包括图级种子和操作级种子。图级种子使用tensorflow,random.set_seed()设置,操作级种子在声明随机变量时通过传入seed参数设置。
难以手动为
tensorflow声明一个随机数生成器实例。
文章介绍了如何在Python的random、numpy、cupy(类似numpy)、torch和tensorflow中设置随机数种子,确保生成的随机数序列可重复。重点提到了每个库中seed函数的使用方法和注意事项。
314

被折叠的 条评论
为什么被折叠?



