import torch
# 1. view() - 调整张量形状
tensor = torch.tensor([1, 2, 3, 4, 5, 6])
reshaped_tensor = tensor.view(2, 3)
print("view:\n", reshaped_tensor)
# 输出:
# tensor([[1, 2, 3],
# [4, 5, 6]])
# 2. reshape() - 调整张量形状,适用于不连续内存的张量
reshaped_tensor = tensor.reshape(2, 3)
print("reshape:\n", reshaped_tensor)
# 输出:
# tensor([[1, 2, 3],
# [4, 5, 6]])
# 3. permute() - 交换张量的维度
tensor = torch.randn(2, 3, 4)
permuted_tensor = tensor.permute(2, 0, 1)
print("permute:\n", permuted_tensor.shape)
# 输出:
# torch.Size([4, 2, 3])
# 4. transpose() - 交换两个维度
tensor = torch.randn(2, 3)
transposed_tensor = tensor.transpose(0, 1)
print("transpose:\n", transposed_tensor.shape)
# 输出:
# torch.Size([3, 2])
# 5. unsqueeze() - 增加一个维度
tensor = torch.tensor([1, 2, 3, 4])
unsqueezed_tensor = tensor.unsqueeze(0)
print("unsqueeze:\n", unsqueezed_tensor.shape)
# 输出:
# torch.Size([1, 4])
# 6. squeeze() - 移除大小为1的维度
tensor = torch.tensor([[[1, 2, 3, 4]]])
squeezed_tensor = tensor.squeeze()
print("squeeze:\n", squeezed_tensor.shape)
# 输出:
# torch.Size([4])
# 7. flatten() - 将张量展平为一维
tensor = torch.tensor([[1, 2], [3, 4]])
flattened_tensor = tensor.flatten()
print("flatten:\n", flattened_tensor)
# 输出:
# tensor([1, 2, 3, 4])
# 8. expand() - 扩展张量的维度
tensor = torch.tensor([1, 2, 3])
expanded_tensor = tensor.expand(3, 3)
print("expand:\n", expanded_tensor)
# 输出:
# tensor([[1, 2, 3],
# [1, 2, 3],
# [1, 2, 3]])
# 9. repeat() - 重复张量的元素
tensor = torch.tensor([1, 2, 3])
repeated_tensor = tensor.repeat(2, 1)
print("repeat:\n", repeated_tensor)
# 输出:
# tensor([[1, 2, 3],
# [1, 2, 3]])
# 10. chunk() - 将张量分割成块
tensor = torch.tensor([[1, 2, 3], [4, 5, 6]])
chunks = tensor.chunk(2, dim=1)
print("chunk:")
for chunk in chunks:
print(chunk)
# 输出:
# tensor([[1, 2],
# [4, 5]])
# tensor([[3],
# [6]])
# 11. split() - 将张量分割成指定大小
tensor = torch.tensor([[1, 2, 3], [4, 5, 6]])
splits = tensor.split(2, dim=1)
print("split:")
for split in splits:
print(split)
# 输出:
# tensor([[1, 2],
# [4, 5]])
# tensor([[3],
# [6]])
# 12. cat() - 沿着指定维度拼接张量
tensor1 = torch.tensor([[1, 2], [3, 4]])
tensor2 = torch.tensor([[5, 6], [7, 8]])
concatenated_tensor = torch.cat((tensor1, tensor2), dim=0)
print("cat:\n", concatenated_tensor)
# 输出:
# tensor([[1, 2],
# [3, 4],
# [5, 6],
# [7, 8]])
# 13. stack() - 沿着新的维度拼接张量
tensor1 = torch.tensor([1, 2, 3])
tensor2 = torch.tensor([4, 5, 6])
stacked_tensor = torch.stack((tensor1, tensor2), dim=0)
print("stack:\n", stacked_tensor)
# 输出:
# tensor([[1, 2, 3],
# [4, 5, 6]])
# 14. unfold() - 将张量展开为滑动窗口
tensor = torch.arange(1, 10).view(1, 1, 3, 3)
unfolded_tensor = tensor.unfold(2, 2, 1).unfold(3, 2, 1)
print("unfold:\n", unfolded_tensor)
# 输出:
# tensor([[[[[[1, 2],
# [4, 5]],
# [[2, 3],
# [5, 6]]],
# [[[4, 5],
# [7, 8]],
# [[5, 6],
# [8, 9]]]]]])
pytorch 用来改变tensor 形状的方法
最新推荐文章于 2024-07-25 23:27:22 发布