由于我不知道稀疏矩阵的任何中值函数,因此想到的唯一替代方法是遍历列,例如使用tf.map_fn():
import tensorflow as tf
A = tf.convert_to_tensor([[ 1, 0, 20, 5],
[-1, 1, 10, 0],
[-2, 1, -10, 2],
[ 0, 2, 20, 1]])
positive_median_fn = lambda x: tf.contrib.distributions.percentile(tf.boolean_mask(x, tf.greater(x, 0)), q=50)
A_t = tf.matrix_transpose(A) # tf.map_fn is applied along 1st dim, so we need to transpose A
res = tf.map_fn(fn=positive_median_fn, elems=A_t)
with tf.Session() as sess:
print(sess.run(res))
# [ 1 1 20 2]
注意:这个 sn-p 不包括列不包含正元素的情况。如果输入张量为空,tf.contrib.distributions.percentile() 将返回错误。例如,可以使用tf.boolean_mask(x, tf.greater(x, 0)) 形状的条件(例如使用tf.where())