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



我有以下数组:

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。

我需要为 2D 数组(一系列类似于示例中的数组)执行此操作

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])

在 2D 情况下,我们取每行的最大值:

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]

此方法需要两行,但它避免将每个数组元素与最大值进行比较,并且在 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 激活函数吗?而不是软最大?你在这里得到的输出不是 10 个可能类的单一分布(你可以看到它甚至没有规范化)。相反,您有 10 个分布,每个类一个(因此,输入为类 0 的概率为8.1837177e-05,不是类 0 的概率为1 - 8.1837177e-05)。这在进行多标签分类(其中可能应用多个标签)时是有意义的,但是您不希望找到概率最高的类,而是预测概率高于阈值(例如 0.5)的所有类。

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])

对于 2D 阵列,您可以执行以下操作:

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的更多信息,请查看此内容
  • 如果你愿意,你可以在TensorFlow中做到这一点,看看这个所以回答

最新更新