【问题标题】:gather values from 2dim tensor in tensorflow从张量流中的 2dim 张量收集值
【发布时间】:2018-06-25 02:26:46
【问题描述】:

您好 tensorflow 初学者...我正在尝试从 2 暗张量中获取某些元素的值,在我的案例中,类分数来自概率矩阵。

概率矩阵为 (1000,81),批大小为 1000,类别数为 81。ClassID 为 (1000,),包含每个样本的最高类别分数的索引。如何使用 tf.gather 从概率矩阵中得到对应的班级分数?

class_ids = tf.cast(tf.argmax(probs, axis=1), tf.int32)  
class_scores = tf.gather_nd(probs,class_ids)

class_scores 应该是一个形状为 (1000) 的张量,其中包含每个样本的最高 class_score。

现在我正在使用如下所示的解决方法:

class_score_count = []
for i in range(probs.shape[0]):
    prob = probs[i,:]
    class_score = prob[class_ids[i]]
    class_score_count.append(class_score)
class_scores = tf.stack(class_score_count, axis=0)

感谢您的帮助!

【问题讨论】:

    标签: tensorflow


    【解决方案1】:

    你可以像这样使用tf.gather_nd

    class_ids = tf.cast(tf.argmax(probs, axis=1), tf.int32)
    # If shape is not dynamic you can use probs.shape[0].value instead of tf.shape(probs)[0]
    row_ids = tf.range(tf.shape(probs)[0], dtype=tf.int32)
    idx = tf.stack([row_ids, class_ids], axis=1)
    class_scores = tf.gather_nd(probs, idx)
    

    您也可以只使用tf.reduce_max,尽管它实际上会再次计算最大值,但如果您的数据不是太大,它可能不会慢很多:

    class_scores = tf.reduce_max(probs, axis=1)
    

    【讨论】:

    • 谢谢!两种解决方案都有效。 tf.reduce_max 在我的情况下效果很好。
    【解决方案2】:
    • 你需要运行张量 class_ids 来获取值
    • 这些值将是一个颠簸的数组
    • 你可以通过循环正常访问numpy数组
    • 你必须这样做: predictions = sess.run(tf.argmax(probs, 1), feed_dict={x: X_data})
    • predictions 变量包含您需要的所有信息
    • tensorflow 只返回那些你显式运行的张量值

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-02-13
      • 2017-10-05
      • 1970-01-01
      • 2017-12-01
      • 2018-05-01
      • 2017-11-05
      相关资源
      最近更新 更多