自己 做网站,怎么查网站icp,wordpress 指定页面,百度一键优化案例背景
trec06c是非常经典的邮件分类的数据#xff0c;还是难能可贵的中文数据集。 这个数据集从一堆txt压缩包里面提取出来整理为excel文件还真不容不易#xff0c;肯定要做一下文本分类。 虽然现在文本分类基本都是深度学习了#xff0c;但是传统的机器学习也能做。本案…案例背景
trec06c是非常经典的邮件分类的数据还是难能可贵的中文数据集。 这个数据集从一堆txt压缩包里面提取出来整理为excel文件还真不容不易肯定要做一下文本分类。 虽然现在文本分类基本都是深度学习了但是传统的机器学习也能做。本案例就演示传统的贝叶斯向量机k近邻这种传统模型怎么做邮件分类。 数据介绍 数据前3行label是标签spam是垃圾邮件ham是正常邮件。content就是纯文字中文的还是很整洁的。
当然需要本次案例演示数据和全部代码文件的可以参考邮件分类 代码实现
导入需要的包、
import glob,random,re,math
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
plt.rcParams[font.sans-serif] [KaiTi] #指定默认字体 SimHei黑体
plt.rcParams[axes.unicode_minus] False #解决保存图像是负号from collections import Counter
from wordcloud import WordCloud
from matplotlib import colors
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.model_selection import train_test_split
读取数据
展示前3行
df1pd.read_csv(email_data.csv)
df1.head(3) 统计一下数量
df1[Label].value_counts() #统计 4w多的垃圾邮件2w多的正常邮件不平衡我们抽取5k的正常邮件和5k的垃圾邮件合并作为数据。
数据量有点多我正负样本都抽取5k条。
# 从 DataFrame 中分别抽取 5k条垃圾邮件和 5k 条正常邮件并合并
number5000
df pd.concat([df1[df1[Label] spam].sample(nnumber, random_state7), # 抽取 5k 条垃圾邮件df1[df1[Label] ham].sample(nnumber, random_state7) # 抽取 5k 条正常邮件
]).reset_index(dropTrue) # 重置索引
df[Label].value_counts() 画图查看
plt.figure(figsize(4,3),dpi128)
sns.countplot(xdf[Label])
#显示图像
plt.show() 分词
中文文本都需要进行分词需要把里面的标点符号通用词去一下然后变成一个个切割开的单词。
import jieba #过滤停用词分词
stop_list pd.read_csv(停用词.txt,index_colFalse,quoting3,sep\t,names[stopword], encodingutf-8)
def txt_cut(juzi): #Jieba分词函数lis[w for w in jieba.lcut(juzi) if w not in stop_list.values]return ( ).join(lis)
df[text]df[Content].astype(str).apply(txt_cut)
查看前五行、
df.head() 后面的文本中间都像英文的空格一样分开了。
然后再把漏掉的标点符号占位符去一下
df[text]df[text].apply(lambda x: x.replace(,).replace(( ,).replace(,).replace(/,).replace( ,)) 下面进行文本的分析
正常邮件
词频分析
这里用tf-idf的词袋方法
from sklearn.feature_extraction.text import CountVectorizer,TfidfVectorizer
from sklearn.decomposition import LatentDirichletAllocation
from sklearn.preprocessing import MinMaxScaler
将文本转为数值矩阵
df_hamdf[df[Label]ham] #取出正常邮件
tf_vectorizer TfidfVectorizer() #tf-idf词袋
#tf_vectorizer TfidfVectorizer(ngram_range(2,2)) #2元词袋
X tf_vectorizer.fit_transform(df_ham[text])
print(X.shape)feature_names tf_vectorizer.get_feature_names_out()
tfidf_values X.toarray()
print(feature_names.shape,tfidf_values.shape) 查看对应的词汇名称tf-idf的值权重等
# 从转换器中提取词汇和对应的 TF-IDF 值
data1 {word: tf_vectorizer.get_feature_names_out(),frequency:np.count_nonzero(X.toarray(), axis0),weight: X.mean(axis0).A.flatten(),}
df1 pd.DataFrame(data1).sort_values(byfrequency ,ascendingFalse,ignore_indexTrue)
df1.head() 可以储存一下
#储存
df1.to_excel(正常邮件词频.xlsx, indexFalse) 查看评率最高前20的词汇
#前20个频率最高的词汇
df2pd.DataFrame(data1).sort_values(byfrequency ,ascendingFalse,ignore_indexTrue)
plt.figure(figsize(7,3),dpi256)
sns.barplot(xdf2[word][:20],ydf2[frequency][:20])
plt.xticks(rotation70,fontsize9)
plt.ylabel(频率)
plt.xlabel()
#plt.title(前20个频率最高的词汇)
plt.show() 词云图
画出对应的词云图
#定义随机生成颜色函数
def randomcolor():colorArr [1,2,3,4,5,6,7,8,9,A,B,C,D,E,F]color #.join([random.choice(colorArr) for i in range(6)])return color#from imageio import imread #形状设置
#mask imread(爱心.png)
all_titles .join(df_ham[text])
# Word segmentation
seg_list jieba.cut(all_titles, cut_allFalse)
seg_text .join(seg_list)
#对分词文本做高频词统计
word_counts Counter(seg_text.split())
word_counts_updatedword_counts.most_common()
#过滤标点符号
non_chinese_pattern re.compile(r[^\u4e00-\u9fa5])
# 过滤掉非中文字符的词汇
filtered_word_counts_regex [item for item in word_counts_updated if not non_chinese_pattern.match(item[0])]
filtered_word_counts_regex[:5] # Generate word cloud
wordcloud WordCloud(font_pathsimhei.ttf, background_colorwhite, max_words80, # Limits the number of words to 100max_font_size50) #.generate(seg_text) #文本可以直接生成但是不好看
wordcloud wordcloud.generate_from_frequencies(dict(filtered_word_counts_regex))
# Display the word cloud
plt.figure(figsize(8, 5),dpi256)
plt.imshow(wordcloud, interpolationbilinear)
plt.axis(off)
plt.show() 上面都是正常邮件的词汇分析下面就是垃圾邮件的分析
垃圾邮件
词频分析
转为tf-idf的词矩阵
df_spamdf[df[Label]spam]
tf_vectorizer TfidfVectorizer()
#tf_vectorizer TfidfVectorizer(ngram_range(2,2)) #2元词袋
X tf_vectorizer.fit_transform(df_spam[text])
#print(tf_vectorizer.get_feature_names_out())
print(X.shape)feature_names tf_vectorizer.get_feature_names_out()
tfidf_values X.toarray()
print(feature_names.shape,tfidf_values.shape) # 从转换器中提取词汇和对应的 TF-IDF 值 data1 {word: tf_vectorizer.get_feature_names_out(),frequency:np.count_nonzero(X.toarray(), axis0),weight: X.mean(axis0).A.flatten(),}
df1 pd.DataFrame(data1).sort_values(byfrequency ,ascendingFalse,ignore_indexTrue)
df1.head() 储存一下可以看到com较多说明垃圾邮件里面的很多网址链接
也可以储存一下
#储存
df1.to_excel(垃圾邮件词频.xlsx, indexFalse)
前20个词汇
#前20个频率最高的词汇
df2pd.DataFrame(data1).sort_values(byfrequency ,ascendingFalse,ignore_indexTrue)
plt.figure(figsize(7,3),dpi256)
sns.barplot(xdf2[word][:20],ydf2[frequency][:20])
plt.xticks(rotation70,fontsize9)
plt.ylabel(频率)
plt.xlabel()
#plt.title(前20个频率最高的词汇)
plt.show() 词云图
#from imageio import imread #形状设置
#mask imread(爱心.png)
all_titles .join(df_spam[text])
# Word segmentation
seg_list jieba.cut(all_titles, cut_allFalse)
seg_text .join(seg_list)
#对分词文本做高频词统计
word_counts Counter(seg_text.split())
word_counts_updatedword_counts.most_common()
#过滤标点符号
non_chinese_pattern re.compile(r[^\u4e00-\u9fa5])
# 过滤掉非中文字符的词汇
filtered_word_counts_regex [item for item in word_counts_updated if not non_chinese_pattern.match(item[0])]
filtered_word_counts_regex[:5] # Generate word cloud
wordcloud WordCloud(font_pathsimhei.ttf, background_colorwhite, max_words80, # Limits the number of words to 100max_font_size50) #.generate(seg_text) #文本可以直接生成但是不好看
wordcloud wordcloud.generate_from_frequencies(dict(filtered_word_counts_regex))
# Display the word cloud
plt.figure(figsize(8, 5),dpi256)
plt.imshow(wordcloud, interpolationbilinear)
plt.axis(off)
plt.show() 机器学习
#准备X和y还是一样的tf-idf的词表矩阵这里限制一下矩阵的维度为5000免得数据维度太大了训练时间很长。
#取出X和y
X df[text]
y df[Label]
#创建一个TfidfVectorizer的实例
vectorizer TfidfVectorizer(max_features5000,max_df0.1,min_df3)
#使用Tfidf将文本转化为向量
X vectorizer.fit_transform(X)
#看看特征形状
X.shape 查看词汇频率
data1 {word: vectorizer.get_feature_names_out(),tfidf: X.toarray().sum(axis0).tolist()}
df1 pd.DataFrame(data1).sort_values(bytfidf ,ascendingFalse,ignore_indexTrue)
df1.head(10) 划分训练集和测试集
y映射一下变成数值型
y1y.map({spam:1,ham:0})
X_train, X_test, y_train, y_test train_test_split(X,y,test_size0.2,stratifyy,random_state 0)
#可以检查一下划分后数据形状
X_train.shape,X_test.shape, y_train.shape, y_test.shape 模型对比
#采用三种模型对比测试集精度
from sklearn.naive_bayes import MultinomialNB
from sklearn.neighbors import KNeighborsClassifier
from sklearn.svm import SVC
实例化模型
#朴素贝叶斯
model1 MultinomialNB()
#K近邻
model2 KNeighborsClassifier(n_neighbors100)
#支持向量机
model3 SVC(kernelrbf, random_state77, probabilityTrue)model_list[model1,model2,model3]
model_name[朴素贝叶斯,K近邻,支持向量机]
自定义一下训练和评价函数
from sklearn.metrics import confusion_matrix, roc_curve, auc
from sklearn.metrics import ConfusionMatrixDisplaydef evaluate_model(model, X_train, X_test, y_train, y_test, model_name):# 训练模型model.fit(X_train, y_train)# 计算准确率accuracy model.score(X_test, y_test)print(f{model_name}方法在测试集的准确率为{round(accuracy, 3)})# 计算混淆矩阵cm confusion_matrix(y_test, model.predict(X_test))print(f混淆矩阵\n{cm})# 绘制混淆矩阵热力图disp ConfusionMatrixDisplay(confusion_matrixcm, display_labels[spam, ham])disp.plot(cmapplt.cm.Blues)plt.title(fConfusion Matrix - {model_name})plt.show()# 计算 ROC 曲线fpr, tpr, thresholds roc_curve(y_test, model.predict_proba(X_test)[:, 1], pos_labelspam)roc_auc auc(fpr, tpr)# 绘制 ROC 曲线plt.plot(fpr, tpr, labelf{model_name} (AUC {roc_auc:.6f}))plt.xlabel(False Positive Rate)plt.ylabel(True Positive Rate)plt.title(ROC Curve)plt.legend()plt.show()return accuracy
对三个模型都进行一下训练
accuracys[]
for model, name in zip(model_list, model_name):accuracyevaluate_model(model, X_train, X_test, y_train, y_test, name)accuracys.append(accuracy) 这个函数会画出很多图混淆矩阵ROC的图评价指标等。
查看三个模型的准确率
accuracys 准确率进行可视化
plt.figure(figsize(7,3),dpi128)
sns.barplot(ymodel_name,xaccuracys,orienth)
plt.xlabel(模型准确率)
plt.ylabel(模型名称)
plt.xticks(fontsize10,rotation45)
plt.title(不同模型文本分类准确率对比)
plt.show() 支持向量机准确率最高
ROC对比
plt.figure(figsize(8, 6),dpi128)# 遍历每个模型绘制其 ROC 曲线
for model, name in zip(model_list, model_name):model.fit(X_train, y_train) # 训练模型fpr, tpr, _ roc_curve(y_test, model.predict_proba(X_test)[:, 1], pos_labelspam) # 计算 ROC 曲线的参数roc_auc auc(fpr, tpr) # 计算 AUCplt.plot(fpr, tpr, labelf{name} (AUC {roc_auc:.6f})) # 绘制 ROC 曲线# 绘制对角线
plt.plot([0, 1], [0, 1], linestyle--, colorgrey, labelRandom)
# 设置图形属性
plt.xlabel(False Positive Rate)
plt.ylabel(True Positive Rate)
plt.title(ROC Curve)
plt.legend()
plt.show() 支持向量机的auc最高。 四个评价指标
模型再实例化一下我们计算分类问题常用的四个评价指标准确率精准度召回率F1值 from sklearn.metrics import confusion_matrix
from sklearn.metrics import classification_report
from sklearn.metrics import cohen_kappa_score
#朴素贝叶斯
model1 MultinomialNB()
#K近邻
model2 KNeighborsClassifier(n_neighbors100)
#支持向量机
model3 SVC(kernelrbf, random_state77, probabilityTrue)model_list[model1,model2,model3]
#model_name[朴素贝叶斯,K近邻,支持向量机]
自定义评价指标
def evaluation(y_test, y_predict):accuracyclassification_report(y_test, y_predict,output_dictTrue)[accuracy]sclassification_report(y_test, y_predict,output_dictTrue)[weighted avg]precisions[precision]recalls[recall]f1_scores[f1-score]#kappacohen_kappa_score(y_test, y_predict)return accuracy,precision,recall,f1_score #, kappa
def evaluation2(lis):arraynp.array(lis)return array.mean() , array.std()
循环遍历预测计算评价指标
df_evalpd.DataFrame(columns[Accuracy,Precision,Recall,F1_score])
for i in range(3):model_Cmodel_list[i]namemodel_name[i]model_C.fit(X_train, y_train)predmodel_C.predict(X_test)sclassification_report(y_test, pred)sevaluation(y_test,pred)df_eval.loc[name,:]list(s)
查看
df_eval 可视化
bar_width 0.4
colors [c, g, tomato, b, m, y, lime, k, orange, pink, grey, tan]
fig, axes plt.subplots(2, 2, figsize(7, 6), dpi128)for i, col in enumerate(df_eval.columns):ax axes[i//2, i%2] # 这将为每个子图指定一个轴df_col df_eval[col]m np.arange(len(df_col))bars ax.bar(xm, heightdf_col.to_numpy(), widthbar_width, colorcolors)# 在柱状图上方显示数值for bar in bars:yval bar.get_height()ax.text(bar.get_x() bar.get_width()/2, yval, round(yval, 4), hacenter, vabottom, fontsize8)# 设置x轴names df_col.indexax.set_xticks(range(len(df_col)))ax.set_xticklabels(names, fontsize10, rotation40)# 设置y轴ax.set_ylim([0.94, df_col.max() 0.02]) ax.set_ylabel(col, fontsize14)plt.tight_layout()
# plt.savefig(柱状图.jpg, dpi512) # 如果需要保存图片取消注释这行
plt.show() 很明显支持向量机 效果最好 交叉验证
自定义交叉验证评价指标和函数
def evaluation(y_test, y_predict):accuracyclassification_report(y_test, y_predict,output_dictTrue)[accuracy]sclassification_report(y_test, y_predict,output_dictTrue)[weighted avg]precisions[precision]recalls[recall]f1_scores[f1-score]#kappacohen_kappa_score(y_test, y_predict)return accuracy,precision,recall,f1_score #, kappa
def evaluation2(lis):arraynp.array(lis)return array.mean() , array.std()
from sklearn.model_selection import KFold
def cross_val(modelNone,XNone,YNone,K5,repeated1,show_confusion_matrixTrue):df_meanpd.DataFrame(columns[Accuracy,Precision,Recall,F1_score]) df_stdpd.DataFrame(columns[Accuracy,Precision,Recall,F1_score])for n in range(repeated):print(f正在进行第{n1}次重复K折.....随机数种子为{n}\n)kf KFold(n_splitsK, shuffleTrue, random_staten)Accuracy[]Precision[]Recall[]F1_score[]print(f 开始本次在{K}折数据上的交叉验证.......\n)i1for train_index, test_index in kf.split(X):print(f 正在进行第{i}折的计算)X_trainX[train_index]y_trainnp.array(y)[train_index]X_testX[test_index]y_testnp.array(y)[test_index]model.fit(X_train,y_train)predmodel.predict(X_test)scorelist(evaluation(y_test,pred))Accuracy.append(score[0])Precision.append(score[1])Recall.append(score[2])F1_score.append(score[3])if show_confusion_matrix:#数据透视表混淆矩阵print(混淆矩阵)table pd.crosstab(y_test, pred, rownames[Actual], colnames[Predicted])#print(table)plt.figure(figsize(4,3))sns.heatmap(table,cmapBlues,fmt.20g, annotTrue)plt.tight_layout()plt.show()#计算混淆矩阵的各项指标print(混淆矩阵的各项指标为)print(classification_report(y_test, pred))print(f 第{i}折的准确率为{round(score[0],4)}Precision为{round(score[1],4)}Recall为{round(score[2],4)}F1_score为{round(score[3],4)})i1print(f ———————————————完成本次的{K}折交叉验证———————————————————\n)Accuracy_mean,Accuracy_stdevaluation2(Accuracy)Precision_mean,Precision_stdevaluation2(Precision)Recall_mean,Recall_stdevaluation2(Recall)F1_score_mean,F1_score_stdevaluation2(F1_score)print(f第{n1}次重复K折本次{K}折交叉验证的总体准确率均值为{Accuracy_mean}方差为{Accuracy_std})print(f 总体Precision均值为{Precision_mean}方差为{Precision_std})print(f 总体Recall均值为{Recall_mean}方差为{Recall_std})print(f 总体F1_score均值为{F1_score_mean}方差为{F1_score_std})print(\n\n)df1pd.DataFrame(dict(zip([Accuracy,Precision,Recall,F1_score],[Accuracy_mean,Precision_mean,Recall_mean,F1_score_mean])),index[n])df_meanpd.concat([df_mean,df1])df2pd.DataFrame(dict(zip([Accuracy,Precision,Recall,F1_score],[Accuracy_std,Precision_std,Recall_std,F1_score_std])),index[n])df_stdpd.concat([df_std,df2])return df_mean,df_std 实例化三个模型
model1 MultinomialNB()
#K近邻
model2 KNeighborsClassifier(n_neighbors100)
#支持向量机
model3 SVC(kernelrbf, random_state77, probabilityTrue)
贝叶斯
model MultinomialNB()
nb_crosseval,nb_crosseval2cross_val(modelmodel,XX,Yy,K5,repeated6) 结果都打印出来的。 朴素贝叶斯的评价指标
nb_crosseval K近邻
model KNeighborsClassifier(n_neighbors100)
knn_crosseval,knn_crosseval2cross_val(modelmodel,XX,Yy,K5,repeated6,show_confusion_matrixFalse)
不放过程了直接上结果
knn_crosseval 支持向量机
model SVC(kernelrbf, random_state77, probabilityTrue)
svc_crosseval,svc_crosseval2cross_val(modelmodel,XX,Yy,K5,repeated6,show_confusion_matrixFalse)
评价指标
svc_crosseval 均值的可视化
plt.subplots(1,4,figsize(16,3),dpi128)
for i,col in enumerate(nb_crosseval.columns):nint(str(14)str(i1))plt.subplot(n)plt.plot(nb_crosseval[col], k, labelNB)plt.plot(knn_crosseval[col], b-., labelKNN)plt.plot(svc_crosseval[col], r-^, labelSVC)plt.title(f不同模型的{col}对比)plt.xlabel(重复交叉验证次数)plt.ylabel(col,fontsize16)plt.legend()
plt.tight_layout()
plt.show() 方差的可视化
plt.subplots(1,4,figsize(16,3),dpi128)
for i,col in enumerate(nb_crosseval2.columns):nint(str(14)str(i1))plt.subplot(n)plt.plot(nb_crosseval2[col], k, labelNB)plt.plot(knn_crosseval2[col], b-., labelKNN)plt.plot(svc_crosseval2[col], r-^, labelSVC)plt.title(f不同模型的{col}方差对比)plt.xlabel(重复交叉验证次数)plt.ylabel(col,fontsize16)plt.legend()
plt.tight_layout()
plt.show() 结论
我们将进行三种机器学习模型的性能分析朴素贝叶斯Naive Bayes、k近邻k-Nearest Neighbors和支持向量机Support Vector Machine。
### 1. 朴素贝叶斯模型分析
朴素贝叶斯模型在数据集上表现出了相对较高的性能。具体来说它在准确率Accuracy、精确率Precision、召回率Recall和F1分数F1-score方面均取得了稳定的表现分别达到了约96%的水平。这表明朴素贝叶斯模型在数据分类方面具有较高的效果并且不易受到数据波动的影响。
### 2. k近邻模型分析
与朴素贝叶斯相比k近邻模型在性能上稍显不及。尽管其在准确率和F1分数方面表现相当但在精确率和召回率方面略有下降分别在95%左右。这可能表明k近邻模型在处理数据集中的某些特征时存在一定的困难导致了一些分类错误。
### 3. 支持向量机模型分析
支持向量机SVM模型在这份数据集上展现了最佳的性能。其在所有评估指标上均表现出了接近98%的高水平包括准确率、精确率、召回率和F1分数。这表明支持向量机模型在数据分类任务中具有较强的鲁棒性和泛化能力能够有效地捕捉数据之间的复杂关系并进行准确的分类。
综上所述支持向量机模型在这份数据集上表现最佳其稳定性和高性能使其成为首选模型。朴素贝叶斯模型在某些情况下也是一个可行的选择而k近邻模型可能需要进一步优化以提高其性能。 支持向量机的准确率最高模型波动的方差小效果最好下面对它进行超参数搜索。 超参数搜索
#利用K折交叉验证搜索最优超参数
from sklearn.model_selection import KFold, StratifiedKFold
from sklearn.model_selection import GridSearchCV,RandomizedSearchCV
参数范围
param_grid {C: [0.1, 1, 10],gamma: [ 0.01, 0.1, 1, 10]}model GridSearchCV(estimatorSVC(kernelrbf), param_gridparam_grid, cv3)
model.fit(X_train, y_train) 参数
model.best_params_ 评估
model model.best_estimator_
predmodel.predict(X_test)
evaluation(y_test,pred) 对这个区间再度细化搜索
param_grid {C: [6,7,8,9,10,11,12,13,14],gamma: [ 0.08,0.09,0.1,0.15,0.2,0.3]}model GridSearchCV(estimatorSVC(kernelrbf), param_gridparam_grid, cv3)
model.fit(X_train, y_train) model.best_params_ model model.best_estimator_
predmodel.predict(X_test)
evaluation(y_test,pred) 能达到99%准确率了。 画图
import itertools
def plot_confusion_matrix(cm, classes,titleConfusion matrix,cmapplt.cm.Blues):plt.imshow(cm, interpolationnearest, cmapcmap)plt.title(title)plt.colorbar()tick_marks np.arange(len(classes))plt.xticks(tick_marks, classes, rotation0)plt.yticks(tick_marks, classes)thresh cm.max() / 2.for i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])):plt.text(j, i, cm[i, j],horizontalalignmentcenter,colorwhite if cm[i, j] thresh else black)plt.tight_layout()plt.ylabel(True label)plt.xlabel(Predicted label) 最好的模型
import time
svcSVC(kernelrbf,C6 , gamma0.09)
startTime time.time()
svc.fit(X_train, y_train)
print(svc分类器训练用时%.2f秒 %(time.time()-startTime))
predsvc.predict(X_test)
print(f准确率精确度召回率F1值{np.round(evaluation(y_test,pred),6)})
plot_confusion_matrix(confusion_matrix(y_test,pred),[0,1])
plt.show() 模型保存
import joblib
# 模型已经选取了最佳估计器存储在变量 model 中
# 保存模型到文件
joblib.dump(model, best_model.pkl) 加载模型然后预测
# 加载模型
loaded_model joblib.load(best_model.pkl)
# 使用加载的模型进行预测
loaded_model.predict(X_test)
evaluation(y_test, pred) 基本是99%的准确率还是很好用的。 创作不易看官觉得写得还不错的话点个关注和赞吧本人会持续更新python数据分析领域的代码文章~(需要定制类似的代码可私信)