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

文章目录

前言

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

相关推荐
码界筑梦坊1 小时前
282-基于Python的豆瓣音乐可视化分析推荐系统
开发语言·python·信息可视化·数据分析·flask·vue
LJianK11 小时前
java多态
java·开发语言·python
_Evan_Yao1 小时前
栈与队列:后进先出与先进先出的智慧
开发语言·python
J2虾虾1 小时前
Spring AI Alibaba - Skills 技能
人工智能·python·spring
带派擂总1 小时前
Python全栈开发 Day08_控制文件指针移动 异常捕获 推导式
python
XLYcmy1 小时前
面向Agent权限系统的快速审计工具
python·网络安全·ai·llm·飞书·agent·字节跳动
范范@2 小时前
Python进阶 多线程、生成器与协程
python
SilentSamsara2 小时前
SQLAlchemy 2.x:异步 ORM 与数据库迁移 Alembic 完整指南
开发语言·数据库·python·sql·青少年编程·oracle·fastapi
27669582922 小时前
京东随机变速滑块拼图验证码识别(京东E卡)
java·服务器·前端·python·京东滑块·京东变速滑块·京东e卡绑卡
weixin_468466852 小时前
支持向量机新手实战指南
人工智能·python·算法·机器学习·支持向量机