PyTorch学习笔记(三):Tensor变换

view/reshape
a = torch.rand(4,1,28,28)
print(a.shape)                     # torch.Size([4, 1, 28, 28])
print(a.view(4, 28*28).shape)      # torch.Size([4, 784])
print(a.reshape(4, 28*28).shape)   # torch.Size([4, 784])
print(a.view(4, -1).shape)         # torch.Size([4, 784])
print(a.reshape(4, -1).shape)      # torch.Size([4, 784])
squeeze/unsqueeze
a = torch.rand(4,1,28,28)
print(a.shape)                  # torch.Size([4, 1, 28, 28])
print(a.unsqueeze(0).shape)     # torch.Size([1, 4, 1, 28, 28])
print(a.unsqueeze(4).shape)     # torch.Size([4, 1, 28, 28, 1])
print(a.unsqueeze(-1).shape)    # torch.Size([4, 1, 28, 28, 1])
print(a.squeeze().shape)        # torch.Size([4, 28, 28])
print(a.squeeze(1).shape)       # torch.Size([4, 28, 28])
transpose/permute
a = torch.rand(10,3,32,32)
print(a.shape)                    # torch.Size([10, 3, 32, 32])
print(a.transpose(1,3).shape)     # torch.Size([10, 32, 32, 3])
print(a.permute(0,3,2,1).shape)   # torch.Size([10, 32, 32, 3])
expand/repeat
b = torch.randint(1, 10, (1, 3))
print(b)
print(b.shape)
print(b.storage())              # 数据存放形式
print(b.storage().data_ptr())   # 地址
# 输出
tensor([[7, 8, 9]])
torch.Size([1, 3])
 7
 8
 9
[torch.LongStorage of size 3]
2530665948608

# expand: broadcasting
b_1 = b.expand(3, 3)
print(b_1)
print(b_1.shape)
print(b_1.storage())
print(b_1.storage().data_ptr())
# 输出
tensor([[7, 8, 9],
        [7, 8, 9],
        [7, 8, 9]])
torch.Size([3, 3])
 7
 8
 9
[torch.LongStorage of size 3]
2530665948608

# repeat: memory copied
b_2 = b.repeat(3, 1)
print(b_2)
print(b_2.shape)
print(b_2.storage())
print(b_2.storage().data_ptr())
# 输出
tensor([[7, 8, 9],
        [7, 8, 9],
        [7, 8, 9]])
torch.Size([3, 3])
 7
 8
 9
 7
 8
 9
 7
 8
 9
[torch.LongStorage of size 9]
2530678187136
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值