bayes中文文本分类(NLP版)

"""
bayes中文文本分类(NLP版)
1、准备数据
读取数据内容,标签
2、中文的分词:中文信息处理时所需的步骤(Jieba、Jiagu、pkuseg)
3、文本向量化:将读取后的数据转换成文本的向量(数字)
TFIDF
词袋模型
4、模型的训练和保存:sklearn的工具包实现,joblib
5、模型的加载使用:joblib
"""
import os
import jieba
from sklearn.feature_extraction.text import \
    TfidfVectorizer
from sklearn.feature_extraction.text import \
    CountVectorizer
from sklearn.naive_bayes import MultinomialNB
from sklearn import metrics
import joblib

#读取文本数据:切分标签和文本》》》数据样本分词
def load_file(file_path):
    """
    1、打开文件
    2、按行读取文本的内容readlines()
    3、按照指定的方式切分文本文件"--"split()>>>label,text
    4、得到的text文本文件之后,jieba对文本文件分词
    :param file_path:
    :return:
    """
    with open(file_path,encoding="utf-8") as f:
        lines = f.readlines()

    texts = []#文件中的每个句子
    labels = []#label
    for line in lines:
        line = line.encode('unicode-escape').decode('unicode-escape')
        line = line.strip().rstrip('\n')#去掉空白符
        _line = line.split('---')#返回一个列表

        if len(_line) != 2:
            continue
        label,text = _line
        words = jieba.cut(text)
        s = ''
        for w in words:
            s += w+' '
            s = s.strip()
            texts.append(s)
            labels.append(label)
        return texts,labels

#按文件夹读取文本数据
def load_data(_dir):
    """
    1、读取文件的内容
    2、texts_list:所有的文件;
       labels_list:标签
    :param _dir:
    :return:
    """
    file_list = os.listdir(_dir)
    texts_list = []
    labels_list = []
    for file_name in file_list:
        file_path = _dir +'/'+file_name#文件名
        text,label = load_file(file_path)#读取当前文件中内容
        texts_list += text
        labels_list += label
    return texts_list,labels_list
#加载停用词
def load_stopwords(file_path):
    """
    1、打开文件,按行读取文件中的内容
    2、将单词保存至word中
    :param file_path:
    :return: words:所有单词组合
    """
    with open(file_path,encoding='utf-8')as f:
        lines = f.readlines()

    words = []
    for line in lines:
        line = line.encode('unicode-escape').decode('unicode-escape')
        line = line.strip().rstrip('\n')#去掉空白符
        words.append(line)
    return words

def main():
    """
     1、加载停用词
     2、加载数据集
     3、文本向量化(词袋模型,TFIDF,N-gram,)
     4、模型的训练和保存(sklearn)(joblib)
    :return:
    """
    stop_words = load_stopwords('stop_word/stopword.txt')
    train_datas,train_labels = load_data('train')
    tf = TfidfVectorizer(stop_words=stop_words,
                         max_df=0.5)
    tf = CountVectorizer(ngram_range=(1,2),#1-3
                         stop_words=stop_words,
                         max_df=0.5)
    train_features = tf.fit_transform(train_datas)
    clf = MultinomialNB(alpha=0.001)#调用模型
    clf.fit(train_features,train_labels)#训练模型
    
    #加载测试数据
    test_datas,test_labels = load_data('test')
    #测试数据的文本向量
    test_features = tf.transform(test_datas)
    predict_label = clf.predict(test_features)
    
    #评价模型
    score = metrics.accuracy_score(test_labels,
                                   predict_label)
    print(score)
    
    #保存模型
    joblib.dump(clf,'bayes.pkl')#保存模型
    joblib.dump(tf,'tf.pkl')#保存词向量模型
    
    #预测
    nb_predict('121212')


########加载模型#########  
#加载模型
def load_model(model_path,tf_path):
    model = joblib.load(model_path)
    tf = joblib.load(tf_path)
    return model,

#######预测#######
def nb_predict(text):
    """
    
    :param text: 
    :return:返回预测标签 
    """
    model,tf = load_model('bayes.pkl','tf.pkl')
    words = jieba.cut(text)
    s = ''.join(words)
    #将预测的文本转换成向量表示
    test_feature = tf.transform([s])
    predict = model.predict(test_feature)
    
    


    
    
if __name__ == '__main__':
    main()
        
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值