x.squeeze()、x.unsqueeze()用法

x.squeeze(dim)

用途:进行维度压缩,去掉tensor中维数为1的维度

参数设置:如果设置dim=a,就是去掉指定维度中维数为1的

示例:

import torch
x = torch.tensor([[[1],[2]],[[3],[4]]])
print('x:',x)
x1 = x.squeeze()
print('x1:',x1)
x2 = x.squeeze(2)
print('x2:',x2)

 输出:

x: tensor([[[1],
         [2]],

        [[3],
         [4]]])
x1: tensor([[1, 2],
        [3, 4]])
x2: tensor([[1, 2],
        [3, 4]])

Process finished with exit code 0

x.unsqueeze(dim=a)

用途:进行维度扩充,在指定位置加上维数为1的维度

参数设置:如果设置dim=a,就是在维度为a的位置进行扩充

示例:

import torch
x = torch.tensor([1,2,3,4])
print(x)
x1 = x.unsqueeze(dim=0)
print(x1)
x2 = x.unsqueeze(dim=1)
print(x2)

y = torch.tensor([[1,2,3,4],[9,8,7,6]])
print(y)
y1 = y.unsqueeze(dim=0)
print(y1)
y2 = y.unsqueeze(dim=1)
print(y2)

输出:

x: tensor([1, 2, 3, 4])
x1: tensor([[1, 2, 3, 4]])
x2: tensor([[1],
        [2],
        [3],
        [4]])
y: tensor([[1, 2, 3, 4],
        [9, 8, 7, 6]])
y1: tensor([[[1, 2, 3, 4],
         [9, 8, 7, 6]]])
y2: tensor([[[1, 2, 3, 4]],

        [[9, 8, 7, 6]]])

Process finished with exit code 0

  • 16
    点赞
  • 37
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
x.unsqueeze(-1)是将张量x在最后一个维度上增加一个维度。具体而言,如果x的形状是(1, 2, 3, 4),那么x.unsqueeze(-1)将返回一个形状为(1, 2, 3, 4, 1)的新张量。这意味着在原来的张量上增加了一个长度为1的维度。这种操作可以用来改变张量的形状,以满足特定的计算需求。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* [Pytorch squeeze() unsqueeze() 用法](https://blog.csdn.net/weixin_43820352/article/details/125995034)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT0_1"}}] [.reference_item style="max-width: 33.333333333333336%"] - *2* [PyTorch版《动手学深度学习》学习笔记 Task.4](https://download.csdn.net/download/weixin_38695773/14034979)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT0_1"}}] [.reference_item style="max-width: 33.333333333333336%"] - *3* [pytorch中的squeeze和unsqueeze](https://blog.csdn.net/flying_all/article/details/117014995)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT0_1"}}] [.reference_item style="max-width: 33.333333333333336%"] [ .reference_list ]

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值