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

文章目录

前言

主要是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()

相关推荐
这里有鱼汤3 小时前
小白必看:QMT里的miniQMT入门教程
后端·python
TF男孩13 小时前
ARQ:一款低成本的消息队列,实现每秒万级吞吐
后端·python·消息队列
该用户已不存在18 小时前
Mojo vs Python vs Rust: 2025年搞AI,该学哪个?
后端·python·rust
站大爷IP20 小时前
Java调用Python的5种实用方案:从简单到进阶的全场景解析
python
用户8356290780511 天前
从手动编辑到代码生成:Python 助你高效创建 Word 文档
后端·python
c8i1 天前
python中类的基本结构、特殊属性于MRO理解
python
liwulin05061 天前
【ESP32-CAM】HELLO WORLD
python
Doris_20231 天前
Python条件判断语句 if、elif 、else
前端·后端·python
Doris_20231 天前
Python 模式匹配match case
前端·后端·python
这里有鱼汤1 天前
Python量化实盘踩坑指南:分钟K线没处理好,小心直接亏钱!
后端·python·程序员