2017-02-09 89 views
4

我想將未壓縮的稀疏數組轉換爲tf.SparseTensor接受的格式。有一個內置函數tf.sparse_to_dense,正好與我正在做的相反。所以我的問題是Tensorflow或Python中有什麼內置功能來做這種轉換?Tensorflow dense_to_sparse

+0

按我所知,沒有任何這樣。但是你可以實現一個。作爲參考,您可以查看https://github.com/fchollet/keras/blob/master/keras/backend/tensorflow_backend.py#L2982-L3015 – indraforyou

+1

[密集的一個Tensorflow稀疏矩陣](https:// stackoverflow.com/questions/39838234/sparse-matrix-from-a-dense-one-tensorflow) –

回答

3

according to this question:

你可以用這個做到這一點:

您可以使用tf.where和tf.gather_nd做到這一點:

a = np.reshape(np.arange(24), (3, 4, 2)) 
with tf.Session() as sess: 
    a_t = tf.constant(a) 
    idx = tf.where(tf.not_equal(a_t, 0)) 
    # Use tf.shape(a_t, out_type=tf.int64) instead of a_t.get_shape() if tensor shape is dynamic 
    sparse = tf.SparseTensor(idx, tf.gather_nd(a_t, idx), a_t.get_shape()) 
    dense = tf.sparse_tensor_to_dense(sparse) 
    b = sess.run(dense) 
np.all(a == b) 
>>> True 
+0

是否有可能將TF圖中的變量從稠密替換爲稀疏,以便圖表起作用? – pcejrowski