这不可能是一个合适的张量,因为维度不统一。如果您愿意使用不规则张量,您可以执行以下操作:
import tensorflow as tf
with tf.Graph().as_default(), tf.Session() as sess:
b = tf.constant([[1, 0, 0, 0, 0],
[1, 0, 1, 0, 1]],dtype=tf.float32)
num_rows = tf.shape(b)[0]
zero = tf.constant(0, dtype=tf.float32)
where = tf.not_equal(b, zero)
indices = tf.where(where)
s = tf.ragged.segment_ids_to_row_splits(indices[:, 0], num_rows)
row_start = s[:-1]
elem_per_row = s[1:] - row_start
idx = tf.expand_dims(row_start, 1) + tf.ragged.range(elem_per_row)
result = tf.gather(indices[:, 1], idx)
print(sess.run(result))
编辑:如果您不想或无法使用不规则张量,则可以尝试另一种方法。您可以生成一个填充有“无效”值的张量。您可以在这些无效值中使用例如-1,也可以只是有一个1D张量,告诉您每行有多少个有效值:
import tensorflow as tf
with tf.Graph().as_default(), tf.Session() as sess:
b = tf.constant([[1, 0, 0, 0, 0],
[1, 0, 1, 0, 1]],dtype=tf.float32)
num_rows = tf.shape(b)[0]
zero = tf.constant(0, dtype=tf.float32)
where = tf.not_equal(b, zero)
indices = tf.where(where)
num_indices = tf.shape(indices)[0]
elem_per_row = tf.bincount(tf.cast(indices[:, 0], tf.int32), minlength=num_rows)
row_start = tf.concat([[0], tf.cumsum(elem_per_row[:-1])], axis=0)
max_elem_per_row = tf.reduce_max(elem_per_row)
r = tf.range(max_elem_per_row)
idx = tf.expand_dims(row_start, 1) + r
idx = tf.minimum(idx, num_indices - 1)
result = tf.gather(indices[:, 1], idx)
result = tf.where(tf.expand_dims(elem_per_row, 1) > r, result, -tf.ones_like(result))
print(sess.run(result))
print(sess.run(elem_per_row))