深度学习中需要固定的随机数种子

文章目录

前言

主要是3个:

  • random.seed()
  • numpy.random.seed()
  • torch.manual_seed()

三个的原理和作用都是相似的,所以接下来我只简单介绍random.seed()

random.seed()

作用

random()函数是用来产生伪随机数的,而random.seed()是用来确定随机数种子,使得每次产生的随机数是一样的。从而保证程序的可复现性。

例子

python 复制代码
import random

for i in range(5):
	# Any number can be used in place of '0'
	random.seed(0)

	# Generated random number will be between 1 to 1000
	print(random.randint(1, 1000))
"""
Output:
865
865
865
865
865
"""
  • 注意是需要在每次调用函数产生随机数之前都必须声明随机数种子,如下所示。
python 复制代码
import random

random.seed(3)
print(random.randint(1, 1000))

random.seed(3)
print(random.randint(1, 1000))

print(random.randint(1, 1000))

"""
Output:
244
244
607
"""

Reference

例子来源于:

https://www.geeksforgeeks.org/random-seed-in-python/

np.random.seed()

torch.manual_seed()

相关推荐
chao_78911 分钟前
更灵活方便的初始化、清除方法——fixture【pytest】
服务器·自动化测试·python·pytest
心情好的小球藻41 分钟前
Python应用进阶DAY9--类型注解Type Hinting
开发语言·python
都叫我大帅哥43 分钟前
LangChain加载HTML内容全攻略:从入门到精通
python·langchain
惜.己1 小时前
使用python读取json数据,简单的处理成元组数组
开发语言·python·测试工具·json
都叫我大帅哥2 小时前
Python的Optional:让你的代码优雅处理“空值”危机
python
曾几何时`4 小时前
基于python和neo4j构建知识图谱医药问答系统
python·知识图谱·neo4j
写写闲篇儿7 小时前
Python+MongoDB高效开发组合
linux·python·mongodb
杭州杭州杭州8 小时前
Python笔记
开发语言·笔记·python
路人蛃9 小时前
通过国内扣子(Coze)搭建智能体并接入discord机器人
人工智能·python·ubuntu·ai·aigc·个人开发
qiqiqi(^_×)9 小时前
卡在“pycharm正在创建帮助程序目录”
ide·python·pycharm