Unverified Commit 20ce9be2 authored by czkkkkkk's avatar czkkkkkk Committed by GitHub
Browse files

[Sparse] Add spmatrix creation function (#5209)



* [Sparse] Add spmatrix creation function

* Update

* Update sparse_matrix.py

* Update sparse_matrix.py
Co-authored-by: default avatarHongzhi (Steve), Chen <chenhongzhi.nkcs@gmail.com>
parent 6d280524
...@@ -465,6 +465,80 @@ class SparseMatrix: ...@@ -465,6 +465,80 @@ class SparseMatrix:
return self.c_sparse_matrix.has_duplicate() return self.c_sparse_matrix.has_duplicate()
def spmatrix(
indices: torch.Tensor,
val: Optional[torch.Tensor] = None,
shape: Optional[Tuple[int, int]] = None,
) -> SparseMatrix:
r"""Creates a sparse matrix from Coordinate format indices.
Parameters
----------
indices : tensor.Tensor
The indices are the coordinates of the non-zero elements in the matrix,
which should have shape of ``(2, N)`` where the first row is the row
indices and the second row is the column indices of non-zero elements.
val : tensor.Tensor, optional
The values of shape (nnz) or (nnz, D). If None, it will be a tensor of
shape (nnz) filled by 1.
shape : tuple[int, int], optional
If not specified, it will be inferred from :attr:`row` and :attr:`col`,
i.e., (row.max() + 1, col.max() + 1). Otherwise, :attr:`shape` should
be no smaller than this.
Returns
-------
SparseMatrix
Sparse matrix
Examples
--------
Case1: Sparse matrix with row and column indices without values.
>>> indices = torch.tensor([[1, 1, 2],
>>> [2, 4, 3]])
>>> A = dglsp.spmatrix(indices)
SparseMatrix(indices=tensor([[1, 1, 2],
[2, 4, 3]]),
values=tensor([1., 1., 1.]),
shape=(3, 5), nnz=3)
>>> # Specify shape
>>> A = dglsp.spmatrix(indices, shape=(5, 5))
SparseMatrix(indices=tensor([[1, 1, 2],
[2, 4, 3]]),
values=tensor([1., 1., 1.]),
shape=(5, 5), nnz=3)
Case2: Sparse matrix with scalar values.
>>> indices = torch.tensor([[1, 1, 2],
>>> [2, 4, 3]])
>>> val = torch.tensor([[1.], [2.], [3.]])
>>> A = dglsp.spmatrix(indices, val)
SparseMatrix(indices=tensor([[1, 1, 2],
[2, 4, 3]]),
values=tensor([[1.],
[2.],
[3.]]),
shape=(3, 5), nnz=3, val_size=(1,))
Case3: Sparse matrix with vector values.
>>> indices = torch.tensor([[1, 1, 2],
>>> [2, 4, 3]])
>>> val = torch.tensor([[1., 1.], [2., 2.], [3., 3.]])
>>> A = dglsp.spmatrix(indices, val)
SparseMatrix(indices=tensor([[1, 1, 2],
[2, 4, 3]]),
values=tensor([[1., 1.],
[2., 2.],
[3., 3.]]),
shape=(3, 5), nnz=3, val_size=(2,))
"""
return from_coo(indices[0], indices[1], val, shape)
def from_coo( def from_coo(
row: torch.Tensor, row: torch.Tensor,
col: torch.Tensor, col: torch.Tensor,
......
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment