【问题标题】:How to use keras predict_proba to output 2 columns of probability?如何使用keras predict_proba 输出2列概率?
【发布时间】:2020-10-29 01:53:10
【问题描述】:

我用这段代码预测x_test中0和1的概率,但结果只有一列概率。真不知道这个列的概率是0的概率还是1的概率。

import numpy as np
from keras.models import Sequential
from keras.layers import Dense

data_train = np.array([
[0, 0, 0],
[0, 1, 0],
[0, 2, 0],
[0, 3, 0],
[1, 0, 0],
[2, 0, 0],
[3, 0, 0],
[1, 1, 1],
[2, 1, 1],
[1, 2, 1],
[3, 1, 1],
])

data_test = np.array([
[1, 3],
[0, 4],
[5, 0]
])

x_train = data_train[:, :-1]
y_train = data_train[:, -1]
x_test = data_test

model = Sequential()
model.add(Dense(512, activation='relu', input_dim=2))
model.add(Dense(200, activation='relu'))
model.add(Dense(200, activation='relu'))
model.add(Dense(128, activation='relu'))
model.add(Dense(1, activation='sigmoid'))
model.compile(optimizer='rmsprop',
              loss='binary_crossentropy',
              metrics=['binary_accuracy'])

model.fit(x_train, y_train, epochs=5, batch_size=1, verbose=1)
predict = model.predict_proba(x_test, batch_size=1)
print(predict)

结果只有 1 列:

[[0.9431795]
 [0.47065434]
 [0.08615088]]

我要2列概率,第一列是0的概率,第二列是1的概率,比如这样:

 [[0.23334,0.76267]
    ……
 [0.84984,0.15685]
 [0.16663,0.83291]]

如何解决?

【问题讨论】:

    标签: python machine-learning keras


    【解决方案1】:

    首先,你需要将y_train转换为one-hot encoding by

    from sklearn.preprocessing import LabelEncoder
    from keras.utils import np_utils
    
    encoder = LabelEncoder()
    encoder.fit(y_train)
    encoded_y = encoder.transform(y_train)
    y_train = np_utils.to_categorical(encoded_y)
    

    运行这段代码,y_train 会变成

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

    其次,需要将输出层改为

    model.add(Dense(2, activation='softmax'))
    

    通过这两个修改,您将获得所需的输出。

    【讨论】:

    • 在这种情况下(one-hot 编码标签和 softmax 输出),它们也应该切换到 loss='categorical_crossentropy' 和 metrics='accuracy'。
    猜你喜欢
    • 2018-10-11
    • 2017-06-02
    • 2019-05-19
    • 1970-01-01
    • 2018-09-06
    • 2016-04-04
    • 2023-04-10
    • 2018-02-28
    • 1970-01-01
    相关资源
    最近更新 更多