torch.meshgrid¶
- torch.meshgrid(*tensors, indexing=None)[來源][來源]¶
根據 attr:tensors 中一維輸入指定的座標,建立網格。
當您想要將資料視覺化在某些輸入範圍內時,這很有用。請參閱下方的繪圖範例。
給定 個 1D 張量 作為輸入,且對應的大小為 ,這會建立 個 N 維張量 ,每個的形狀為 ,其中輸出 是透過擴展 到結果形狀來建構的。
注意
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 (張量) (list of Tensor (張量)) – 純量或一維張量的列表。純量會自動被視為大小為 的張量。
indexing (索引) (Optional (可選的)[str]) –
(str, optional (可選的)): 索引模式,可以是 "xy" 或 "ij",預設為 "ij"。 請注意未來變更的警告。
如果選擇 "xy",則第一維對應於第二個輸入的基數 (cardinality),而第二維對應於第一個輸入的基數。
如果選擇 "ij",則維度與輸入的基數順序相同。
- Returns (返回值)
如果輸入具有 個大小為 的張量,則輸出也將具有 個張量,其中每個張量的形狀為 。
- Return type (返回值類型)
seq (sequence of Tensors) (Tensors 序列)
Example (範例)
>>> 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()