Pytorch(3)- torch.mean(),.randn(),.squeeze(),.pow()

torch常用的一些函数
1 torch.randn()
2 torch.mean()
3 torch.squeeze()
4 torch.pow()求幂次运算
1 torch.randn()
产生大小为指定的,正态分布的采样点,数据类型是tensor

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]])

2 torch.mean()
torch.mean(input) 输出input 各个元素的的均值,不指定任何参数就是所有元素的算术平均值,指定参数可以计算每一行或者 每一列的算术平均数

a = torch.randn(1, 3)

tensor([[ 0.2294, -0.5481, 1.3288]])

torch.mean(a)

tensor(0.3367)

a = torch.randn(4, 4)

tensor([[-0.3841, 0.6320, 0.4254, -0.7384],
[-0.9644, 1.0131, -0.6549, -1.4279],
[-0.2951, -1.3350, -0.7694, 0.5600],
[ 1.0842, -0.9580, 0.3623, 0.2343]])

torch.mean(a, 1, True)

tensor([[-0.0163],
[-0.5085],
[-0.4599],
[ 0.1807]])

torch.mean(a, 1)

tensor([-0.0163, -0.5085, -0.4599, 0.1807])

dim=true,计算每一行的平均数,输出与输入有相同的维度:两维度(4,1)

不设置dim,默认计算每一行的平均数,内嵌了一个torch.squeeze(),将数值为1的维度压缩(4,)

3 torch.squeeze()
torch.squeeze(input, dim=None, out=None)
输出:将输入所有维度为1的去除(2,1)=(2,)(以行向量的形式存在)

x = torch.zeros(2, 1, 2, 1, 2)
x.size()

torch.Size([2, 1, 2, 1, 2])

y = torch.squeeze(x)
y.size()

torch.Size([2, 2, 2])

torch.unsqueeze(),(Returns a new tensor with a dimension of size one inserted at the specified position)给数据增加一维度,特别是看到数据的维度为.size([])懵逼了,在后续计算的时候会造成问题。所以需要给数据升维度。

x = torch.tensor([1, 2, 3, 4])
torch.unsqueeze(x, 0)

tensor([[ 1, 2, 3, 4]])

torch.unsqueeze(x, 1)

tensor([[ 1],
[ 2],
[ 3],
[ 4]])

4 torch.pow()求幂次运算
对输入的每分量求幂次运算

a = torch.randn(4)
a
tensor([ 0.4331, 1.2475, 0.6834, -0.2791])

torch.pow(a, 2)
tensor([ 0.1875, 1.5561, 0.4670, 0.0779])

exp = torch.arange(1., 5.)

a = torch.arange(1., 5.)
a
tensor([ 1., 2., 3., 4.])

exp
tensor([ 1., 2., 3., 4.])

torch.pow(a, exp)
tensor([ 1., 4., 27., 256.])
1
2
3
4
5
6
7
8
9
10
11
12
13
14
和numpy中的numpy.power()作用类似。

torch.pow(input, exponent, out=None)
对输入input的按元素求exponent次幂值,并返回结果张量。
幂值exponent 可以为单一 float 数或者与input相同元素数的张量。

当幂值为标量时,执行操作:
o u t i = x e x p o n e n t out_i=x^{exponent} outi=xexponent

当幂值为张量时,执行操作:
o u t i = x e x p o n e n t i out_i=x^{exponent_i} outi=xexponenti

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值