简体   繁体   中英

How to convert SparseTensorValue to numpy array?

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.

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() .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM