Python 计算TensorFlow中tf.SparsetSensor每行的平均值

Python 计算TensorFlow中tf.SparsetSensor每行的平均值,python,tensorflow,Python,Tensorflow,我想计算atf.SparseTensor的axis=0的平均值。我想要类似于tf.sparse\u reduce\u sum的东西。TensorFlow没有为平均值计算提供类似的函数。有没有办法计算每行中的值,以便将它们除以总和 indices = np.array([[0, 0], [0, 1], [0, 2], [0, 3], [0, 4], [0, 5], [1, 0], [1, 1], [1, 3], [1, 4], [1, 5],

我想计算a
tf.SparseTensor
的axis=0的平均值。我想要类似于
tf.sparse\u reduce\u sum
的东西。TensorFlow没有为平均值计算提供类似的函数。有没有办法计算每行中的值,以便将它们除以总和

indices = np.array([[0, 0], [0, 1], [0, 2], [0, 3], [0, 4], [0, 5],
               [1, 0], [1, 1], [1, 3], [1, 4], [1, 5],
               [2, 1], [2, 2], [2, 3], [2, 4],
               [3, 0], [3, 1], [3, 2], [3, 3], [3, 4], [3, 5],
               [4, 0], [4, 2], [4, 3], [4, 4], [4, 5]], dtype=np.int64)

values = np.array([7, 6, 7, 4, 5, 4,
                   6, 7, 4, 3, 4,
                   3, 3, 1, 1,
                   1, 2, 2, 3, 3, 4,
                   1, 1, 2, 3, 3], dtype=np.float64)

dense_shape = np.array([5, 6], dtype=np.int64)

tRatings = tf.SparseTensor(indices, values, dense_shape)

尝试使用
get_shape()
然后乘以
shape[0]*shape[1]
这是元素的总数

您可以通过除以第0维度的大小,从减少的和中计算减少的平均值:

tRatings = tf.SparseTensor(indices, values, dense_shape)
reduced_sum = tf.sparse_reduce_sum(tRatings, 0)  # Sum of each row
reduced_mean = reduced_sum / tf.cast(tRatings.dense_shape[0], tf.float64)  # Mean of each row

这就是稠密张量的表现形式。为了计算每行的平均值,我需要计算稠密张量每行的元素。使用
tf.sparse\u reduce\u sum(张量,1)
,你将得到另一个张量和每行的总和,正如你在示例中所读到的,然后使用
tf.divide(张量,形状[1])
,你将得到每行的平均值