pytorch修改tensor的维度(修改为任意维度,或单纯的增减维度)

1. 修改为任意维度

一般使用两个函数:view()/reshape()resize_()函数

确保修改前后数据量一致:view() / reshape()

import torch

# 自定义维度(变换前后的数据总量必须一致)
my_tensor: torch.Tensor = torch.rand((3, 4, 5, 6))

my_tensor.view((3 * 4, 5 * 6))  # (12,30)
my_tensor.view((4, 3, 6, 5))  # (4,3,6,5)
my_tensor.view((3, -1))  # (3, 120)

my_tensor.reshape((3 * 4, 5 * 6))  # (12,30)
my_tensor.reshape((4, 3, 6, 5))  # (4,3,6,5)
my_tensor.reshape((3, -1))  # (3, 120)

一个常用的操作是拉平矩阵,可以使用:

my_tensor.reshape(-1) # (360,)

修改前后数据量可以不一致: resize_()

pycharm 提示的是resize(),但是使用的是resize_()函数哈

my_tensor = torch.rand((2, 2))
print("原始数据", my_tensor)

my_tensor.resize_([3, 4])  # 用0填充不足的部分
print("增加维度", my_tensor)

my_tensor.resize_([1, 2])  # 直接剪裁超出的维度
print("降低维度", my_tensor)

2. 单纯的增减维度

my_tensor: torch.Tensor = torch.rand((3, 1, 5, 6))

my_tensor.unsqueeze(0)  # 在第一个位置加一个维度 (1,3,1,5,6)
my_tensor.squeeze()  # 减一个维度,只能减少为1的维度 (3,5,6)

猜你喜欢

转载自blog.csdn.net/weixin_35757704/article/details/121201389