目录
前篇已经提供了训练模型的方法,本篇代码将实现保存模型并使用模型进行预测。
1.保存模型
# 保存模型和向量化器
import joblib
# 保存模型
joblib.dump(classifier, 'naive_bayes_model.m')
# 保存向量化器
joblib.dump(vec, 'vectorizer.m')
2.去除停用词
import jieba
import joblib
import pandas as pd
# 读取停用词
stopwords = pd.read_csv("StopwordsCN.txt", encoding='utf8', engine='python', index_col=False)
# 定义去除停用词的函数
def drop_stopwords(words, stopwords):
return [word for word in words if word not in stopwords]
3.加载模型和向量化器
classifier = joblib.load('naive_bayes_model.m')
vec = joblib.load('vectorizer.m')
4.定义预测句子的函数
def predict_sentence(sentence, vectorizer, classifier):
# 使用jieba进行分词
segments = jieba.lcut(sentence)
# 去除停用词
segments_clean = drop_stopwords(segments, stopwords)
# 将分词结果转换为字符串,以便向量化
text_vectorized = vectorizer.transform([' '.join(segments_clean)])
# 使用模型进行预测
prediction = classifier.predict(text_vectorized)
# 返回预测结果
return '差评' if prediction[0] == 1 else '非差评'
5.测试句子
new_sentence = "手机网络不好,一直卡顿,反应迟钝,需要换货!"
print(f"句子 '{new_sentence}' 是:{predict_sentence(new_sentence, vec, classifier)}")