評價此頁

torch.meshgrid#

torch.meshgrid(*tensors, indexing=None)[原始碼]#

建立由 attr:tensors 中一維輸入指定的座標網格。

這在您想視覺化某些輸入範圍的資料時很有幫助。有關繪圖示例,請參閱下文。

給定 NN 個 1D 張量 T0TN1T_0 \ldots T_{N-1} 作為輸入,其對應的尺寸為 S0SN1S_0 \ldots S_{N-1},則會建立 NN 個 N 維張量 G0GN1G_0 \ldots G_{N-1},每個張量的形狀為 (S0,...,SN1)(S_0, ..., S_{N-1}),其中輸出 GiG_i 是透過將 TiT_i 擴充套件到結果形狀而建立的。

注意

0D 輸入被視為與單元素 1D 輸入等效。

警告

torch.meshgrid(*tensors) 目前的行為與呼叫 numpy.meshgrid(*arrays, indexing=’ij’) 相同。

未來 torch.meshgrid 將預設過渡到 indexing=’xy’

pytorch/pytorch#50276 跟蹤此問題,目標是遷移到 NumPy 的行為。

另請參閱

torch.cartesian_prod() 具有相同的效果,但它將資料收集到張量向量中。

引數
  • tensors (list of Tensor) – 標量或 1 維張量的列表。標量將被自動視為大小為 (1,)(1,) 的張量。

  • indexing (Optional[str]) –

    (str, optional): 索引模式,可以是“xy”或“ij”,預設為“ij”。有關未來更改的警告。

    如果選擇“xy”,則第一個維度對應於第二個輸入的基數,第二個維度對應於第一個輸入的基數。

    如果選擇“ij”,則維度順序與輸入的基數順序相同。

返回

如果輸入包含 NN 個尺寸為 S0SN1S_0 \ldots S_{N-1} 的張量,則輸出也將包含 NN 個張量,其中每個張量的大小為 (S0,...,SN1)(S_0, ..., S_{N-1})

返回型別

seq (Tensors 序列)

示例

>>> 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()
../_images/meshgrid.png