PyTorch学习之torch.reshape函数
一、什么是 torch.reshape
torch.reshape
函数用于将一个张量重新排列成指定的形状(shape)。其本质上是创建了一个新的张量,新的张量与原始张量共享相同的数据存储,但形状发生了变化。
二、torch.reshape
的语法
torch.reshape(input, shape)
input
:待调整形状的张量。shape
:一个表示新形状的元组或列表。新形状的元素乘积必须等于原始张量的元素总数。
三、示例
下面通过几个简单的例子来演示 torch.reshape
的用法。
示例 1:基本用法
import torch
# 创建一个 1x8 的张量
x = torch.arange(8)
print("原始张量:")
print(x)
# 将 1x8 的张量重塑为 2x4 的张量,下面给两条语句的作用相同
# x_reshaped = torch.reshape(x, (2, 4))
x_reshaped = x.reshape((2, 4))
print("重塑后的张量:")
print(x_reshaped)
输出:
原始张量:
tensor([0, 1, 2, 3, 4, 5, 6, 7])
重塑后的张量:
tensor([[0, 1, 2, 3],
[4, 5, 6, 7]])
示例 2:使用 -1 自动推断形状
在 torch.reshape
中,可以使用 -1 让 PyTorch 自动计算某一个维度的大小,只要其它维度的大小是已知的即可。
import torch
# 创建一个 2x2x2 的张量
x = torch.arange(8).reshape(2, 2, 2)
print(x)
# 将 2x2x2 的张量重塑为 2x4 的张量
x_reshaped = x.reshape((2, -1))
print("重塑后的张量:")
print(x_reshaped)
输出:
tensor([[[0, 1],
[2, 3]],
[[4, 5],
[6, 7]]])
重塑后的张量:
tensor([[0, 1, 2, 3],
[4, 5, 6, 7]])
四、torch.reshape
与 torch.view
的区别
在 PyTorch 中,torch.view
也可以用于调整张量的形状。两者的主要区别在于:
torch.view
只能用于连续(contiguous)的张量,如果张量在内存中不是连续的,会需要调用.contiguous()
方法后才能使用view
。而torch.reshape
则没有这个限制,能够处理非连续的张量。torch.reshape
通常会更通用,适用性更广。