朴素贝叶斯应用:垃圾邮件分类
1. 数据准备:收集数据与读取
2. 数据预处理:处理数据
3. 训练集与测试集:将先验数据按一定比例进行拆分。
4. 提取数据特征,将文本解析为词向量 。
5. 训练模型:建立模型,用训练数据训练模型。即根据训练样本集,计算词项出现的概率P(xi|y),后得到各类下词汇出现概率的向量 。
6. 测试模型:用测试数据集评估模型预测的正确率。
混淆矩阵
准确率、精确率、召回率、F值
7. 预测一封新邮件的类别。
8. 考虑如何进行中文的文本分类(期末作业之一)。
要点:
理解朴素贝叶斯算法
理解机器学习算法建模过程
理解文本常用处理流程
理解模型评估方法
#垃圾邮件分类# import csv import nltk from nltk.corpus import stopwords from nltk.stem import WordNetLemmatizer text = '''As per your request 'Melle Melle (Oru Minnaminunginte Nurungu Vettam)' has been set as your callertune for all Callers. Press *9 to copy your friends Callertune''' #预处理# def preprocessing(text): #分词# tokens = [word for sent in nltk.sent_tokenize(text) for word in nltk.word_tokenize(sent)] # for sent in nltk.sent_tokenize(text): #对文本按照句子进行分割 # for word in nltk.word_tokenize(sent): #对句子进行分词 # print(word) tokens #停用词# stops = stopwords.words('english') stops #去掉停用词 tokens = [token for token in tokens if token not in stops] tokens #去掉短于3的词 tokens = [token.lower() for token in tokens if len(token)>=3] tokens #词性还原 lmtzr = WordNetLemmatizer() tokens = [lmtzr.lemmatize(token) for token in tokens] tokens #将剩下的词重新连接成字符串 preprocessed_text = ' '.join(tokens) return preprocessed_text preprocessing(text) #读数据# file_path = r'C:\Users\s2009\Desktop\email.txt' sms = open(file_path,'r',encoding = 'utf-8') sms_data = [] sms_target = [] csv_reader = csv.reader(sms,delimiter = '\t') #将数据分别存入数据列表和目标分类列表# for line in csv_reader: sms_data.append(preprocessing(line[1])) sms_target.append(line[0]) sms.close() print("邮件总数为:",len(sms_target)) sms_target #将数据分为训练集和测试集# from sklearn.model_selection import train_test_split x_train,x_test,y_train,y_test=train_test_split(sms_data,sms_target,test_size=0.3,random_state=0,startify=sms_target) print(len(x_train,len(x_test))) #将其向量化# from sklearn.feature_extraction.text import TfidfVectorizer ##建立数据的特征向量# vectorizer=TfidfVectorizer(min_df=2,ngram_range=(1,2),stop_words='english',strip_accents='unicode',norm='12') X_train=vectorizer.fit_transform(x_train) X_test=vectorizer.transform(x_test) import numpy as np #观察向量 a = X_train.toarray() #X_test = X_test.toarray() #X_train.shape #X_train for i in range(1000): #输出不为0的列 for j in range(5984): if a[i,j]!=0: print(i,j,a[i,j]) #朴素贝叶斯分类器# from sklearn.navie_bayes import MultinomialNB clf= MultinomialNB().fit(X_train,y_train) y_nb_pred=clf.predict(X_test) #分类结果显示# from sklearn.metrics import confusion_matrix from sklearn.metrics import classification_report print(y_nb_pred.shape,y_nb_pred)#x_test预测结果 print('nb_confusion_matrix:') cm=confusion_matrix(y_test,y_nb_pred)#混淆矩阵 print(cm) print('nb_classification_report:') cr=classification_report(y_test,y_nb_pred)#主要分类指标的文本报告 print(cr) feature_name=vectorizer.get_feature_name()#出现过的单词列表 coefs=clf_coef_ #先验概率 intercept=clf.intercept_ coefs_with_fns=sorted(zip(coefs[0],feature_names))#对数概率p(x_i|y)与单词x_i映射 n=10 top=zip(coefs_with_fns[:n],coefs_with_fns[:-(n+1):-1])#最大的10个与最小的10个单词 for (coef_1,fn_1),(coef_2,fn_2) in top: print('\t%.4f\t%-15s\t\t%.4f\t%-15s' % (coef_1,fn_1,coef_2,fn_2))
运行结果: