使用训练好的模型判断差评

 

目录

1.保存模型

2.去除停用词

3.加载模型和向量化器

4.定义预测句子的函数

5.测试句子

6.结果


前篇已经提供了训练模型的方法,本篇代码将实现保存模型并使用模型进行预测。

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)}")

6.结果

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值