PyTorch常用函数1

PyTorch常用函数1

1.生成一组随机数

1.1.函数

import torch
torch.rand()
torch.randn()
torch.randint()
torch.randperm()

1.2.torch.rand()

1.2.1.综述

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

1.2.2.参数

torch.rand(*sizes, out=None) → Tensor
#sizes (int...) - 整数序列,定义了输出张量的形状
#out (Tensor, optinal) - 结果张量
#直接一组数字输入即可

1.2.3.代码示例

ten = torch.rand(2,3)#注意,直接就是一个整数序列而已,不需要数组\列表形式
ten.shape
Out[18]: torch.Size([2, 3])
ten
Out[19]: 
tensor([[0.8582, 0.7170, 0.2270],
        [0.1360, 0.4222, 0.1338]])
#注意,取值范围,一定是[0,1),这个就很概率

1.3.torch.randn()

1.3.1.综述

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

1.3.2.参数

​ 与上同,这里解释一下高斯白噪声:简单的讲,就是瞬时值服从高斯分布,均值为0,方差为1,怎么说呢,这东西在通信领域确实存在,然后发现在很多时候,这个噪声用来模拟真实噪声很舒服,就来用了,重点是,这东西还挺简单的,就拿来做仿真测试了。

1.3.3.代码示例

ddd = torch.randn(2, 3, 4)#同理,也是直接输入数字就好了
print('{}\n{}'.format(ddd, ddd.shape))
========Output=======
tensor([[[ 0.6919,  1.6823, -0.2984,  1.5326],
         [-0.5526,  1.2831,  1.0159, -1.0033],
         [ 0.4496, -0.1958,  0.0327,  0.8110]],

        [[-0.4584,  0.8621, -0.6444, -0.9392],
         [ 1.0915, -0.4509, -1.5438, -1.3622],
         [ 1.8630,  0.6656, -0.9347,  1.0215]]])
#这个舒服用来看 size 还是很舒服的,上下分成了两块:最高的dim是2,之后次一级有三块,这个dim是3,最后的4就很好看出来了
torch.Size([2, 3, 4])

1.4.torch.randint()

1.4.1.综述

​ 返回一个张量:指定形状,具体取值在 [low,high)之间,随机的整数。

1.4.2.参数

randint(low=0, high, size, out=None) → Tensor 
#low和high必须是 int 类型,size我们一般可以使用tuple类型

1.4.3.代码示例

ddd = torch.randint(2, 4, (2, 3))
print('{}\n{}'.format(ddd, ddd.shape))
=======Output=======
tensor([[3, 2, 2],
        [2, 3, 3]])
#注意取值范围
torch.Size([2, 3])

1.4.4.Add:randint_like()

综述&参数:
randint_like(input, low=0, high) -> Tensor
Returns a tensor with the same shape as Tensor :attr:`input` filled with

​ 大致意思就是返回一个 Tensor,返回值的形状和 input 的 size 一致,每个元素的取值在 [low,high)之中。

代码示例:
ddd = torch.randint(2, 4, (2, 3))
ddd2 = torch.randint_like(ddd, 2, 5)
print('{}\n{}'.format(ddd2, ddd2.shape))
========Output========
tensor([[2, 4, 3],
        [4, 4, 2]])
torch.Size([2, 3])

1.5.torch.randperm()

1.5.1.综述

​ 其作用类似于python 里面的 shuffle , 返回从 [0,n-1] 的一组随机数列。注意,参数只能是 int ,不能是 tensor.

1.5.2.参数

torch,randperm(n) ->  LongTensor

1.5.3.代码示例

import torch
if __name__ == "__main__":
    print(torch.randperm(10))
    print(torch.randperm(10).type())
=====Output=====
tensor([6, 3, 1, 8, 5, 7, 0, 9, 4, 2])
torch.LongTensor

2.isinstance()

2.1.综述&参数

​ 实现检查数据是否是指定的数据类型。参数如下:

isinstance(data,data.type)

2.2.代码示例

import torch
a = torch.randperm(10)
isinstance(a,torch.FloatTensor)
Out[9]: False
a.type()
Out[10]: 'torch.LongTensor'
isinstance(a,torch.LongTensor)
Out[11]: True

3.torch.normal()

3.1.综述

​ 这个的作用是生成一组带有统计学特征的随机数:(可以指定这个随机数的方差和 mean )。使用需要结合 torch.arrange()函数。

3.2.torch.arange()

3.2.1.综述&参数

​ 返回区间 [start,end] ,步长为 step 的一组序列,注意,返回的参数不包括 end

torch.arange(start,end,step) -> torch.LongTensor

3.2.2.代码示例

torch.arange(-1,5,2)
Out[8]: tensor([-1,  1,  3])
torch.arange(-1,5,2).type()
Out[6]: 'torch.LongTensor'
#也可以是 FloatTensor
torch.arange(1,2,0.5)
Out[12]: tensor([1.0000, 1.5000])

3.2.3.补充.torch.range()

​ 这个函数的参数和 torch.arrange 类似,但是,区别在于,返回的区间包括 end:[start,end]

​ 根据 PyTorch 的官方解释,这个函数并不推荐被使用,而推荐使用 torch.arange() 作为替代

torch.range(1,2,0.5)
<ipython-input-11-d24a6212e6be>:1: UserWarning: torch.range is deprecated in favor of torch.arange and will be removed in 0.5. Note that arange generates values in [start; end), not [start; end].
  torch.range(1,2,0.5)
Out[11]: tensor([1.0000, 1.5000, 2.0000])

3.3.参数

torch.normal(means, std) ->  Tensor

