torch.meshgrid

torch.meshgrid(*tensors, indexing=None)[源代码]

根据 attr 中的一维输入张量生成坐标网格。

当你希望在某个输入范围内可视化数据时,这会非常有帮助。以下是一个绘图示例。

给定 $N$ 个 1D 张量 $T_0 \ldots T_{N-1}$,它们的大小分别为 $S_0 \ldots S_{N-1}$。这会创建 $N$ 个 N 维张量 $G_0 \ldots G_{N-1}$,每个张量的形状为 $(S_0, ..., S_{N-1})$。输出张量 $G_i$ 是通过将输入张量 $T_i$ 扩展到指定形状来构造的。

注意

0D输入等同于只有一个元素的1D输入。

警告

torch.meshgrid(*tensors) 的当前行为与调用 numpy.meshgrid(*arrays, indexing='ij') 时的行为相同。

将来,torch.meshgrid 的默认设置将改为 indexing='xy'

https://github.com/pytorch/pytorch/issues/50276 跟踪这个问题,目标是迁移至 NumPy 的行为。

参见

torch.cartesian_prod() 有相同的效果,但会将数据收集到一个包含向量的张量中。

参数
  • tensors (列表 of Tensor) – 标量或一维张量的列表。标量将自动被视为大小为$(1,)$的张量。

  • 索引 (Optional[str]) –

    (str, 可选): 索引模式,可以是“xy”或“ij”,默认为“ij”。请参阅有关未来更改的警告。

    如果选择“xy”,第一个维度对应第二个输入的大小,第二个维度对应第一个输入的大小。

    如果选择“ij”,维度将与输入的顺序一致。

返回值

如果输入包含$N$个大小分别为$S_0 \ldots S_{N-1}$的张量,那么输出也将有$N$个张量,每个张量的形状为$(S_0, ..., S_{N-1})$

返回类型

seq(Tensor序列)

示例:

>>> x = torch.tensor([1, 2, 3])
>>> y = torch.tensor([4, 5, 6])

Observe the element-wise pairings across the grid, (1, 4),
(1, 5), ..., (3, 6). This is the same thing as the
cartesian product.
>>> grid_x, grid_y = torch.meshgrid(x, y, indexing='ij')
>>> grid_x
tensor([[1, 1, 1],
        [2, 2, 2],
        [3, 3, 3]])
>>> grid_y
tensor([[4, 5, 6],
        [4, 5, 6],
        [4, 5, 6]])

This correspondence can be seen when these grids are
stacked properly.
>>> torch.equal(torch.cat(tuple(torch.dstack([grid_x, grid_y]))),
...             torch.cartesian_prod(x, y))
True

`torch.meshgrid` is commonly used to produce a grid for
plotting.
>>> import matplotlib.pyplot as plt
>>> xs = torch.linspace(-5, 5, steps=100)
>>> ys = torch.linspace(-5, 5, steps=100)
>>> x, y = torch.meshgrid(xs, ys, indexing='xy')
>>> z = torch.sin(torch.sqrt(x * x + y * y))
>>> ax = plt.axes(projection='3d')
>>> ax.plot_surface(x.numpy(), y.numpy(), z.numpy())
>>> plt.show()
{BASE_RAW_UPLOAD_URL}/pytorch-doc-2.5/7a9793ecf160cddd2370157677b39b77.png
本页目录