首页 > 其他分享 >Pytorch tensor操作 gather、expand、repeat、reshape、view、permute、transpose

Pytorch tensor操作 gather、expand、repeat、reshape、view、permute、transpose

时间:2022-12-02 17:07:42浏览次数:41  
标签:repeat tensor reshape contiguous torch permute expand view


文章目录

  • ​​tensor.gather​​
  • ​​tensor.expand​​
  • ​​tensor.repeat​​
  • ​​reshape() 和 view()​​
  • ​​permute() 和 transpose()​​
  • ​​torch.matmul()​​
  • ​​torch.ger​​

tensor.gather

​​torch.gather​​

tensor.expand

返回当前张量在某维扩展更大后的张量。扩展(expand)张量不会分配新的内存,只是在存在的张量上创建一个新的视图(view),一个大小(size)等于1的维度扩展到更大的尺寸。

x = torch.tensor([[1,2,3]])
x.expand(2,-1) # 第一个维度重复一次,第二个维度不变,注意,只能操作大小等于1的维度

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

tensor.repeat

沿着特定的维度重复这个张量,和expand()不同的是,这个函数拷贝张量的数据。

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

对比一下​​repeat​​​和​​expand​

x = torch.tensor([[1,2,3]])
y = x.expand(2,-1)
z = x.repeat(2,1)
print(x.data_ptr(), y.data_ptr(), z.data_ptr())

2434171052800 2434171052800 2434177810176

PyTorch学习笔记——repeat()和expand()区别

reshape() 和 view()

功能相似,但是​​view()​​​只能操作 tensor,​​reshape()​​​可以操作 tensor 和 ndarray。​​view()​​​ 只能用在 ​​contiguous​​​ 的 variable 上。如果在 view 之前用了 ​​transpose​​​, ​​permute​​​ 等,需要用 ​​contiguous()​​​ 来返回一个 contiguous copy。 view() 操作后的 tensor 和原 tensor 共享存储。
pytorch 中的 ​​​torch.reshape()​​​ 大致相当于 ​​tensor.contiguous().view()​​。

x = torch.tensor([[1,2,3]])
x.reshape(3,1)
>>>
tensor([[1],
[2],
[3]])

x.view(3,1) # x.view(*[3,1])
>>>
tensor([[1],
[2],
[3]])

permute() 和 transpose()

两者都是实现维度之间的交换,transpose 只能一次转换两个维度,permute 可以一次转换多个维度,permute 可以通过 transpose 组合的形式实现。在卷积神经网络中,cross-channel max pooling 就用到了这类变换。

x = torch.tensor([[1,2,3]])
y = x.expand(2,-1)
z = x.repeat(2,1)
print(x.is_contiguous(), y.is_contiguous(), z.is_contiguous())
>>>True False True

a = z.permute(1,0)
print(a.is_contiguous())
>>>False

b = z.permute(1,0).contiguous()
b.is_contiguous()
>>>True

​​pytorch中reshape()、view()、permute()、transpose()总结​​

torch.matmul()

a = torch.ones(2,1,3,4) # 2为batch,1*5
b = torch.ones(5,4,2)
torch.matmul(a,b).size()

>>>torch.Size([2, 5, 3, 2])

​​torch.matmul()用法介绍​​

torch.ger

向量外积,输入两个向量

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

Out[15]:
tensor([[ 1, 2, 3, 4],
[ 2, 4, 6, 8],
[ 3, 6, 9, 12]])


标签:repeat,tensor,reshape,contiguous,torch,permute,expand,view
From: https://blog.51cto.com/u_15899958/5907214

相关文章