PyTorch torch.fliplr 函数
torch.fliplr 是 PyTorch 中用于左右翻转(水平翻转)张量的函数。
函数定义
torch.fliplr(input)
使用示例
实例
import torch
# 二维张量左右翻转
x = torch.arange(12).reshape(3, 4)
print("原始张量:")
print(x)
result = torch.fliplr(x)
print("左右翻转:")
print(result)
# 方阵左右翻转
y = torch.tensor([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
print("n3x3 方阵:")
print(y)
result = torch.fliplr(y)
print("左右翻转:")
print(result)
# 向量无法翻转,会报错
z = torch.tensor([1, 2, 3])
try:
result = torch.fliplr(z)
except RuntimeError as e:
print(f"n一维向量翻转报错: {e}")
# 二维张量左右翻转
x = torch.arange(12).reshape(3, 4)
print("原始张量:")
print(x)
result = torch.fliplr(x)
print("左右翻转:")
print(result)
# 方阵左右翻转
y = torch.tensor([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
print("n3x3 方阵:")
print(y)
result = torch.fliplr(y)
print("左右翻转:")
print(result)
# 向量无法翻转,会报错
z = torch.tensor([1, 2, 3])
try:
result = torch.fliplr(z)
except RuntimeError as e:
print(f"n一维向量翻转报错: {e}")
输出结果为:
原始张量:
tensor([[ 0, 1, 2, 3],
[ 4, 5, 6, 7],
[ 8, 9, 10, 11]])
左右翻转:
tensor([[ 3, 2, 1, 0],
[ 7, 6, 5, 4],
[11, 10, 9, 8]])
3x3 方阵:
tensor([[1, 2, 3],
[4, 5, 6],
[7, 8, 9]])
左右翻转:
tensor([[3, 2, 1],
[6, 5, 4],
[9, 8, 7]])
一维向量翻转报错: fliplr: Input must be at least 2-D

Pytorch torch 参考手册