获取SparseTensor的非零行

时间:2017-03-07 09:42:41

标签: tensorflow sparse-matrix

我想从SparseTensor中的一行中获取所有非零值,因此“m”是我所拥有的稀疏张量对象,而行是我想从中得到所有非零值和索引的行。所以我想返回一对[(index,values)]的数组。我希望我能得到关于这个问题的帮助。

# -*- coding: utf-8 -*-

import os, sys

for i=0:10 
l = i;
for word in l:
    os.system("convert -fill black -background white -bordercolor red -border 6 -font AponaLohit.ttf -pointsize 100 label:\"%s\" \"%s.png\""%(word, word))

终端

中的错误消息
def nonzeros( m, row):
    res = []
    indices = m.indices
    values = m.values
    userindices = tf.where(tf.equal(indices[:,0], tf.constant(0, dtype=tf.int64)))
    res = tf.map_fn(lambda index:(indices[index][1], values[index]), userindices)
    return res

编辑: 非零的输入 cm是一个值为

的coo_matrix
TypeError: Input 'strides' of 'StridedSlice' Op has type int32 that does not match type int64 of argument 'begin'.

如果数据是

m = tf.SparseTensor(indices=np.array([row,col]).T,
                        values=cm.data,
                        dense_shape=[10, 10])
nonzeros(m, 1)

结果应该是

[[ 0.  1.  0.  0.  0.  0.  0.  0.  0.  1.]
 [ 0.  0.  0.  0.  1.  0.  0.  0.  0.  2.]
 [ 0.  0.  0.  1.  0.  0.  0.  0.  0.  0.]
 [ 0.  0.  0.  0.  0.  0.  0.  0.  0.  1.]
 [ 0.  0.  0.  0.  0.  0.  0.  0.  0.  0.]
 [ 0.  0.  0.  0.  0.  0.  0.  0.  0.  0.]
 [ 0.  0.  0.  0.  0.  0.  0.  0.  0.  0.]
 [ 0.  0.  0.  0.  0.  0.  0.  0.  0.  0.]
 [ 0.  0.  0.  0.  0.  0.  0.  0.  0.  0.]
 [ 0.  0.  0.  0.  0.  0.  0.  0.  0.  1.]]

1 个答案:

答案 0 :(得分:2)

问题是lambda中的index是Tensor,你不能直接使用它来索引例如indices。您可以使用tf.gather代替。另外,您没有使用您发布的代码中的row参数。

请改为尝试:

import tensorflow as tf
import numpy as np

def nonzeros(m, row):
    indices = m.indices
    values = m.values
    userindices = tf.where(tf.equal(indices[:, 0], row))
    found_idx = tf.gather(indices, userindices)[:, 0, 1]
    found_vals = tf.gather(values, userindices)[:, 0:1]
    res = tf.concat(1, [tf.expand_dims(tf.cast(found_idx, tf.float64), -1), found_vals])
    return res

data = np.array([[0.,  1.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  1.],
                [0., 0.,  0.,  0.,  1.,  0.,  0.,  0.,  0.,  2.]])

m = tf.SparseTensor(indices=np.array([[0, 1], [0, 9], [1, 4], [1, 9]]),
                    values=np.array([1.0, 1.0, 1.0, 2.0]),
                    shape=[2, 10])

with tf.Session() as sess:
    result = nonzeros(m, 1)
    print(sess.run(result))

打印:

[[ 4.  1.]
 [ 9.  2.]]