【发布时间】:2018-02-19 00:43:16
【问题描述】:
我想为每一行返回一个非零索引的密集张量。例如,给定张量:
[0,1,1]
[1,0,0]
[0,0,1]
[0,1,0]
应该返回
[1,2]
[0]
[2]
[1]
我可以使用 tf.where() 获取索引,但我不知道如何根据第一个索引组合结果。例如:
graph = tf.Graph()
with graph.as_default():
data = tf.constant([[0,1,1],[1,0,0],[0,0,1],[0,1,0]])
indices = tf.where(tf.not_equal(data,0))
sess = tf.InteractiveSession(graph=graph)
sess.run(tf.local_variables_initializer())
print(sess.run([indices]))
以上代码返回:
[array([[0, 1],
[0, 2],
[1, 0],
[2, 2],
[3, 1]])]
但是,我想根据这些索引的第一列组合结果。有人可以建议一种方法吗?
更新
试图使其适用于更多维度并遇到错误。如果我在矩阵上运行下面的代码
sess = tf.InteractiveSession()
a = tf.constant([[0, 1, 1, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 1, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 1, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 1, 1, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 1, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 1, 0, 1],
[0, 0, 0, 0, 0, 0, 0, 0, 1, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 1],
[1, 0, 0, 0, 0, 0, 0, 0, 0, 1]])
row_counts = tf.reduce_sum(a, axis=1)
max_padding = tf.reduce_max(row_counts)
extra_padding = max_padding - row_counts
extra_padding_col = tf.expand_dims(extra_padding, 1)
range_row = tf.expand_dims(tf.range(max_padding), 0)
padding_array = tf.cast(tf.tile(range_row, [9, 1])<extra_padding_col, tf.int32)
b = tf.concat([a, padding_array], axis=1)
result = tf.map_fn(lambda x: tf.cast(tf.where(tf.not_equal(x, 0)), tf.int32), b)
result = tf.where(result<=max_padding, result, -1*tf.ones_like(result)) # replace with -1's
result = tf.reshape(result, (int(result.get_shape()[0]), max_padding))
result.eval()
然后我会得到太多的 -1,所以解决方案似乎并不完全存在:
[[ 1, 2],
[ 2, -1],
[-1, -1],
[-1, -1],
[-1, -1],
[-1, -1],
[-1, -1],
[-1, -1],
[ 0, -1]]
【问题讨论】:
标签: python tensorflow