【问题标题】:good accuracy , but bad prediction with keras准确率高,但用 keras 预测不好
【发布时间】:2018-04-15 00:44:48
【问题描述】:

我需要帮助,我使用 keras 分类器,问题是我用相同的数据得到了很高的准确率但非常糟糕的预测,预测类别应该是 0,1,2,3,3,4,0。但我全是零,这是我的代码

from keras.models import Sequential
from keras.layers import Dense
from keras import optimizers
model = Sequential()
model.add(Dense(units=14, activation='relu', input_shape=(14,)))
model.add(Dropout(0.5))
model.add(Dense(units=14, activation='relu'))
model.add(Dropout(0.5))
model.add(Dense(units=14, activation='relu'))
model.add(Dense(units=5, activation='sigmoid'))
#model.add(Dense(units=5, activation='relu'))
#monitor = EarlyStopping(monitor='val_loss', min_delta=1e-3, patience=5, verbose=0, mode='auto')
#checkpointer = ModelCheckpoint(filepath="best_weights.hdf5", verbose=0, save_best_only=True) # save best model  
sgd = optimizers.SGD(lr=0.01, decay=1e-6, momentum=0.001, nesterov=True)
model.compile(optimizer=sgd,
               loss='categorical_crossentropy',
               metrics=['accuracy'])

model.fit(x_vals_train,y_train,validation_data=(x_vals_test,y_test),verbose=0,epochs=10)
#Evaluate the accuracy of our trained model
score = model.evaluate(x_vals_test, y_test,
                       batch_size=32, verbose=1)
print('Test score:', score[0])
print('Test accuracy:', score[1])
27134/27134 [==============================] - 1s 29us/step
Test score: 0.10602876026708943
Test accuracy: 0.9448293653718581


the predition
testset = np.loadtxt('G:/project/test.pcap_z/all_data_amount_7.csv', delimiter=',')

xtest = testset[:,0:14]

#x_test1 = np.nan_to_num(normalize_cols(xtest))

y_pred = model.predict(x_test1)
y_pred =y_pred.astype(int)
y_pred

array([[0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0]])

拜托,任何帮助将不胜感激。

【问题讨论】:

  • 在将数据拆分为测试和训练之前对其进行洗牌。在您关注@Primusa 回答后发布结果。
  • @rere,你是怎么解决这个问题的,我也有同样的问题

标签: keras


【解决方案1】:

对于分类,你应该使用 one-hot 向量作为你的 y 和 softmax 激活作为你神经网络中的最后一层。

要将您的 y 转换为 one-hot 格式:

from keras.np_utils import to_categorical
y = to_categorical(y)

并添加另一个具有 softmax 激活的 Dense 层:

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

现在不是输出严格的类别,而是输出每个类别的概率向量。要检索预测,您可以在输出的向量上使用np.argmax(),这会得到概率最高的类。

【讨论】:

  • 我按照你的建议做了,但预测还是不好,谢谢
  • 还是全零?
【解决方案2】:

可能是y_pred = y_pred.astype(int) 删除了所有数据,因为当float 变成int 时,它总是向下取整。

【讨论】:

    猜你喜欢
    • 2019-05-30
    • 1970-01-01
    • 2020-02-02
    • 1970-01-01
    • 2020-01-21
    • 2020-10-17
    • 2020-02-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多