How to get a new sparse tensor with grad

Hi,
I have a tensor edge_v(stores value) with grad and a 2d array edge(stores index), how can i get a sparse_coo_tensor with grad?

if i code like this, sgraph has no grad.
sgraph =sp.coo_matrix((edge_v.tolist(), (edge[0], edge[1])),
shape=(input.shape[0], input.shape[0]),
dtype=np.float32)

if i code like this,it will get error.
sgraph =sp.coo_matrix((edge_v, (edge[0], edge[1])),
shape=(input.shape[0], input.shape[0]),
dtype=np.float32)

this will get error either.
sgraph = torch.sparse_coo_tensor(edge, edge_v, shape=(input.shape[0], input.shape[0]),dtype=np.float32)

Hi,
The syntax is as follows :

torch.sparse_coo_tensor(indices, values, size=None, *, dtype=None, device=None, requires_grad=False)

Here indices represent the coordinates of the non-zero values in the matrix, and thus should be 2-dimensional. indices = edge in your case.

So, try this-
sgraph = torch.sparse_coo_tensor(indices=edge, values=edge_v, dtype=torch.float32, requires_grad=True)

Additionally, size argument is inferred automatically in case you do not manually provide a size for the sparse tensor required.

Hope this helps,
Srishti

Thanks for your solution, it works!

sgraph = torch.sparse_coo_tensor(indices=edge,
values=edge_v,dtype=torch.float32,requires_grad=True)