unsqueeze,squeeze

import torch
import matplotlib.pyplot as plt

a = torch.randn(2, 3)  # 标准正态分布生成随机数
print("a:", a)
print("a.shape:", a.shape)  # torch.Size([2, 3])

# unsqueeze:扩充数据维度,在0起的指定位置N加上维数为一的维度
b = torch.unsqueeze(a, 1)  # [2, 3]中在位置1,就是=3的位置增加维度1,3向后串
print("b.shape:", b.shape)  # torch.Size([2, 1, 3])
print("b:", b)
c = torch.unsqueeze(a, 0)  # [2, 3]中在位置0,就是=1的位置增加维度1,2向后串
print("c.shape:", c.shape)  # torch.Size([1, 2, 3])
# --------------------------------------------------------------#
f = torch.randn(3)
print("f:", f)
print("f.shape:", f.shape)  # torch.Size([3])
g = f.unsqueeze(0)  # [3]中在位置0,就是=3的位置增加维度1,3向后串
print("g.shape:", g.shape)  # torch.Size([1, 3])
print("g:", g)
# --------------------------------------------------------------#
# squeeze:维度压缩,在0起的指定位置,去掉维数为1的的维度
print("c:", c)
print("c.shape:", c.shape)
d = torch.squeeze(c)  # d=c.squeeze(0)
print("d:", d)
print(d.shape)  # torch.Size([2, 3])
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值