垃圾邮件分类

作者: 本凡_大数据_机器学习 | 来源:发表于2019-04-02 18:54 被阅读1次

    本文使用python基于贝叶斯算法进行邮件分类,具体步骤如下:

    贝叶斯公式P(B/A)=(P(A/B)\cdot P(B))/P(A)

    python使用贝叶斯公式步骤如下:

    打开所在文件:

    with open("d:/sms_spam1.txt","r")as f:

    将文件处理,分成 label 和 feature :

    #按行读取文件

    line = f.readline()

    #文件每一行按逗号隔开为 label 和 feature

    line1 = line.split(",")

    label = line1[0]

    corpu = line1[1]

    #将feature和 label分别存入list中,并分为测试集和训练集

    corpus.append(corpu)

    if 'ham'==label:

    labels.append(0)

    elif 'spam'==label:

    labels.append(1)

    #30行之后为测试集

    if count>30:

    corpus_test.append(corpu)

    if 'ham' ==label:

    labels_test.append(0)

    elif 'spam'==label:

    labels_test.append(1)

    #文本特征提取:

    #将文本特征转换为特征向量的过程

    #采用词袋法进行文本特征提取

    #词袋法:

    #将文章中出现过的词作为一列特征

    #这些不重复的特征词汇集合为词表

    #构建词袋

    vectorize = CountVectorizer()

    #fea_train是每一封邮件中出现词表中词汇个数的矩阵

    fea_train = vectorize.fit_transform(corpus)

    #从第一个词表中创建第二个词表

    vectorize2 = CountVectorizer(vocabulary=vectorize.vocabulary_)

    #生成测试邮件中出现词表中词汇个数的矩阵

    fea_test = vectorize2.fit_transform(corpus_test)

    #拉普拉斯估计给每个单词加一,alpha的设定

    #训练

    clf = MultinomialNB(alpha=1)

    clf.fit(fea_train,labels)

    #预测

    pred = clf.predict(fea_test)

    for p  in pred:

    if p==0:

    print("正常邮件")

    else:

    print("垃圾邮件")

    相关文章

      网友评论

        本文标题:垃圾邮件分类

        本文链接:https://www.haomeiwen.com/subject/dxpwbqtx.html