# chainer.utils.to_coo¶

chainer.utils.to_coo(x, ldnz=None, requires_grad=False)[source]

Returns a single or a batch of matrices in COO format.

Parameters
• x (N-dimensional array) – Input dense matrix. The ndim of x must be two or three. If ndim is two, it is treated as a single matrix. If three, it is treated as batched matrices.

• ldnz (int) – Size of arrays for data, row index and column index to be created. The Actual size becomes max(nnz, ldnz) where nnz is number of non-zero elements in a input dense matrix.

• requires_grad (bool) – If True, gradient of sparse matrix will be computed in back-propagation.

Returns

A sparse matrix or batched sparse matrices in COO format of a given dense matrix or batched dense matrices.

Return type

CooMatrix

Example

Create a CooMatrix from an array with 2 non-zero elements and 4 zeros and access its attributes. No batch dimension is involved.

>>> data = np.array([[0, 2, 0], [-1, 0, 0]], np.float32)
>>> x = chainer.utils.to_coo(data)
>>> x.data
variable([ 2., -1.])
>>> x.row
array([0, 1], dtype=int32)
>>> x.col
array([1, 0], dtype=int32)
>>> x.shape
(2, 3)