簡體   English   中英

訓練和驗證期間的准確性高,使用相同數據集進行預測期間的准確性低

[英]High accuracy during training and validation, low accuracy during prediction with the same dataset

所以我正在嘗試訓練 Keras model。在訓練和驗證時具有很高的准確性(我使用的是 f1score,但准確性也很高)。 但是當我試圖預測某些數據集時,我的准確性會降低。 即使我預測訓練集。 所以我想這不是過度擬合的問題。 那問題是什么?

import matplotlib.pyplot as plt

skf = StratifiedKFold(n_splits=5)
for train_index, test_index in skf.split(X, y):
    X_train, X_test = X[train_index], X[test_index]
    y_train, y_test = y[train_index], y[test_index]
    X_train,x_val,y_train,y_val = train_test_split(X_train, y_train, test_size=0.5,stratify = y_train)
    y_train = encode(y_train)
    y_val = encode(y_val)
    
    model = Sequential()
    model.add(Dense(50,input_dim=X_train.shape[1],activation='tanh'))
    model.add(Dropout(0.5))
    model.add(Dense(25,activation='tanh'))
    model.add(Dropout(0.5))
    model.add(Dense(10,activation='tanh'))
    model.add(Dropout(0.5))
    model.add(Dense(2, activation='softmax'))   
    
    opt = Adam(learning_rate=0.001)
    model.compile(loss='binary_crossentropy', optimizer=opt, metrics=['acc', ta.utils.metrics.f1score])  
    history = model.fit(X_train, y_train, 
                        validation_data=(x_val, y_val),
                        epochs=5000,
                        verbose=0)
    
    plt.plot(history.history['f1score'])
    plt.plot(history.history['val_f1score'])
    plt.title('model accuracy')
    plt.ylabel('f1score')
    plt.xlabel('epoch')
    plt.legend(['train', 'test'], loc='upper left')
    plt.show()
    break 

結果就在這里 如您所見,訓練和驗證集的結果很高。

預測代碼:

from sklearn.metrics import f1_score

y_pred = model.predict(x_train)
y_pred = decode(y_pred)
y_train_t = decode(y_train)
print(f1_score(y_train_t, y_pred))

結果為 0.64,低於預期的 0.9。

我的解碼和編碼:

def encode(y):
    Y=np.zeros((y.shape[0],2))
    for i in range(len(y)):
        if y[i]==1:
            Y[i][1]=1
        else :
            Y[i][0]=1
    return Y

def decode(y):
    Y=np.zeros((y.shape[0]))
    for i in range(len(y)):
        if np.argmax(y[i])==1:
            Y[i]=1
        else :
            Y[i]=0
    return Y

由於您使用了最后一層

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

不應model.compile()中使用loss='binary_crossentropy' ,而應使用 loss loss='categorical_crossentropy'

由於這個錯誤,model 擬合過程中顯示的結果可能是錯誤的——sklearn 的f1_score返回的結果是真實的。

與您的問題無關(因為我猜后續問題將是如何改進它? ),我們實際上從不使用activation='tanh'作為隱藏層(改用relu )。 此外,默認情況下不應使用 dropout(尤其是在 0.5 如此高的值下); 注釋掉所有 dropout 層,僅當您的 model 過擬合時才將它們添加回來(已知在不需要時使用 dropout 會損害性能)。

我認為您應該將binary_crossentropy更改為categorical_crossentropy ,因為您使用的是單熱編碼。

不知何故,圖像生成器與 predict_generator() function 或 Keras 的 model 的 predict() function 的組合無法按預期工作。 與其使用圖像生成器進行預測,我寧願一張一張地遍歷所有測試圖像,並在每次迭代中獲得每個圖像的預測。 我使用 Plaid-ML Keras 作為我的后端,為了獲得預測,我使用以下代碼。

import os
from PIL import Image
import keras
import numpy

###
# I am not including code to load models or train model
###

print("Prediction result:")
dir = "/path/to/test/images"
files = os.listdir(dir)
correct = 0
total = 0
#dictionary to label all traffic signs class.
classes = {
    0:'This is Cat',
    1:'This is Dog',
}
for file_name in files:
    total += 1
    image = Image.open(dir + "/" + file_name).convert('RGB')
    image = image.resize((100,100))
    image = numpy.expand_dims(image, axis=0)
    image = numpy.array(image)
    image = image/255
    pred = model.predict_classes([image])[0]
    sign = classes[pred]
    if ("cat" in file_name) and ("cat" in sign):
        print(correct,". ", file_name, sign)
        correct+=1
    elif ("dog" in file_name) and ("dog" in sign):
        print(correct,". ", file_name, sign)
        correct+=1
print("accuracy: ", (correct/total))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM