垃圾邮件完整

1.读取

直接代码简单易懂

代码:

SMSS = open("D:\数据可视化技术课程文件\SMSSpamCollection", 'r', encoding='utf-8')  # 数据读取
SMSS_detail = []  # 邮件内容
SMSS_label = []  # 邮件标题
csv_reader = csv.reader(SMSS, delimiter='\t')
# 对每封邮件进行预处理
for line in csv_reader:
    SMSS_label.append(line[0])  # 获取标题
    SMSS_detail.append(preprocessing(line[1]))  # 获取处理后邮件数据
SMSS.close()  # 关闭读取流
print("邮件标题:\n", SMSS_label)  # 邮件标题
print("邮件内容:")                # 邮件内容
for i in SMSS_detail:
    print(i)

 

2.数据预处理

代码:

#邮件预处理
def preprocessing(text):
    # 分词
    tokens = [word for sent in nltk.sent_tokenize(text) for word in nltk.word_tokenize(sent)]
    # 停用词
    stops=stopwords.words("english")    # 构建停用器
    tokens = [token for token in tokens if token not in stops]
    # 词性标注
    nltk.pos_tag(tokens)
    # 词性还原Lemmatisation
    lemmatizer=WordNetLemmatizer()  # 定义还原对象
    tokens=[lemmatizer.lemmatize(token, pos='n')for token in tokens]  # 名词还原
    tokens=[lemmatizer.lemmatize(token, pos='v')for token in tokens]  # 动词还原
    tokens=[lemmatizer.lemmatize(token, pos='a')for token in tokens]  # 形容词还原
    return tokens  # 返回处理结果

 

3.数据划分—训练集和测试集数据划分

from sklearn.model_selection import train_test_split

x_train,x_test, y_train, y_test = train_test_split(data, target, test_size=0.2, random_state=0, stratify=y_train)

代码:

def split_dataset(data, label):
     x_train, x_test, y_train, y_test = train_test_split(data, label, test_size=0.2, random_state=0, stratify=label)
     return x_train, x_test, y_train, y_test

 

4.文本特征提取

sklearn.feature_extraction.text.CountVectorizer

https://scikit-learn.org/stable/modules/generated/sklearn.feature_extraction.text.CountVectorizer.html?highlight=sklearn%20feature_extraction%20text%20tfidfvectorizer

sklearn.feature_extraction.text.TfidfVectorizer

https://scikit-learn.org/stable/modules/generated/sklearn.feature_extraction.text.TfidfVectorizer.html?highlight=sklearn%20feature_extraction%20text%20tfidfvectorizer#sklearn.feature_extraction.text.TfidfVectorizer

from sklearn.feature_extraction.text import TfidfVectorizer

tfidf2 = TfidfVectorizer()

代码:

(转换为特征矩阵)

 

def tfidf_dataset(x_train,x_test):
     tfidf = TfidfVectorizer()
     X_train = tfidf.fit_transform(x_train)  # X_train用fit_transform生成词汇表
     X_test = tfidf.transform(x_test) 
     return X_train, X_test, tfidf

 

 

 

向量还原为邮件

代码:

 

def revert_mail(x_train, X_train, model):
    s = X_train.toarray()[0]
    print("首个邮件转向量为:", s)
    a = np.flatnonzero(X_train.toarray()[0])  # 非零元素的位置(index)
    print("非零元素的位置:", a)
    print("向量的非零元素的值:", s[a])
    b = model.vocabulary_  # 词汇表
    key_list = []
    for key, value in b.items():
        if value in a:
            key_list.append(key)  # key非0元素对应的单词
    print("非零元素其单词:", key_list)
    print("还原成邮件为:", x_train[0])

 

 

 

4.模型选择

from sklearn.naive_bayes import GaussianNB

from sklearn.naive_bayes import MultinomialNB

选用多项式分布:

代码:

def mnb_model(x_train, x_test, y_train, y_test):
    mnb = MultinomialNB()
    mnb.fit(x_train, y_train)
    ypre_mnb = mnb.predict(x_test)
    print("总数:", len(y_test))
    print("正确个数:", (ypre_mnb == y_test).sum())
    return ypre_mnb

说明为什么选择这个模型?

答:因为第一项的高斯模型是倾向正态分布问题的,它本身就是来画正态分布的,而垃圾文件和正态分布是毫无关联的,它主要是依照检测那些垃圾文件中频繁出现的词来进行判断的,词频无序,不好用高斯。

5.模型评价:混淆矩阵,分类报告

from sklearn.metrics import confusion_matrix

confusion_matrix = confusion_matrix(y_test, y_predict)

代码:

def class_report(ypre_mnb, y_test):
    conf_matrix = confusion_matrix(y_test, ypre_mnb)print("混淆矩阵:\n", conf_matrix)
    c = classification_report(y_test, ypre_mnb)print("分类报告:\n", c)
    print("模型准确率:", (conf_matrix[0][0] + conf_matrix[1][1]) / np.sum(conf_matrix))

 

说明混淆矩阵的含义

答:混淆矩阵是就机器学习中总结分类模型预测结果的情形分析表,以矩阵形式将数据集中的记录按照真实的类别与分类模型预测的类别判断两个标准进行汇总,其行表示真实值,其列表示预测值。

from sklearn.metrics import classification_report

说明准确率、精确率、召回率、F值分别代表的意义 

答:

  准确率accuracy=(a+d)/(a+b+c+d)=(TP+FN+FP+TN)

  精确率Precision=a/(a+c)=TP/(TP+FP)

  召回率recall=a/(a+b)=TP/(TP+FN)

  F=2*[(精确率*召回率)/(精确率+召回率)]

6.比较与总结

如果用CountVectorizer进行文本特征生成,与TfidfVectorizer相比,效果如何?

答:相比的话,会多一些非重要词,产生干扰,可能会降低判断的准确性。效果不会太好。

posted @ 2020-05-27 20:56  CrJia  阅读(248)  评论(0编辑  收藏  举报