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

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

对比一下repeatexpand

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]])
  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值