简体   繁体   English

如何使用keras predict_proba 输出2列概率?

[英]How to use keras predict_proba to output 2 columns of probability?

I use this code to predict the probability of 0 and 1 in x_test , but the result is only one column of probability.我使用这段代码来预测x_test中 0 和 1 的概率,但结果只有一列概率。 I really don't know whether the probability of this column is the probability of 0 or the probability of 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)

And the result is only 1 column:结果只有 1 列:

[[0.9431795]
 [0.47065434]
 [0.08615088]]

I want 2 columns of probability, the first column is the probability of 0, and the second column is the probability of 1, such as this:我要2列概率,第一列是0的概率,第二列是1的概率,比如这样:

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

How to fix it?如何解决?

First, you need to convert y_train to one-hot encoding by首先,您需要将y_train转换为 one-hot encoding

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)

running this code, y_train will become运行此代码, 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)

Secondly, you need to change the output layer to其次,您需要将输出层更改为

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

with these two modifications, you will get the desired output.通过这两个修改,您将获得所需的输出。

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

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