2016-10-03 93 views
7

我正在创建一个卷积稀疏自动编码器,我需要将一个充满了值(其形状为[samples, N, N, D])的4D矩阵转换为稀疏矩阵。从一个密集的Tensorflow稀疏矩阵

对于每个样本,我都有D NxN个特征映射。我想将每个NxN特征映射转换为一个稀疏矩阵,最大值映射为1,所有其他映射为0.

我不想在运行时执行此操作,但在Graph声明期间(因为我需要使用最终的稀疏矩阵作为其他图操作的输入),但我不明白如何获取索引来构建稀疏矩阵。

+0

你想要做的Tensorflow或在此转换蟒蛇?如果在Python中这个函数可以帮助你从密集转换为稀疏矩阵(http://docs.scipy.org/doc/scipy/reference/generated/scipy.sparse.coo_matrix.html#scipy.sparse.coo_matrix)你可以使用tf.SparseTensor(它使用coo格式)来存储每个特征映射,并使用列表来存储所有稀疏张量。 –

+0

具体来说,非零()(http://docs.scipy.org/doc/scipy/reference/generated/scipy.sparse.coo_matrix.nonzero.html#scipy.sparse.coo_matrix.nonzero)可以为您提供非零元素。不知道这是否被认为是运行时方法。这可能是图形声明之前的一些数据预处理。 4D密集矩阵是在运行时生成的还是仅仅是一些给定的输入数据? –

+0

我不想在运行时做到这一点(我知道如何与numpy做到这一点),但在图形声明(所以与Tensorflow) – Cramer

回答

9

您可以使用tf.wheretf.gather_nd做到这一点:

import numpy as np 
import tensorflow as tf 

# Make a tensor from a constant 
a = np.reshape(np.arange(24), (3, 4, 2)) 
a_t = tf.constant(a) 
# Find indices where the tensor is not zero 
idx = tf.where(tf.not_equal(a_t, 0)) 
# Make the sparse tensor 
# 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()) 
# Make a dense tensor back from the sparse one, only to check result is correct 
dense = tf.sparse_tensor_to_dense(sparse) 
# Check result 
with tf.Session() as sess: 
    b = sess.run(dense) 
np.all(a == b) 
>>> True 
+0

如何用张量做到这一点?就像我想把张量转换成稀疏的。 –

+1

@RocketPingu不知道你的意思,这是为了将一个密集的张量转换成一个稀疏的张量。 'a_t'在这里是一个规则的TensorFlow张量(在这种情况下是从'tf.constant'运算得到的,但可以是任何其他运算的输出)。为了清晰起见,我添加了一些评论。 – jdehesa

+0

只是当我为我的代码尝试它时,它给了我一个错误。更多关于它在这里:https://stackoverflow.com/questions/48201725/converting-tensor-to-a-sparsetensor –

1

简单的代码来密集numpy的数组转换为tf.SparseTensor:

def denseNDArrayToSparseTensor(arr): 
    idx = np.where(arr != 0.0) 
    return tf.SparseTensor(np.vstack(idx).T, arr[idx], arr.shape)