2017-02-09 156 views
1

利用TensorFlow的HashTable查找实现,我使用提供的默认值返回SparseTensor。我想清除它并得到一个没有默认值的最终SparseTensor。如何从稀疏张量中获取非零值

如何清除该默认值?我不介意为了实现这个目的,默认值是什么。 0很好,所以是-1。

回答

0

tf.sparse_retain应该工作:

def sparse_remove(sparse_tensor, remove_value=0.): 
    return tf.sparse_retain(sparse_tensor, tf.not_equal(a.values, remove_value)) 

举个例子:

import tensorflow as tf 

a = tf.SparseTensor(indices=[[1, 2], [2, 2]], values=[0., 1.], shape=[3, 3]) 
with tf.Session() as session: 
    print(session.run([a, sparse_remove(a)])) 

打印(我稍微重新格式化吧):

[SparseTensorValue(indices=array([[1, 2], [2, 2]]), values=array([ 0., 1.], dtype=float32), shape=array([3, 3])), 
SparseTensorValue(indices=array([[2, 2]]), values=array([ 1.], dtype=float32), shape=array([3, 3]))] 
相关问题