2024-04-29 01:23:50 发布
网友
特别是给定一个二维矩阵,如何为每一列的正元素求中值?你知道吗
从数学上讲:返回B,其中B[i] = median({A[j, i] | A[j, i] > 0})
B[i] = median({A[j, i] | A[j, i] > 0})
我知道中位数可以用tf.contrib.distributions.percentile来计算
tf.contrib.distributions.percentile
tf.boolean_mask(A, tf.greater(A, 0))输出一维列表而不是矩阵。你知道吗
tf.boolean_mask(A, tf.greater(A, 0))
^{}确实返回一个一维张量,否则保留维数的结果张量将是稀疏的(c.f.列具有不同数量的正元素)。你知道吗
因为我不知道稀疏矩阵的任何中值函数,所以我想到的唯一替代方法是在列上循环,例如使用^{}:
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]
注意:此代码段不包括列不包含正元素的情况。tf.contrib.distributions.percentile()如果其输入张量为空,则返回一个错误。例如,可以使用tf.boolean_mask(x, tf.greater(x, 0))形状的条件(例如与tf.where())
tf.contrib.distributions.percentile()
tf.boolean_mask(x, tf.greater(x, 0))
tf.where()
你可以在列切片上循环并像这样过滤。你知道吗
inputlist = [[5 , -10 ] , [10 , 3 ] , [15 , -5 ]] x = tf.Variable(initial_value=inputlist) sess = tf.Session() sess.run(tf.global_variables_initializer()) for i in range(x.get_shape().as_list()[1]) : #loop over columns print( sess.run(tf.contrib.distributions.percentile(tf.gather(x[:,i], tf.where(tf.greater(x[:,i], 0))), 50.0)))
^{} 确实返回一个一维张量,否则保留维数的结果张量将是稀疏的(c.f.列具有不同数量的正元素)。你知道吗
因为我不知道稀疏矩阵的任何中值函数,所以我想到的唯一替代方法是在列上循环,例如使用^{} :
注意:此代码段不包括列不包含正元素的情况。
tf.contrib.distributions.percentile()
如果其输入张量为空,则返回一个错误。例如,可以使用tf.boolean_mask(x, tf.greater(x, 0))
形状的条件(例如与tf.where()
)你可以在列切片上循环并像这样过滤。你知道吗
相关问题 更多 >
编程相关推荐