pytorch基础学习2

1.切片

import torch
b=torch.tensor([[[1, 2, 3,4]]])
print(b)
a=b[:,:,0:4:2].shape
print(a)
print(b[:,:,0:4:2])
print(b)

结果:tensor([[[1, 2, 3, 4]]])
torch.Size([1, 1, 2])
tensor([[[1, 3]]])
tensor([[[1, 2, 3, 4]]])

2.维度变幻

2.1view/reshape

import torch
b=torch.rand(1,1,3,3)
print(b)
a=b.view(1,1*3*3)
print(a)
c=b.view(1*1*3,3)
print(c)


结果:tensor([[[[0.5734, 0.3008, 0.0772],
          [0.8198, 0.1803, 0.3937],
          [0.0340, 0.9622, 0.0150]]]])
tensor([[0.5734, 0.3008, 0.0772, 0.8198, 0.1803, 0.3937, 0.0340, 0.9622, 0.0150]])
tensor([[0.5734, 0.3008, 0.0772],
        [0.8198, 0.1803, 0.3937],
        [0.0340, 0.9622, 0.0150]])

2.2Squeeze压缩维度,自动化,只能压缩1/unsqueeze展开维度

import torch
b=torch.tensor([1,1,3,3])
print(b)
print(b.shape)
a=b.unsqueeze(0)
print(a)
print(a.shape)
c=b.unsqueeze(-1)
print(c)
print(c.shape)


结果:tensor([1, 1, 3, 3])
torch.Size([4])
tensor([[1, 1, 3, 3]])
torch.Size([1, 4])
tensor([[1],
        [1],
        [3],
        [3]])
torch.Size([4, 1])

2.3Transpose/t/permute

2.3.1 t二维

import torch
b=torch.randn(2,3)
print(b)
a=b.t()
print(a)

结果:

tensor([[ 6.8482e-01,  1.0790e+00, -4.5453e-04],
        [-2.3182e+00,  7.3845e-01,  1.0354e+00]])
tensor([[ 6.8482e-01, -2.3182e+00],
        [ 1.0790e+00,  7.3845e-01],
        [-4.5453e-04,  1.0354e+00]])
2.3.2  Transpose

import torch
b=torch.randn(4,2,3,8)
a1=b.transpose(1,3).contiguous().view(4,2*3*8).view(4,2,3,8)
a2=b.transpose(1,3).contiguous().view(4,2*3*8).view(4,8,3,2).transpose(1,3)
#a2=b.transpose(1,3).contiguous().view(4,8,3,2).transpose(1,3)#same
print(torch.all(torch.eq(b,a1)))
print(torch.all(torch.eq(b,a2)))

结果:
tensor(0, dtype=torch.uint8)
tensor(1, dtype=torch.uint8)

 

2.4Expand/repeat建议少用

import torch
b=torch.rand(1,3,14,14)
print(b.shape)
a=b.expand(4,3,14,14)
print(a.shape)

结果:
torch.Size([1, 3, 14, 14])
torch.Size([4, 3, 14, 14])

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值