【问题标题】:Compute the mean for each row from a tf.SparseTensor in TensorFlow从 TensorFlow 中的 tf.SparseTensor 计算每一行的平均值
【发布时间】:2018-10-16 05:45:17
【问题描述】:

我想计算tf.SparseTensor 的axis=0 的平均值。我想要tf.sparse_reduce_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)

【问题讨论】:

    标签: python tensorflow


    【解决方案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
    

    【讨论】:

      【解决方案2】:

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

      【讨论】:

      • 那将是稠密张量的代表形状。我需要计算密集张量的每一行的元素,以便计算每一行的平均值。
      • 使用tf.sparse_reduce_sum(tensor, 1),你会得到另一个张量,每行的总和,你可以在例子tensorflow.org/api_docs/python/tf/sparse_reduce_sum中读到,然后使用tf.divide(tensor, shape[1]),你会得到每一行的平均值
      猜你喜欢
      • 2019-01-05
      • 1970-01-01
      • 2019-04-03
      • 2014-04-23
      • 2021-07-24
      • 1970-01-01
      • 2016-09-02
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多