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

文章目录

前言

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

相关推荐
Eiceblue2 小时前
Python读取PDF:文本、图片与文档属性
数据库·python·pdf
weixin_527550402 小时前
初级程序员入门指南
javascript·python·算法
程序员的世界你不懂2 小时前
Appium+python自动化(十)- 元素定位
python·appium·自动化
CryptoPP3 小时前
使用WebSocket实时获取印度股票数据源(无调用次数限制)实战
后端·python·websocket·网络协议·区块链
树叶@3 小时前
Python数据分析7
开发语言·python
老胖闲聊4 小时前
Python Rio 【图像处理】库简介
开发语言·图像处理·python
码界奇点4 小时前
Python Flask文件处理与异常处理实战指南
开发语言·python·自然语言处理·flask·python3.11
浠寒AI5 小时前
智能体模式篇(上)- 深入 ReAct:LangGraph构建能自主思考与行动的 AI
人工智能·python
行云流水剑6 小时前
【学习记录】如何使用 Python 提取 PDF 文件中的内容
python·学习·pdf
心扬6 小时前
python生成器
开发语言·python