# Sparse tensor construction from Variable

**URL:** <https://discuss.pytorch.org/t/sparse-tensor-construction-from-variable/14224>\
**Category:** autograd\
**Created:** [March 1, 2018, 8:46pm UTC](https://discuss.pytorch.org/t/sparse-tensor-construction-from-variable/14224 "2018-03-01T20:46:30Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![agarret7](https://discuss.pytorch.org/user_avatar/discuss.pytorch.org/agarret7/32/4146_2.png) [@agarret7](https://discuss.pytorch.org/u/agarret7)\
**Post date:** [March 1, 2018, 8:46pm UTC](https://discuss.pytorch.org/t/sparse-tensor-construction-from-variable/14224/1 "2018-03-01T20:46:30Z")

</div>

From what I’ve read it appears that support for sparse tensors is still relatively unsupported, so I don’t have a ton of confidence that this is possible, but is it possible to construct a sparse tensor from a Variable? If this isn’t possible, how could I take a list of indices of length N, a list of values of length N, and put the nth value into the corresponding nth index of some new tensor?  
Essentially I’m looking for an equivalent to the sparse tensor construction, but where the values can be Variable.

---

<div class="post-metadata">

**Author:** ![richard](https://discuss.pytorch.org/user_avatar/discuss.pytorch.org/richard/32/1861_2.png) [@richard](https://discuss.pytorch.org/u/richard)\
**Post date:** [March 2, 2018, 5:58pm UTC](https://discuss.pytorch.org/t/sparse-tensor-construction-from-variable/14224/2 "2018-03-02T17:58:15Z")

</div>

You can always call .data to get a tensor from a variable.

```auto
import torch
from torch.autograd import Variable
i = Variable(torch.LongTensor([[0, 1, 1, 2, 2],
                     [2, 0, 2, 1, 0]]))
v = Variable(torch.FloatTensor([3, 4, 5, 1, 2]))
x = Variable(torch.sparse.FloatTensor(i.data, v.data, torch.Size([3,3])))

```

There is better support for this on master right now, though, if building from source is an option.

---

<div class="post-metadata">

**Author:** ![agarret7](https://discuss.pytorch.org/user_avatar/discuss.pytorch.org/agarret7/32/4146_2.png) [@agarret7](https://discuss.pytorch.org/u/agarret7)\
**Post date:** [March 2, 2018, 8:21pm UTC](https://discuss.pytorch.org/t/sparse-tensor-construction-from-variable/14224/3 "2018-03-02T20:21:47Z")

</div>

I know that this is possible, but it doesn’t preserve the computation graph which is what I’m aiming for.
