PyTorch向量变换基本操作

一、torch.cat()或者时torch.concat()

对张量在指定维度进行拼接

# 例如有一个维度为[2,3]的向量x = torch.tensor([[1, 2, 3], [4, 5, 6]])


>>> torch.cat((x, x), 1)
tensor([[1, 2, 3, 1, 2, 3],
        [4, 5, 6, 4, 5, 6]])
>>> torch.cat((x, x), 0)
tensor([[1, 2, 3],
        [4, 5, 6],
        [1, 2, 3],
        [4, 5, 6]])

二、tesnsor.unzqueeze()

对张量进行维度扩展

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

三、tensor.permute()

对张量进行维度变换

# 借用上面x的值
>>> x.shape
torch.Size([1, 1, 4])
>>> x=x.permute(0,2,1)
>>> x.shape
torch.Size([1, 4, 1])
>>> x=x.permute(1,0,2)
>>> x.shape
torch.Size([4, 1, 1])

四、torch.full()

使用指定数字对指定形状的向量进行填充

>>> bert = [[1,2,3],[2,3,1]]
>>> bert_tensor = torch.tensor(bert,dtype=torch.long)
>>> bert_tensor.shape
torch.Size([2, 3])

>>> pad = torch.full([1,5,bert_tensor.shape[1]],0, dtype = torch.long)
>>> pad
tensor([[[0, 0, 0],
         [0, 0, 0],
         [0, 0, 0],
         [0, 0, 0],
         [0, 0, 0]]])

五、torch.repeat_interleave()

对张量进行重复

x = torch.tensor([1, 2, 3])
x.repeat_interleave(2)
# tensor([1, 1, 2, 2, 3, 3])
y = torch.tensor([[1, 2], [3, 4]])
torch.repeat_interleave(y, 2)  # 全部展平成(x,1)维的张量
# tensor([1, 1, 2, 2, 3, 3, 4, 4])
torch.repeat_interleave(y, 3, dim=1)  # 在指定维度进行重复
# tensor([[1, 1, 1, 2, 2, 2],
#         [3, 3, 3, 4, 4, 4]])
torch.repeat_interleave(y, torch.tensor([1, 2]), dim=0)  # 进行指定形状的重复
#tensor([[1, 2],
#        [3, 4],
#        [3, 4]])
torch.repeat_interleave(y, torch.tensor([1, 2]), dim=0, output_size=3)
# tensor([[1, 2],
#         [3, 4],
#         [3, 4]])

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

hithithithithit

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值