[英]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.where
與max
結合使用:
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.