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

文章目录

前言

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

相关推荐
Gyoku Mint2 分钟前
深度学习×第4卷:Pytorch实战——她第一次用张量去拟合你的轨迹
人工智能·pytorch·python·深度学习·神经网络·算法·聚类
郭庆汝6 小时前
pytorch、torchvision与python版本对应关系
人工智能·pytorch·python
思则变9 小时前
[Pytest] [Part 2]增加 log功能
开发语言·python·pytest
漫谈网络9 小时前
WebSocket 在前后端的完整使用流程
javascript·python·websocket
try2find11 小时前
安装llama-cpp-python踩坑记
开发语言·python·llama
博观而约取12 小时前
Django ORM 1. 创建模型(Model)
数据库·python·django
精灵vector13 小时前
构建专家级SQL Agent交互
python·aigc·ai编程
Zonda要好好学习13 小时前
Python入门Day2
开发语言·python
Vertira13 小时前
pdf 合并 python实现(已解决)
前端·python·pdf
太凉13 小时前
Python之 sorted() 函数的基本语法
python