垃圾邮件
Posted yan668
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了垃圾邮件相关的知识,希望对你有一定的参考价值。
from sklearn.metrics import confusion_matrix, classification_report from sklearn.naive_bayes import MultinomialNB import csv file_path=r‘F:duymaismsspamcollectionsms.txt‘ sms=open(file_path,‘r‘,encoding=‘utf-8‘) sms_data=[] sms_label=[] csv_reader=csv.reader(sms,delimiter=‘ ‘) for line in csv_reader: sms_label.append(line[0]) sms_data.append(preprocessing(line[1])) sms.close() def preprocessing(text): preprocessed_text = text return preprocessed_text #按0.7:0.3比例分为训练集和测试集 from sklearn.model_selection import train_test_split x_train,x_test,_y_train,_y_test =train_test_split(sms_data,sms_label,test_size=0.3,random_state=0,stratify=sms_label) from sklearn.feature_extraction.text import TfidfVectorizer vectorizer=TfidfVectorizer(min_df=2,ngram_range=(1,2),stop_words=‘english‘,strip_accents=‘unicode‘,norm=‘l2‘) X_train=vectorizer.fit_transform(x_train) X_test=vectorizer.transform(x_test) clf = MultinomialNB().fit(X_train,y_train) y_nb_pred = clf.predict(X_test) # 分类结果显示 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_repert:‘) cr = classification_report(y_test,y_nb_pred) # 主要分类指标的文本报告 print(cr) feature_names=vectorizer.get_feature_names() # 出现过的单词列表 coefs=clf.coef_ # 先验概率 p(x_ily),6034 feature_log_preb intercept = clf.intercept_ # P(y),class_log_prior : array,shape(n... 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]) for (coef_1,fn_1),(coef_2,fn_2) in top: print(‘ %.4f %-15s %.4f %-15s‘ % (coef_1,fn_1,coef_2,fn_2))
以上是关于垃圾邮件的主要内容,如果未能解决你的问题,请参考以下文章