PyTorch的Tensor相关函数/操作

定义Tensor与tensor

# 大写Tensor里面的参数可以定义Tensor的形状
>>> a = torch.Tensor(5)
>>> a
tensor([2.0700e-19, 4.4667e+33, 7.0065e-45, 0.0000e+00, 1.4013e-45])

# 小写的tensor里面的参数就是具体值
>>> a = torch.tensor(5)
>>> a
tensor(5)

# 返回跟input的tensor一样size的0-1随机数
>>> a = torch.rand_like(input)

与numpy.array的转换

# torch.tensor转numpy.array
>>> type(a)
<class 'torch.Tensor'>
>>> type(a.numpy())
<class 'numpy.ndarray'>

# numpy.array转torch.tensor
>>> type(b)
<class 'numpy.ndarray'>
>>> type(torch.tensor(b))
<class 'torch.Tensor'>

view
改变张量的形状,相当于numpy的reshape。

>>> a.shape
torch.Size([3, 2, 2])
>>> a.view(3,4).shape
torch.Size([3, 4])

permute
给张量的维度换位置,期中的参数就是原来的维度的编号。

>>> a.shape
torch.Size([3, 2, 2])
>>> a.permute(2,1,0).shape
torch.Size([2, 2, 3])

# 可以用-1代替未知的维度参数,但是只能有一个位置使用-1
>>> a.view(-1,4).shape
torch.Size([3, 4])
>>> a.view(3,-1).shape
torch.Size([3, 4])
>>> a.view(-1,).shape
torch.Size([12])

mul
张量对应位置相乘

>>> a
tensor([0., 1., 2., 3., 4.])
>>> c
tensor([1., 2., 3., 4., 5.])
>>> a.mul(c)
tensor([ 0.,  2.,  6., 12., 20.])

torch.mm 和 torch.matmul
张量相乘 mm(m x n, n x p) = (m x p)

# 当张量维度符合要求的时候
>>> b = torch.Tensor(3,5)
>>> a = torch.Tensor(5,2)
>>> torch.mm(b,a).shape
torch.Size([3, 2])
>>> torch.matmul(b,a).shape
torch.Size([3, 2])
# 两者无区别

# 当张量是一维的时候
>>> a = torch.tensor([5])
>>> torch.matmul(a,a)
tensor(25)
>>> torch.mm(a,a)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: Dimension out of range (expected to be in range of [-1, 0], but got 1)

# 当张量既不符合要求也不是一维的时候,两个函数皆不能使用。
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值