温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

torch.mean()和torch.pow()怎么使用

发布时间:2021-12-27 14:28:53 来源:亿速云 阅读:1583 作者:iii 栏目:大数据

本篇内容主要讲解“torch.mean()和torch.pow()怎么使用”,感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习“torch.mean()和torch.pow()怎么使用”吧!

torch.randn()

产生大小为指定的,正态分布的采样点,数据类型是tensor

torch.mean()

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

例如:

a=torch.randn(3) #生成一个一维的矩阵

b=torch.randn(1,3) #生成一个二维的矩阵

print(a)

print(b)

torch.mean(a)

结果:

tensor([-1.0737, -0.8689, -0.9553])
tensor([[-0.4005, -0.6812,  0.0958]])

tensor(-0.9659)

如果指定参数的话,

a=torch.randn(4,4)

print(a)

c=torch.mean(a,dim=0,keepdim=True)

print(c)

d=torch.mean(a,dim=1,keepdim=True)

print(d)

结果:

tensor([[ 0.2378, -1.1380,  0.7964, -0.1413],
        [ 0.4622, -1.7003, -1.1628,  0.8930],
        [-2.0379, -1.7137,  0.6423, -0.2026],
        [ 0.3512, -0.1251, -0.8315,  2.2642]])

tensor([[-0.2467, -1.1693, -0.1389,  0.7033]])

tensor([[-0.0612],
        [-0.3770],
        [-0.8280],
        [ 0.4147]])

可以看到dim指定为1时,求得是行的平均值,指定为0时,求得是列的平均值。

torch.pow()

对输入的每分量求幂次运算

a=torch.tensor(3)

b=torch.pow(a,2)

print(b)

c=torch.randn(4)

print(c)

d=torch.pow(c,2)

print(d)

结果:

tensor(9)
tensor([ 0.0923,  0.7006, -0.2963,  0.6543])
tensor([0.0085, 0.4909, 0.0878, 0.4282])

torch.matmul()

torch.matmul 是做矩阵乘法

例如:

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

b=torch.tensor([3,4,5])

torch.matmul(a, b)

结果:

tensor(26)

torch.ones_like()

torch.ones_like(input, dtype=None, layout=None, device=None, requires_grad=False) → Tensor

返回一个填充了标量值1的张量,其大小与之相同 input。

我是在Pytorch自动求导中第一次发现此方法的,

例如:

import torch

from torch.autograd import Variable

m = Variable(torch.FloatTensor([[2, 3]]), requires_grad=True) # 构建一个 1 x 2 的矩阵

n = Variable(torch.zeros(1, 2)) # 构建一个相同大小的 0 矩阵

print(m)

print(n)

# 通过 m 中的值计算新的 n 中的值

n[0, 0] = m[0, 0] ** 2

n[0, 1] = m[0, 1] ** 3

print(n[0,0])

print(n)

结果:

tensor([[2., 3.]], requires_grad=True)
tensor([[0., 0.]])
tensor(4., grad_fn=<SelectBackward>)
tensor([[ 4., 27.]], grad_fn=<CopySlices>)
n.backward(torch.ones_like(n))

# 相当于n.backward(torch.FloatTensor([[1,1]]))

print(m.grad)

结果:

tensor([[ 4., 27.]])

到此,相信大家对“torch.mean()和torch.pow()怎么使用”有了更深的了解,不妨来实际操作一番吧!这里是亿速云网站,更多相关内容可以进入相关频道进行查询,关注我们,继续学习!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI