Keras[文本多分类]训练和测试的准确性好,但预测能力差

2024-04-24 12:44:25 发布

您现在位置:Python中文网/ 问答频道 /正文

在根据新闻文章预测话题时,我遇到了几个问题。新闻文章已被清除(没有浮夸,数字,…)。有6个类可能,我有一个数据集13000新闻文章每类(数据集的均匀分布)。你知道吗

预处理:


stop_words = set(stopwords.words('english')) 

for index, row in data.iterrows():
    print ("Index: ", index)
    txt_clean = ' '.join(re.sub("([^a-zA-Z ])", " ", data.loc[index,'txt_clean']).split()).lower()

    word_tokens = word_tokenize(txt_clean) 

    filtered_sentence = [w for w in word_tokens if not w in stop_words] 
    cleaned_text = ''

    for w in filtered_sentence:
        cleaned_text = cleaned_text + ' ' + w

    data.loc[index,'txt_clean'] = cleaned_text

我使用LSTM实现了一个RNN,如下所示:

model = Sequential()
    model.add(Embedding(50000, 100, input_length=500))
    model.add(SpatialDropout1D(0.2))
    model.add(LSTM(150, dropout=0.2, recurrent_dropout=0.2))
    model.add(Dense(6, activation='softmax'))
    model.summary()

    model.compile(loss='categorical_crossentropy', optimizer='rmsprop', metrics=['accuracy'])

    history = model.fit(X_train, Y_train, epochs=epochs, batch_size=batch_size, validation_split=0.1)

    accr = model.evaluate(X_test,Y_test)
    print('Test set\n  Loss: {:0.3f}\n  Accuracy: {:0.3f}'.format(accr[0],accr[1]))

预测:

model = load_model('model.h5')
data = data.sample(n=15000)

model.compile(optimizer = 'rmsprop', loss = 'categorical_crossentropy', metrics = ['accuracy'])
tokenizer = Tokenizer(num_words=50000)
tokenizer.fit_on_texts(data['txt_clean'].values) (Prediction data sample values and not the same as in the training))

CATEGORIES = ['A','B','C','D','E','F']
for index, row in data.iterrows():


    seq = tokenizer.texts_to_sequences([data.loc[index,'txt_clean']])
    padded = pad_sequences(seq, maxlen=500)

    pred = model.predict(padded)
    pred = pred[0]
    print (pred, pred[np.argmax(pred)]))

例如,在10个时代和批量大小为500之后:

  • 培训科目:0.831
  • 培训损失:0.513
  • 试验依据:0.714
  • 试验损失:0.907

还尝试将批处理大小的数量减少到64:

  • 培训科目:0.859
  • 训练损失:0.415
  • 试验依据:0.771
  • 试验损失:0.679

在我看来,使用64批量大小的结果更好,但是当我预测新闻文章(一篇接一篇)时,我得到了15.97%的准确率。与训练和测试相比,这种预测精度要低得多。你知道吗

有什么问题吗?你知道吗

谢谢!你知道吗


Tags: textintxtcleanaddfordataindex
2条回答

请尝试使用picklejoblib对您的标记器进行酸洗,以保存您的keras标记器使用它进行训练和预测。你知道吗

下面是保存keras标记器的示例代码:

import pickle

# saving
with open('tokenizer.pickle', 'wb') as handle:
    pickle.dump(tokenizer, handle, protocol=pickle.HIGHEST_PROTOCOL)

# loading
with open('tokenizer.pickle', 'rb') as handle:
    tokenizer = pickle.load(handle)

这是ML或DL中存在的一个经典问题。可能有几个原因

  1. 过度拟合,尝试使模型更深入或添加一些规范化。你知道吗
  2. 训练和测试数据集是不同的
  3. 使用与培训期间相同的预处理步骤
  4. 类不平衡,即训练数据集包含测试数据集所缺少的特定类的更多数据。你知道吗
  5. 尝试使用双向LSTM或GRU改变模型架构

相关问题 更多 >