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

时间:2019-04-21 03:44:25

标签: python keras mnist sigmoid

我有以下数组:

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数组(一系列类似于示例中的数组)进行此操作

4 个答案:

答案 0 :(得分:2)

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应该内置一些东西来为您做......

答案 1 :(得分:1)

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

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

答案 2 :(得分:1)

此方法占用两行,但避免了将每个数组元素与max进行比较,并且在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

(这不是您的实际问题,但您是要使用S形激活函数吗?不是softmax吗?您在此处获得的输出不是在10种可能的类中的单一分布(您可以看到相反,您有10个分布,每个类一个(因此,输入为类0的概率为8.1837177e-05,而不是类0的概率为1 - 8.1837177e-05)。在进行多标签分类时(可以应用多个标签),这很有意义,但是您不想找到概率最高的类别,而是预测所有概率都高于阈值(例如0.5)的类别)

答案 3 :(得分:0)

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