torch的所有随机数官方已经整理在torch — PyTorch 1.10.0 documentation这个页面了,我又重新整理到了本blog中,用中文进行了部分解释,方便理解。

一、常用的

1、torch.normal()  正态分布

返回一个张量,包含了从指定均值mean和标准差std的离散正态分布中抽取的一组随机数。

①第一种形式

torch.normal(mean, std, generator=None, out=None) → Tensor

mean (Tensor) – the tensor of per-element means
std (Tensor) – the tensor of per-element standard deviations

generator (torch.Generator, optional) – a pseudorandom number generator for samplin
out (Tensoroptional) – the output tensor.

例子:

torch.normal(mean=torch.arange(1., 11.), std=torch.arange(1, 0, -0.1))返回:
tensor([  1.0425,   3.5672,   2.7969,   4.2925,   4.7229,   6.2134,8.0505,   8.1408,   9.0563,  10.0566])

②第二种形式

torch.normal(mean, std=1.0, out=None) → Tensor

例子:

torch.normal(mean=torch.arange(1., 6.))返回:
tensor([ 1.1552,  2.6148,  2.6535,  5.8318,  4.2361])

③第三种形式

torch.normal(mean, std, size, out=None) → Tensor
  • size (int...) – a sequence of integers defining the shape of the output tensor.

例子:

torch.normal(2, 3, size=(1, 4))返回:
tensor([[-1.3987, -1.9544,  3.6048,  0.7909]])

2、torch.rand()  均匀分布

torch.rand(*size, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False) → Tensor

返回一个张量,包含了从区间[0, 1)的均匀分布中抽取的一组随机数。张量的形状由参数sizes定义。

sizes (int…) - 整数序列,定义了输出张量的形状

out (Tensoroptional) – the output tensor.
dtype (torch.dtype, optional) – the desired data type of returned tensor. Default: if None, uses a global default (see torch.set_default_tensor_type()).
layout (torch.layout, optional) – the desired layout of returned Tensor. Default: torch.strided.
device (torch.device, optional) – the desired device of returned tensor. Default: if None, uses the current device for the default tensor type (see torch.set_default_tensor_type()). device will be the CPU for CPU tensor types and the current CUDA device for CUDA tensor types.
requires_grad (booloptional) – If autograd should record operations on the returned tensor. Default: False.

例子:

>>> torch.rand(4)
tensor([ 0.5204,  0.2503,  0.3525,  0.5673])>>> torch.rand(2, 3)
tensor([[ 0.8237,  0.5781,  0.6879],[ 0.3816,  0.7249,  0.0998]])

3、torch.randint()  均匀分布

torch.randint(low=0, high, size, generator=None, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False) → Tensor

产生一个tensor,tensor中的每个元素都是从[low, high)(前闭后开)中获得的。使用均匀分布。

参数同【2、torch.rand()】

例子:

>>> torch.randint(3, 5, (3,))
tensor([4, 3, 4])>>> torch.randint(10, (2, 2))
tensor([[0, 2],[5, 5]])>>> torch.randint(3, 10, (2, 2))
tensor([[4, 5],[6, 7]])

4、torch.randn()  正态分布

torch.randn(*size, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False) → Tensor

返回一个张量,包含了从标准正态分布(均值为0,方差为1,即高斯白噪声)中抽取的一组随机数。张量的形状由参数sizes定义。

参数同【2、torch.rand()】

例子:

>>> torch.randn(4)
tensor([-2.1436,  0.9966,  2.3426, -0.6366])>>> torch.randn(2, 3)
tensor([[ 1.5954,  2.8929, -1.0923],[ 1.1719, -0.4709, -0.1996]])

5、torch.randperm()  官方没有说是什么分布

torch.randperm(n, generator=None, out=None, dtype=torch.int64, layout=torch.strided, device=None, requires_grad=False, pin_memory=False) → Tensor

返回 0到n-1之间,所有数字的一个随机排列

参数同【2、torch.rand()】

pin_memory (booloptional) – If set, returned tensor would be allocated in the pinned memory. Works only for CPU tensors. Default: False.

例子:

>>> torch.randperm(4)
tensor([2, 1, 0, 3])

6、torch.rand_like()

torch.rand_like(input, dtype=None, layout=None, device=None, requires_grad=False, memory_format=torch.preserve_format) → Tensor

功能和【2、torch.rand()】完全相同,只是输出的shape和input.shape相同。

7、torch.randint_like()

torch.randint_like(input, low=0, high, \*, dtype=None, layout=torch.strided, device=None, requires_grad=False, memory_format=torch.preserve_format) → Tensor

功能和【3、torch.randint()】完全相同,只是输出的shape和input.shape相同。

8、torch.randn_like()

torch.randn_like(input, *, dtype=None, layout=None, device=None, requires_grad=False, memory_format=torch.preserve_format) → Tensor

功能和【4、torch.randn()】完全相同,只是输出的shape和input.shape相同。

