PyTorch torch.broadcast_to 函数
torch.broadcast_to 是 PyTorch 中用于将张量广播到指定形状的函数。它返回输入张量的视图,该视图被广播到目标形状。广播规则遵循 NumPy 的广播机制。
函数定义
torch.broadcast_to(input, shape)
使用示例
实例
import torch
# 基础用法:将 1 维张量广播到 2 维
x = torch.tensor([1, 2, 3])
y = torch.broadcast_to(x, (3, 3))
print("原始:", x)
print("广播后:")
print(y)
# tensor([[1, 2, 3],
# [1, 2, 3],
# [1, 2, 3]])
# 将标量广播到更大形状
x = torch.tensor(5)
y = torch.broadcast_to(x, (2, 3, 4))
print("标量广播到 (2,3,4):", y.shape)
# 将 2 维广播到 3 维
x = torch.tensor([[1, 2], [3, 4]]) # (2, 2)
y = torch.broadcast_to(x, (3, 2, 2))
print("广播到 (3,2,2):", y.shape)
print(y)
# 基础用法:将 1 维张量广播到 2 维
x = torch.tensor([1, 2, 3])
y = torch.broadcast_to(x, (3, 3))
print("原始:", x)
print("广播后:")
print(y)
# tensor([[1, 2, 3],
# [1, 2, 3],
# [1, 2, 3]])
# 将标量广播到更大形状
x = torch.tensor(5)
y = torch.broadcast_to(x, (2, 3, 4))
print("标量广播到 (2,3,4):", y.shape)
# 将 2 维广播到 3 维
x = torch.tensor([[1, 2], [3, 4]]) # (2, 2)
y = torch.broadcast_to(x, (3, 2, 2))
print("广播到 (3,2,2):", y.shape)
print(y)

Pytorch torch 参考手册