如何将 sigmoid 激活函数输出转换为 0 和 1?

How can I convert the sigmoid activation function outputs to 0s and 1s?

我有以下数组:

array([8.1837177e-05, 1.0788739e-03, 4.4837892e-03, 3.4919381e-04, 7.6085329e-05, 7.6562166e-05, 5.3864717e-04, 5.4001808e-04,  3.3849746e-02, 2.9903650e-04], dtype = float32)

我想把它转换成这个:

array([0, 0, 0, 0, 0, 0, 0, 0, 1, 0], dtype = float32)

我需要找到该行的最大值,将其替换为 1。然后,将该行的其他 9 个值替换为 0。

我需要为二维数组(一系列看起来像示例中的数组)完成此操作

结合使用np.wheremax:

a = np.array([8.1837177e-05, 1.0788739e-03, 4.4837892e-03, 3.4919381e-04, 7.6085329e-05, 7.6562166e-05, 5.3864717e-04, 5.4001808e-04,  3.3849746e-02, 2.9903650e-04])

np.where(a == a.max(), 1, 0)

输出:

array([0, 0, 0, 0, 0, 0, 0, 0, 1, 0])

在二维情况下,我们取每一行的最大值:

np.where(a == a.max(axis=1)[:, np.newaxis], 1, 0)

就是说,我觉得 keras 应该内置一些东西来为你做这件事...

您可以像这样使用列表理解:

x = [5,6,7,8,9]
y = [1 if num == max(x) else 0 for num in x]
x = array([1, 2, 3, 4])


x = np.where(x == max(x), 1, 0) # will replace max with 1 and the others with 0

这将创建:

array([0, 0, 0, 1])

对于二维数组,您可以执行以下操作:

x = array([[0, 3, 4, 5],
           [1, 2, 3, 1],
           [6, 9, 1, 2]])

x = np.array([np.where(l == max(l), 1, 0) for l in x])

这将创建:

array([[0, 0, 0, 1],
       [0, 0, 1, 0],
       [0, 1, 0, 0]])`

  • 有关使用 numpy.where check out this
  • 的更多信息
  • 如果你愿意,你可以在tensorflow中做这个,

此方法需要两行,但它避免了将每个数组元素与最大值进行比较,并且在 2D 中运行良好。我不知道它真的会更快(当然不是渐近),但我认为两行比在 python 中为 2D 执行 for 循环更好,并且可读性可能比使用 np.where.

import numpy as np

# here's your example input
# note - the input must be 2D even if there's just one row
# it's easy to adapt this to the 1D case, but you'll be working with 2D arrays for this anyway
class_probs = np.array([[
    8.1837177e-05, 1.0788739e-03, 4.4837892e-03, 3.4919381e-04, 7.6085329e-05,
    7.6562166e-05, 5.3864717e-04, 5.4001808e-04, 3.3849746e-02, 2.9903650e-04,
]])
pred_classes = np.zeros_like(class_probs)
pred_classes[range(len(class_probs)), class_probs.argmax(-1)] = 1
print(pred_classes) # [[0. 0. 0. 0. 0. 0. 0. 0. 1. 0.]]

# and here's showing the same code works for multiple rows
class_probs = np.random.rand(100, 10)
pred_classes = np.zeros_like(class_probs)
pred_classes[range(len(class_probs)), class_probs.argmax(-1)] = 1
pred_classes

(这不是您的实际问题,但您的意思是要使用 sigmoid 激活函数吗?而不是 softmax?您在这里得到的输出不是 10 个可能的单一分布 classes(你可以看到它甚至没有归一化)。相反,你有 10 个分布,每个 class(因此,输入 class 0 的概率是 8.1837177e-05 并且不是 class 0 的概率是 1 - 8.1837177e-05)。这在进行多标签 class 化(可以应用多个标签)时是有意义的,但是你不会想要要找到概率最高的 class,您需要预测概率高于阈值(例如 0.5)的所有 class。)