二、不常用的

1、torch.bernoulli()

torch.bernoulli(inputgenerator=Noneout=None) →Tensor

从伯努利分布(二项分布)中提取二进制随机数(0或1)

输出的shape和input的shape相同,input中每个元素的值就是生成“输出中当前位置的元素值的”“伯努利分布的概率”,如下公式:

所以,input中每个元素的值都必须是[0, 1]之间的概率值。

例子:

>>> a = torch.empty(3, 3).uniform_(0, 1)  # generate a uniform random matrix with range [0, 1]
>>> a
tensor([[ 0.1737,  0.0950,  0.3609],[ 0.7148,  0.0289,  0.2676],[ 0.9456,  0.8937,  0.7202]])
>>> torch.bernoulli(a)
tensor([[ 1.,  0.,  0.],[ 0.,  0.,  0.],[ 1.,  1.,  1.]])>>> a = torch.ones(3, 3) # probability of drawing "1" is 1
>>> torch.bernoulli(a)
tensor([[ 1.,  1.,  1.],[ 1.,  1.,  1.],[ 1.,  1.,  1.]])
>>> a = torch.zeros(3, 3) # probability of drawing "1" is 0
>>> torch.bernoulli(a)
tensor([[ 0.,  0.,  0.],[ 0.,  0.,  0.],[ 0.,  0.,  0.]])

2、torch.multinomial()

torch.multinomial(inputnum_samplesreplacement=Falsegenerator=Noneout=None) → LongTensor

作用是对input的每一行做n_samples次取值,输出的张量是每一次取值时input张量对应行的下标。

If input is a vector, out is a vector of size num_samples.

If input is a matrix with m rows, out is an matrix of shape (m×num_samples).

input张量可以看成一个权重张量,每一个元素代表其在该行中的权重。如果有元素为0,那么在其他不为0的元素被取干净之前,这个元素是不会被取到的。

n_samples是每一行的取值次数,该值不能大于每一行的元素数,否则会报错。

replacement指的是取样时是否是有放回的取样,True是有放回,False无放回。

(参考:torch.multinomial()理解_monchin的博客-CSDN博客)

看官方给的例子:

>>> weights = torch.tensor([0, 10, 3, 0], dtype=torch.float) # create a tensor of weights
>>> torch.multinomial(weights, 2)
tensor([1, 2])>>> torch.multinomial(weights, 4) # ERROR!
RuntimeError: invalid argument 2: invalid multinomial distribution (with replacement=False,
not enough non-negative category to sample) at ../aten/src/TH/generic/THTensorRandom.cpp:320>>> torch.multinomial(weights, 4, replacement=True)
tensor([ 2,  1,  1,  1])

3、torch.poisson()

torch.poisson(inputgenerator=None) → Tensor

input的作用,类似于torch.bernoulli()中input的作用

input (Tensor) – the input tensor containing the rates of the Poisson distribution

>>> rates = torch.rand(4, 4) * 5  # rate parameter between 0 and 5
>>> torch.poisson(rates)
tensor([[9., 1., 3., 5.],[8., 6., 6., 0.],[0., 4., 5., 3.],[2., 1., 4., 2.]])

三、每个函数对应的原地运算

In-place random sampling

There are a few more in-place random sampling functions defined on Tensors as well. Click through to refer to their documentation:

  • torch.Tensor.bernoulli_() - in-place version of torch.bernoulli()

  • torch.Tensor.cauchy_() - numbers drawn from the Cauchy distribution

  • torch.Tensor.exponential_() - numbers drawn from the exponential distribution

  • torch.Tensor.geometric_() - elements drawn from the geometric distribution

  • torch.Tensor.log_normal_() - samples from the log-normal distribution

  • torch.Tensor.normal_() - in-place version of torch.normal()

  • torch.Tensor.random_() - numbers sampled from the discrete uniform distribution

  • torch.Tensor.uniform_() - numbers sampled from the continuous uniform distribution

四、设置随机数的种子

主要是torch.seed()、torch.manual_seed()、torch.initial_seed()

1、torch.initial_seed()
无参数
Returns the initial seed for generating random numbers as a Python long.
可以看出,这个函数只是返回一个python long类型的数值。

2、torch.manual_seed(seed)
Sets the seed for generating random numbers. Returns a torch.Generator object.
seed (int) 必须的参数,随机数种子。如果seed为负值,则会通过0xffff_ffff_ffff_ffff + seed映射为正值。seed的值的范围为 [-0x8000_0000_0000_0000, 0xffff_ffff_ffff_ffff]。

