Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/344.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何计算2D张量每行的屏蔽平均值?_Python_Tensorflow_Mean - Fatal编程技术网

Python 如何计算2D张量每行的屏蔽平均值?

Python 如何计算2D张量每行的屏蔽平均值?,python,tensorflow,mean,Python,Tensorflow,Mean,我有这样一个二维张量: [[1.0.0.2.1.0.1] [0. 0. 0. 1. 0. 0. 0.] [2. 0. 2. 1. 1. 3. 0.]] 我想计算每行中每一个非零元素的平均值,结果是: [1.25 1.1.8] 如何使用TensorFlow做到这一点?计算每行屏蔽平均数的一种方法是使用。实际上,每行可以有一个段id,然后用一个额外的id替换屏蔽元素的段id import tensorflow as tf with tf.Graph().as_default(), tf.Ses

我有这样一个二维张量:

[[1.0.0.2.1.0.1]
[0. 0. 0. 1. 0. 0. 0.]
[2. 0. 2. 1. 1. 3. 0.]]
我想计算每行中每一个非零元素的平均值,结果是:

[1.25 1.1.8]

如何使用TensorFlow做到这一点?

计算每行屏蔽平均数的一种方法是使用。实际上,每行可以有一个段id,然后用一个额外的id替换屏蔽元素的段id

import tensorflow as tf

with tf.Graph().as_default(), tf.Session() as sess:
    x = tf.constant([[1., 0., 0., 2., 1., 0., 1.],
                     [0., 0., 0., 1., 0., 0., 0.],
                     [2., 0., 2., 1., 1., 3., 0.]], tf.float32)
    s = tf.shape(x)
    num_rows = s[0]
    num_cols = s[1]
    # Mask for selected elements
    mask = tf.not_equal(x, 0)
    # Make per-row ids
    row_id = tf.tile(tf.expand_dims(tf.range(num_rows), 1), [1, num_cols])
    # Id is replaced for masked elements
    seg_id = tf.where(mask, row_id, num_rows * tf.ones_like(row_id))
    # Take segmented mean discarding last value (mean of masked elements)
    out = tf.math.unsorted_segment_mean(tf.reshape(x, [-1]), tf.reshape(seg_id, [-1]),
                                        num_rows + 1)[:-1]
    print(sess.run(out))
    # [1.25 1.   1.8 ]
但是,由于在这种情况下,掩码正好用于非零元素,因此您也可以仅使用:


我们可以使用
tf.map\u fn
来实现这一点:

x=tf.常数([[1,0,0,2,1,0,1.],
[0., 0., 0., 1., 0., 0., 0.],
[2,0,2,1,1,3,0.]
def平均值(世界其他地区):
掩码=tf.不相等(行,0.0)
过滤=tf.boolean_掩码(行,掩码)
返回tf.reduce_平均值(已过滤)
out=tf.map\u fn(平均值,x)

就计算速度而言,我不知道这与jdehesa的综合(投票表决!)答案相比如何(很高兴承认我根本不知道
tf.math.count\u nonzero
tf.math.unsorted\u segment\u的意思是
)。我把它贴在这里,作为一种更通用的方式来做“这类事情”,我觉得很有用。谢谢,通常是
tf。map\u fn
不是很快,但是
tf.math。未排序的\u segment\u意思是
也不是很快,所以值得比较。无论如何,是的,对于类似的问题,这是一个很好的通用方法。
import tensorflow as tf

with tf.Graph().as_default(), tf.Session() as sess:
    x = tf.constant([[1., 0., 0., 2., 1., 0., 1.],
                     [0., 0., 0., 1., 0., 0., 0.],
                     [2., 0., 2., 1., 1., 3., 0.]], tf.float32)
    x_sum = tf.reduce_sum(x, axis=1)
    x_count = tf.cast(tf.count_nonzero(x, axis=1), x.dtype)
    # Using maximum avoids problems when all elements are zero
    out = x_sum / tf.maximum(x_count, 1)
    print(sess.run(out))
    # [1.25 1.   1.8 ]