如何使用keras预报_proba输出2列概率?

时间:2020-10-29 01:53:10

标签: python machine-learning keras

我使用此代码来预测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]]

如何解决?

1 个答案:

答案 0 :(得分:2)

首先,您需要通过{p>将y_train转换为单编码

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'))

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