​ means是均值,std是标准差,这个看起来没什么,但是参数类型却很有意思,我们可以参考官方的解释进行理解。

 normal() received arguments expected one of:
 * (Tensor mean, Tensor std, *, torch.Generator generator, Tensor out)
 * (Tensor mean, float std, *, torch.Generator generator, Tensor out)
 * (float mean, Tensor std, *, torch.Generator generator, Tensor out)
 * (float mean, float std, tuple of ints size, *, torch.Generator generator, Tensor out, torch.dtype dtype, torch.layout layout, torch.device device, bool pin_memory, bool requires_grad)

​ 并且其返回值一定是一个一维张量。

3.4.代码示例

3.4.1.简单示例

    Args:
        mean (Tensor): the tensor of per-element means
        std (Tensor): the tensor of per-element standard deviations
        generator (:class:`torch.Generator`, optional): a pseudorandom number generator for sampling
        out (Tensor, optional): the output tensor.    
    Example::    
        >>> 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])   
        
    Args:
        mean (float, optional): the mean for all distributions
        std (Tensor): the tensor of per-element standard deviations
        out (Tensor, optional): the output tensor.   
    Example::
    
        >>> torch.normal(mean=0.5, std=torch.arange(1., 6.))
        tensor([-1.2793, -1.0732, -2.0687,  5.1177, -1.2303])
    
    Args:
        mean (Tensor): the tensor of per-element means
        std (float, optional): the standard deviation for all distributions
        out (Tensor, optional): the output tensor
    Example::
        >>> torch.normal(mean=torch.arange(1., 6.))
        tensor([ 1.1552,  2.6148,  2.6535,  5.8318,  4.2361])
    
    Args:
        mean (float): the mean for all distributions
        std (float): the standard deviation for all distributions
        size (int...): a sequence of integers defining the shape of the output tensor.
        out (Tensor, optional): the output tensor.    
    Example::    
        >>> torch.normal(2, 3, size=(1, 4))
        tensor([[-1.3987, -1.9544,  3.6048,  0.7909]])
torch.normal(mean=torch.arange(1., 11.), std=torch.arange(1, 0, -0.1))
Out[15]: 
tensor([ 0.7201,  2.3695,  2.8230,  2.4502,  4.6258,  5.5251,  7.6323,  8.4068,
         8.8986, 10.0107])

3.4.2.一个理解

>>> torch.arange(1, 5)
Out[18]: tensor([1, 2, 3, 4])
>>> torch.arange(1, 0.6, -0.1)
tensor([1.0000, 0.9000, 0.8000, 0.7000])
>>>torch.normal(mean=torch.arange(1., 5.), std=torch.arange(1,0.6 , -0.1))
Out[29]: tensor([2.4046, 1.4440, 2.6715, 4.4209])
 2.4046 #是从均值为1,标准差为1的正态分布中随机生成的
 1.4440 #是从均值为2,标准差为0.9的正态分布中随机生成的
 2.6715	#........3,........0.8
 4.4209

​ 生成的张量中进行切片和索引,每一个元素的生成都是对应索引中的 means,std 的正态分布中的元素进行选取的。

3.4.3.一个进一步的引用

​ 我们通过 以下的变量创建可以得到,假设我们想要得到一个指定形状的张量,那么我们可以使用如下的办法:

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

​ 也可以结合 reshape 函数

a = torch.normal(mean=torch.arange(1., 11.), std=torch.arange(1, 0, -0.1))
torch.reshape(a,(2, 5))
Out[31]: 
tensor([[ 2.3706,  2.0997,  3.3471,  3.8318,  4.4080],
        [ 6.1979,  7.1602,  8.3320,  9.1737, 10.0239]])

4.torch.full()

4.1.综述&参数

​ 创建指定形状的 张量,并使用指定的元素填充,参数如下所示:

 torch.full(size, fill_value)

4.2.代码示例

>>> torch.full((2, 3), 3.141592)
tensor([[ 3.1416,  3.1416,  3.1416],
		[ 3.1416,  3.1416,  3.1416]])

5.torch.linspace()&torch.logspace()

5.1.综述&参数

​ 这两个函数的作用和 torch.arange() 其实非常的类似,都是创建一组等距的张量,不同的是这个控制的是返回的张量的长度(必等距),而不是相邻两个元素的差。

​ 参数如下:

torch.linspace(start,end,steps)
torch.logspace(start,end,steps,base = 10)

​ torch.linspace 创建 [start,end] 的共有 steps 个元素的张量,相邻元素之间,必等距。而 torch.logspace 所创建的张量,在 linspace 的基础上,会经过 base(底) ,取指数。具体可看实例。

5.2.代码示例

a = torch.linspace(1,3,3)
a
Out[35]: tensor([1., 2., 3.])
b = torch.logspace(1,3,3,base = 2)
b
Out[36]: tensor([2., 4., 8.])
#可以看到b[0] = base^a[0],b[1] = base^a[1],b[2] = base^a[2]

6.torch.eye()

6.1.综述&参数

​ 传入形状,创建一个对角矩阵,左上角->右下角的元素填充为1,其他元素填充为0.

eye(n, m=None)

​ 注意,只要参数不是 size ,就是一个很简单的整数序列,而不是 tuple\list,想想也是,对于元组等的处理,显然要比整数更加复杂。

6.2.代码示例

torch.eye(2,3)#注意,是一个整型的序列
Out[43]: 
tensor([[1., 0., 0.],
        [0., 1., 0.]])

torch.eye(3)
Out[44]: 
tensor([[ 1.,  0.,  0.],
        [ 0.,  1.,  0.],
        [ 0.,  0.,  1.]])
posted @ 2021-02-03 21:42  关河梦断  阅读(552)  评论(0)    收藏  举报