2

I have a Tensorflow network and can get the values of the graph after I call Session().run(). However, I have some trouble converting SparseTensorValue to other types.

For example, the following program creates a SparseTensorValue.

>>> import tensorflow as tf
>>> t = tf.Session().run(tf.SparseTensor([[0,1], [0,0], [1,1], [1,0]],[1,2,3,4],[2,2]))
>>> print(t)
SparseTensorValue(indices=array([[0, 1],
       [0, 0],
       [1, 1],
       [1, 0]]), values=array([1, 2, 3, 4], dtype=int32), dense_shape=array([2, 2]))
>>> 

What I want is some way to convert t to a np.array or np.matrix, for example, np.array([[2., 1.], [4., 3.]]).

What I have currently is the following

>>> import numpy as np
>>> a = np.zeros(t.dense_shape)
>>> for i, v in zip(t.indices, t.values) :
...     a[tuple(i)] = v
... 
>>> print(a)
[[2. 1.]
 [4. 3.]]
>>> 

Is there a better way to perform the conversion? Especially, I want to eliminate the for-loop.

2
  • So there's nothing tensorflow that would help you? numpy of course knows nothing about tensorflow, but tf should have something. Commented Aug 29, 2019 at 7:16
  • I am new to Tensorflow, and I did not find a way to perform the conversion through Googleing. Commented Aug 29, 2019 at 7:36

1 Answer 1

7

Thanks to hpaulj's hint, I found the way to convert from Tensorflow's website.

tf.Session().run(tf.sparse.to_dense(tf.sparse.reorder(t)))

First reorder the values to lexicographical order, then use to_dense to make it dense, and finally feed the tensor to Session().run().

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.