Python 如何获得张量/矩阵中列正元素的中值?
特别是给定一个二维矩阵,如何为每列的正元素找到中值 从数学上讲:返回B,其中Python 如何获得张量/矩阵中列正元素的中值?,python,tensorflow,conditional-statements,distribution,median,Python,Tensorflow,Conditional Statements,Distribution,Median,特别是给定一个二维矩阵,如何为每列的正元素找到中值 从数学上讲:返回B,其中B[i]=中位数({A[j,i]|A[j,i]>0}) 我知道中位数可以通过 tf.contrib.distributions.percentile tf.boolean\u mask(A,tf.greater(A,0))输出一个一维列表而不是矩阵。您可以在列切片上循环并像这样过滤 inputlist = [[5 , -10 ] , [10 , 3 ] , [15 , -5 ]
B[i]=中位数({A[j,i]|A[j,i]>0})
我知道中位数可以通过 <代码>tf.contrib.distributions.percentile
tf.boolean\u mask(A,tf.greater(A,0))
输出一个一维列表而不是矩阵。您可以在列切片上循环并像这样过滤
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)))
实际上,返回一个1-D张量,否则,保留维数的结果张量将是稀疏的(c.f.列具有不同数量的正元素)
因为我不知道稀疏矩阵的任何中值函数,所以我想到的唯一替代方法是在列上循环,例如使用:
将tensorflow导入为tf
A=tf.convert_to_张量([[1,0,20,5],
[-1, 1, 10, 0],
[-2, 1, -10, 2],
[ 0, 2, 20, 1]])
正中位数fn=lambda x:tf.contrib.distributions.percentile(tf.boolean\u mask(x,tf.greater(x,0)),q=50)
A_t=tf.matrix_转置(A)#tf.map_fn沿第一维度应用,因此我们需要转置A
res=tf.map\u fn(fn=正中位数,elems=A\u t)
使用tf.Session()作为sess:
打印(sess.run(res))
# [ 1 1 20 2]
注意:此代码段不包括列不包含正元素的情况<如果其输入张量为空,则code>tf.contrib.distributions.percentile()将返回错误。例如,可以使用
tf.boolean_掩码(x,tf.greater(x,0))形状上的条件(例如,与tf.where()
)