繁体   English   中英

如何将S型激活函数输出转换为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。

我需要针对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

(这不是您的实际问题,但您是要使用S形激活函数吗?不是softmax吗?您在此处获得的输出不是在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]])`

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM