torch_geometric.nn.pool.knn
- knn(x: Tensor, y: Tensor, k: int, batch_x: Optional[Tensor] = None, batch_y: Optional[Tensor] = None, cosine: bool = False, num_workers: int = 1, batch_size: Optional[int] = None) Tensor [source]
Finds for each element in
y
thek
nearest points inx
.import torch from torch_geometric.nn import knn x = torch.tensor([[-1.0, -1.0], [-1.0, 1.0], [1.0, -1.0], [1.0, 1.0]]) batch_x = torch.tensor([0, 0, 0, 0]) y = torch.tensor([[-1.0, 0.0], [1.0, 0.0]]) batch_y = torch.tensor([0, 0]) assign_index = knn(x, y, 2, batch_x, batch_y)
- Parameters:
x (torch.Tensor) – Node feature matrix \(\mathbf{X} \in \mathbb{R}^{N \times F}\).
y (torch.Tensor) – Node feature matrix \(\mathbf{X} \in \mathbb{R}^{M \times F}\).
k (int) – The number of neighbors.
batch_x (torch.Tensor, optional) – Batch vector \(\mathbf{b} \in {\{ 0, \ldots, B-1\}}^N\), which assigns each node to a specific example. (default:
None
)batch_y (torch.Tensor, optional) – Batch vector \(\mathbf{b} \in {\{ 0, \ldots, B-1\}}^M\), which assigns each node to a specific example. (default:
None
)cosine (bool, optional) – If
True
, will use the cosine distance instead of euclidean distance to find nearest neighbors. (default:False
)num_workers (int, optional) – Number of workers to use for computation. Has no effect in case
batch_x
orbatch_y
is notNone
, or the input lies on the GPU. (default:1
)batch_size (int, optional) – The number of examples \(B\). Automatically calculated if not given. (default:
None
)
- Return type:
torch.Tensor