如何使用keras预报_proba输出2列概率? [英] How to use keras predict_proba to output 2 columns of probability?

查看:71
本文介绍了如何使用keras预报_proba输出2列概率?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用此代码来预测x_test中0和1的概率,但是结果只是一列概率.我真的不知道此列的概率是0还是1.

I use this code to predict the probability of 0 and 1 in x_test, but the result is only one column of probability. I really don’t know whether the probability of this column is the probability of 0 or the probability of 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的概率,例如:

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:

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

如何解决?

推荐答案

首先,您需要通过

y_train转换为单编码

First, you need to convert y_train to 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)

第二,您需要将输出层更改为

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.

这篇关于如何使用keras预报_proba输出2列概率?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