PyTorch torch.meshgrid 函数
torch.meshgrid 是 PyTorch 中用于从坐标向量创建网格的函数。它从多个一维坐标向量生成坐标张量。
函数定义
torch.meshgrid(*tensors, indexing='xy')
参数说明:
*tensors: 输入的一维张量indexing: 索引方式,'xy'(笛卡尔)或 'ij'(矩阵)
使用示例
实例
import torch
# 创建坐标向量
x = torch.tensor([1, 2, 3])
y = torch.tensor([4, 5])
# 创建网格(笛卡尔索引)
grid_x, grid_y = torch.meshgrid(x, y, indexing='xy')
print("grid_x:")
print(grid_x)
print("grid_y:")
print(grid_y)
# 创建坐标向量
x = torch.tensor([1, 2, 3])
y = torch.tensor([4, 5])
# 创建网格(笛卡尔索引)
grid_x, grid_y = torch.meshgrid(x, y, indexing='xy')
print("grid_x:")
print(grid_x)
print("grid_y:")
print(grid_y)
输出结果为:
grid_x:
tensor([[1, 2, 3],
[1, 2, 3]])
grid_y:
tensor([[4, 4, 4],
[5, 5, 5]])
实例
import torch
# 创建坐标向量
x = torch.tensor([1, 2, 3])
y = torch.tensor([4, 5])
# 创建网格(矩阵索引)
grid_x, grid_y = torch.meshgrid(x, y, indexing='ij')
print("grid_x:")
print(grid_x)
print("grid_y:")
print(grid_y)
# 创建坐标向量
x = torch.tensor([1, 2, 3])
y = torch.tensor([4, 5])
# 创建网格(矩阵索引)
grid_x, grid_y = torch.meshgrid(x, y, indexing='ij')
print("grid_x:")
print(grid_x)
print("grid_y:")
print(grid_y)
输出结果为:
grid_x:
tensor([[1, 1],
[2, 2],
[3, 3]])
grid_y:
tensor([[4, 5],
[4, 5],
[4, 5]])

Pytorch torch 参考手册