【问题标题】:Numpy reverse keras to_categoricalNumpy反向keras to_categorical
【发布时间】:2023-04-09 05:37:01
【问题描述】:

在 keras 中,我使用to_categorical 将二进制 nx1 向量 y 转换为 nx2 矩阵,如果 y=1,则第一列为 1,第二列为 y=0。如何使用 numpy 反转此操作?

【问题讨论】:

  • 你可以使用argmax
  • np.argmax(a, axis = 1)

标签: numpy keras


【解决方案1】:

简单。

numpy.argmax(a, axis=None, out=None)

这将返回沿轴的最大值的索引。

【讨论】:

    【解决方案2】:

    添加到 MazeRunner09 的答案。如果您使用 keras 中的 to_categorical,您将拥有一个列表,并且可以对整个 one-hot 编码列表使用列表推导:

    y_classes = [np.argmax(y, axis=None, out=None) for y in y_test]
    

    【讨论】:

      【解决方案3】:

      无需进行列表理解。简单的

      numpy.argmax(a, axis=1)
      

      将在所有行的每一行中找到 argmax

      【讨论】:

      • 这应该是答案。
      【解决方案4】:

      这是一个如何在 tensorflow keras 中反转标签的完整示例:

      label = [0,1,1,0]
      label = tf.keras.utils.to_categorical(label)
      print(label) #output: label = [[1,0],[0,1],[0,1],[1,0]]
      label = tf.math.argmax(label, axis=1)
      print(label) #output back to [0,1,1,0]
      

      【讨论】:

        猜你喜欢
        • 2018-07-02
        • 2019-10-08
        • 2019-03-02
        • 2021-08-14
        • 2018-11-10
        • 1970-01-01
        • 2018-05-05
        • 2018-07-07
        • 2021-07-26
        相关资源
        最近更新 更多