PyTorch torch.tile 函数
torch.tile 是 PyTorch 中用于将张量重复多次的函数。
函数定义
torch.tile(input, dims)
使用示例
实例
import torch
# 一维张量重复
x = torch.tensor([1, 2, 3])
print("原始一维张量:")
print(x)
result = torch.tile(x, 3)
print("重复 3 次:")
print(result)
# 二维张量重复
y = torch.tensor([[1, 2], [3, 4]])
print("n原始二维张量:")
print(y)
result = torch.tile(y, (2, 3))
print("沿行重复 2 次,沿列重复 3 次:")
print(result)
# 三维张量重复
z = torch.tensor([[[1, 2], [3, 4]]])
print("n原始三维张量:")
print(z)
result = torch.tile(z, (2, 1, 2))
print("形状 [2, 1, 2] 重复:")
print(result)
print(f"形状: {result.shape}")
# 一维张量重复
x = torch.tensor([1, 2, 3])
print("原始一维张量:")
print(x)
result = torch.tile(x, 3)
print("重复 3 次:")
print(result)
# 二维张量重复
y = torch.tensor([[1, 2], [3, 4]])
print("n原始二维张量:")
print(y)
result = torch.tile(y, (2, 3))
print("沿行重复 2 次,沿列重复 3 次:")
print(result)
# 三维张量重复
z = torch.tensor([[[1, 2], [3, 4]]])
print("n原始三维张量:")
print(z)
result = torch.tile(z, (2, 1, 2))
print("形状 [2, 1, 2] 重复:")
print(result)
print(f"形状: {result.shape}")
输出结果为:
原始一维张量:
tensor([1, 2, 3])
重复 3 次:
tensor([1, 2, 3, 1, 2, 3, 1, 2, 3])
原始二维张量:
tensor([[1, 2],
[3, 4]])
沿行重复 2 次,沿列重复 3 次:
tensor([[1, 2, 1, 2, 1, 2],
[3, 4, 3, 4, 3, 4],
[1, 2, 1, 2, 1, 2],
[3, 4, 3, 4, 3, 4]])
原始三维张量:
tensor([[[1, 2],
[3, 4]]])
形状 [2, 1, 2] 重复:
tensor([[[1, 2, 1, 2],
[3, 4, 3, 4]],
[[1, 2, 1, 2],
[3, 4, 3, 4]]])
形状: torch.Size([2, 2, 4])

Pytorch torch 参考手册