python - kerasequential().predict(x_test) 只返回两个类的 1 列

标签 python neural-network keras sequential

我在使用 keras sequential().predict(x_test) 时遇到问题。

顺便说一句,使用 sequential().predict_proba(x_test) 获得相同的输出,因为我发现这两个现在在顺序上是无关紧要的。

我的数据有两个类:0 或 1,我相信 predict(x_test) 应该给出两列,其中第一列是获得 0 的概率,第二列是获得 1 的概率。不过我只有一篇专栏有此内容。

    In [85]:y_train.value_counts()
    Out[85]: 
    0    616751
    1     11140
    Name: _merge, dtype: int64

我的数据应该没有问题,因为我对 LogisticRegression 模型和神经网络模型使用了相同的 x_train、y_train、x_test、y_test,它在 LogisticRegression 中运行完美。

In [87]:y_pred_LR
Out[87]: 
array([[  9.96117151e-01,   3.88284921e-03],
       [  9.99767583e-01,   2.32417329e-04],
       [  9.87375774e-01,   1.26242258e-02],
       ..., 
       [  9.72159138e-01,   2.78408623e-02],
       [  9.97232916e-01,   2.76708432e-03],
       [  9.98146985e-01,   1.85301489e-03]])

但我在神经网络模型中只得到 1 列。

所以我猜NN模型设置有问题?这是我的代码

NN = Sequential()
NN.add(Dense(40, input_dim = 65, kernel_initializer = 'uniform', activation = 'relu'))
NN.add(Dense(20, kernel_initializer = 'uniform', activation = 'relu'))
NN.add(Dense(1, kernel_initializer = 'uniform', activation = 'sigmoid'))
NN.compile(optimizer = 'adam', loss = 'binary_crossentropy', metrics = ['accuracy'])

NN.fit(x_train, y_train, batch_size = 50, epochs=5)
y_pred_NN = NN.predict(x_test)
print(y_pred_NN)

    In [86]: print(y_pred_NN)
    [[ 0.00157279]
     [ 0.0010451 ]
     [ 0.03178826]
     ..., 
     [ 0.01030775]
     [ 0.00584918]
     [ 0.00186538]]

实际上看起来是得到1的概率? 如有任何帮助,我们将不胜感激!

顺便说一句,我在两个模型中的预测形状如下

In [91]:y_pred_LR.shape
Out[91]: (300000, 2)

In [90]:y_pred_NN.shape
Out[90]: (300000, 1)

最佳答案

如果您想输出两个概率,则必须将 y_train 替换为 to_categorical(y_train),然后相应地调整网络:

from keras.utils import to_categorical

NN = Sequential()
NN.add(Dense(40, input_dim = 65, kernel_initializer = 'uniform', activation = 'relu'))
NN.add(Dense(20, kernel_initializer = 'uniform', activation = 'relu'))
NN.add(Dense(2, activation='sigmoid'))
NN.compile(optimizer = 'adam', loss = 'binary_crossentropy', metrics = ['accuracy'])

NN.fit(x_train, to_categorical(y_train), batch_size = 50, epochs=5)

咨询这里:https://keras.io/utils/#to_categorical

关于python - kerasequential().predict(x_test) 只返回两个类的 1 列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52823862/

相关文章:

python - Tkinter:获取 Canvas 属性和选项值

python - 即使退出后,环境变量也会保留在 Python 脚本中

artificial-intelligence - 卷积神经网络中权重和输出的值

tensorflow - 如何计算神经网络预测的置信度得分

python - 如何在 keras 中训练顺序模型,给出一个列表作为输出和输入?

tensorflow - 无法将 .h5 模型转换为 ONNX 以通过任何方式进行推理

python - 将 2012-12-19 字符串转换为 Python 中的日期时间对象

python - 嵌套 concurrent.futures.ThreadPoolExecutor

python-3.x - 来自两个输入源的自定义 Tensorflow 层

python - 如何为 TensorFlow 中的不同层或变量设置不同的学习率?