# 为CPU设置种子用于生成随机数,以使得结果是确定的
torch.manual_seed(args.seed)# torch.cuda.manual_seed()为当前GPU设置随机种子
if args.cuda:torch.cuda.manual_seed(args.seed)# 如果使用多个GPU,应该使用torch.cuda.manual_seed_all()为所有的GPU设置种子。
if args.cuda:torch.cuda.manual_seed_all(args.seed)(参考:https://blog.csdn.net/qq_40357974/article/details/100973233)

例子:

import torch
seed = 2021
torch.manual_seed(seed)
torch.manual_seed(seed)
# torch.cuda.manual_seed(seed)
a=torch.rand([3, 3])

 3、torch.seed()
无参数
Sets the seed for generating random numbers to a non-deterministic random number. Returns a 64 bit number used to seed the RNG.
这个函数的功能:就是产生一个随机数字,作为manual_seed()函数的种子,并执行manual_seed();可以看一下torch.seed()的代码。
RNG:随机数发生器(专业名词)

pytorch中的所有随机数(normal、rand、randn、randint、randperm) 以及 随机数种子(seed、manual_seed、initial_seed)相关推荐

  1. matlab中randint函数用法,matlab中rand randn randint函数的区别

    matlab中rand函数是产生0到1的随机分布 matlab中randn函数是产生标准正态分布 randint是产生整数随机数,默认为0和1 %%%%%%%%%%%rand%%%%%%%%%%%%% ...

  2. Matlab rand randn randint

    1.0matlab中rand函数是产生0到1的随机分布 2.0matlab中randn函数是产生标准正态分布 3.0randint是产生整数随机数,默认为0和1 1.0rand %%%%%%%%%%% ...

  3. 【matlab】随机函数生成随机排列:rand,randn,randi,randperm,randint

    1.rand() rand(n):生成0到1的均匀分布的n×n的随机数方阵 rand(m,n):生成0到1的m行n列的随机数矩阵 2.randn() randn(n)和randn(m,n)产生均值为0 ...

  4. Matlab 没有 randint,Matlab_learning_4(rand randn randint函数 )

    ||matlab 中 rand 函数是产生0到1的随机分布 1>.RAND:Uniformly distributed random numbers. 标准化分布的随机数 2>.RAND( ...

  5. Python的numpy库中rand(),randn(),randint(),random_integers()的使用

    1.numpy.random.rand() 用法是:numpy.random.rand(d0,d1,-dn) 以给定的形状创建一个数组,并在数组中加入在[0,1]之间均匀分布的随机样本. 用法及实现: ...

  6. Python的numpy库中rand(),randn(),randint(),random_integers()等random系函数的使用

    在使用Python进行数据处理时,往往需要用到大量的随机数据,那如何构造这么多数据呢?Python的第三方库numpy库中提供了random函数来实现这个功能. 本文将根据官方文档以及其他博友的博客一 ...

  7. ones eye rand randn diag randperm

    立即学习:https://edu.csdn.net/course/play/24708/278796?utm_source=blogtoedu 尝试 ones(4)            4*4 on ...

  8. pytorch 中的数据类型,tensor的创建

    pytorch中的数据类型 import torcha=torch.randn(2,3) b=a.type() print(b)#检验是否是该数据类型 print(isinstance(a,torch ...

  9. Pytorch中rand,randn, random以及normal的区别

    Pytorch中rand,randn, random以及normal的区别 torch.rand() torch.randn() torch.normal() torch.randperm() tor ...

最新文章

  1. usaco Home on the Range
  2. linux 编辑hosts 命令,linux下修改hostid
  3. opengl入门资料
  4. boost::python::slice相关的测试程序
  5. UML2.0 学习笔记
  6. Unicode 与 UTF-8 之间的转换
  7. 网易云课堂Java模拟面试笔记(31-40)
  8. 哪些Amazon erp是可以免费使用的?
  9. 联想小新520怎么样?对比当贝D3X哪款更值得买?
  10. Android面试线程,android 面试题 - 多线程部分
  11. 制定目标时需要遵循的SMART原则
  12. 原型工具Axure常见问题
  13. 43. TA镜像文件的签名
  14. 软件需求工程 高校教学平台 测试计划
  15. 中国IT产业人才分布地图
  16. 【产业互联网周报】网信办:不得利用算法影响网络舆论;华为任命丁耘为企业BG总裁;上海市布局数字经济、元宇宙等新赛道...
  17. create view 和 create or replace view的区别
  18. Unity3D消耗CPU过高解决办法
  19. html5 制作书架展示 PHP,简单做出HTML5翻页效果文字特效
  20. a55计算机主板,A55架构简介与A55主板赏析

热门文章

  1. Junit Test a getter
  2. 使用k-means及k-prototype对混合型数据集进行聚类分析
  3. MapReducer Counter计数器的使用,Combiner ,Partitioner,Sort,Grop的使用,
  4. 制作web3d动态产品展示的优点
  5. 利用python实现微信自动回复群发等操作(不需要登录网页版微信)
  6. AC/DC电源模块输入电压范围
  7. Cyberdog——小米四足机器人测评
  8. 编译内核 make modules_install报错make[1]: *** [arch/x86/crypto/aegis128-aesni.ko] Error 1 Makefile:1281: r
  9. C#接入steam内购
  10. webservice安全验证