代码编织梦想

import os
import re
import string
import math

DATA_DIR = 'enron'
target_names = ['ham', 'spam']


def get_data(DATA_DIR):
    subfolders = ['enron%d' % i for i in range(1, 7)]
    data = []
    target = []
    for subfolder in subfolders:
        spam_files = os.listdir(os.path.join(DATA_DIR, subfolder, 'spam'))
        for spam_file in spam_files:
            with open(os.path.join(DATA_DIR, subfolder, 'spam', spam_file), encoding="latin-1") as f:
                data.append(f.read())
                target.append(1)
        ham_files = os.listdir(os.path.join(DATA_DIR, subfolder, 'ham'))
        for ham_file in ham_files:
            with open(os.path.join(DATA_DIR, subfolder, 'ham', ham_file), encoding="latin-1") as f:
                data.append(f.read())
                target.append(0)
    return data, target


X, y = get_data(DATA_DIR)


class SpamDetector_1(object):
    """Implementation of Naive Bayes for binary classification"""

    def clean(self, s):
        translator = str.maketrans("", "", string.punctuation)
        return s.translate(translator)

    def tokenize(self, text):
        text = self.clean(text).lower()
        return re.split("\W+", text)

    def get_word_counts(self, words):
        word_counts = {}
        for word in words:
            word_counts[word] = word_counts.get(word, 0.0) + 1.0
        return word_counts


class SpamDetector_2(SpamDetector_1):
    def fit(self, X, Y):
        self.num_messages = {}
        self.log_class_priors = {}
        self.word_counts = {}
        self.vocab = set()
        self.num_messages['spam'] = sum(1 for label in Y if label == 1)
        self.num_messages['ham'] = sum(1 for label in Y if label == 0)

        self.log_class_priors['spam'] = math.log(
            self.num_messages['spam'] / (self.num_messages['spam'] + self.num_messages['ham']))
        self.log_class_priors['ham'] = math.log(
            self.num_messages['ham'] / (self.num_messages['spam'] + self.num_messages['ham']))

        self.word_counts['spam'] = {}
        self.word_counts['ham'] = {}

        for x, y in zip(X, Y):
            c = 'spam' if y == 1 else 'ham'
            counts = self.get_word_counts(self.tokenize(x))
            for word, count in counts.items():
                if word not in self.vocab:
                    self.vocab.add(word) 
                if word not in self.word_counts[c]:
                    self.word_counts[c][word] = 0.0
                self.word_counts[c][word] += count


MNB = SpamDetector_2()
MNB.fit(X[100:], y[100:])


class SpamDetector(SpamDetector_2):
    def predict(self, X):
        result = []
        flag_1 = 0
        for x in X:
            counts = self.get_word_counts(self.tokenize(x)) 
            spam_score = 0
            ham_score = 0
            flag_2 = 0
            for word, _ in counts.items():
                if word not in self.vocab:
                    continue

                else:
                    if word in self.word_counts['spam'].keys() and word in self.word_counts['ham'].keys():
                        log_w_given_spam = math.log(
                            (self.word_counts['spam'][word] + 1) / (
                                    sum(self.word_counts['spam'].values()) + len(self.vocab)))
                        log_w_given_ham = math.log(
                            (self.word_counts['ham'][word] + 1) / (sum(self.word_counts['ham'].values()) + len(
                                self.vocab)))
                    if word in self.word_counts['spam'].keys() and word not in self.word_counts['ham'].keys():
                        log_w_given_spam = math.log(
                            (self.word_counts['spam'][word] + 1) / (
                                    sum(self.word_counts['spam'].values()) + len(self.vocab)))
                        log_w_given_ham = math.log(1 / (sum(self.word_counts['ham'].values()) + len(
                            self.vocab)))
                    if word not in self.word_counts['spam'].keys() and word in self.word_counts['ham'].keys():
                        log_w_given_spam = math.log(1 / (sum(self.word_counts['spam'].values()) + len(self.vocab)))
                        log_w_given_ham = math.log(
                            (self.word_counts['ham'][word] + 1) / (sum(self.word_counts['ham'].values()) + len(
                                self.vocab)))

                spam_score += log_w_given_spam
                ham_score += log_w_given_ham

                flag_2 += 1

                spam_score += self.log_class_priors['spam']
                ham_score += self.log_class_priors['ham']

            if spam_score > ham_score:
                result.append(1)
            else:
                result.append(0)

            flag_1 += 1

        return result


MNB = SpamDetector()
MNB.fit(X[100:], y[100:])
pred = MNB.predict(X[:100])
true = y[:100]

accuracy = 0
for i in range(100):
    if pred[i] == true[i]:
        accuracy += 1
print(accuracy)

 运行结果:

分类正确率为98% 

 

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/CipherXXX/article/details/128014807

qust日常训练(1)分数修改-爱代码爱编程

题目描述 很多学校流行一种比较的习惯。老师们很喜欢询问,从某某到某某当中,分数最高的是多少。 这让很多学生感到反感,不管你喜不喜欢,现在需要你做的是,就是按照老师的要求,写一个程序,模拟老师的询问。当然,老师有时候需要更新某位同学的成绩。 输入 本题目包含多组测试,请处理到文件结束。在每个测试的第一行,有两个正整数 N 和 M分别

qust日常训练(1)乘积最大-爱代码爱编程

题目描述 很多学校流行一种比较的习惯。老师们很喜欢询问,从某某到某某当中,分数最高的是多少。 这让很多学生感到反感,不管你喜不喜欢,现在需要你做的是,就是按照老师的要求,写一个程序,模拟老师的询问。当然,老师有时候需要更新某位同学的成绩。 输入 本题目包含多组测试,请处理到文件结束。在每个测试的第一行,有两个正整数 N 和 M分别

qust作业 numpy入门_cipherxxx的博客-爱代码爱编程

data = np.array([1,2,3])  代表一个数组1 2 3 data = np.array([1,2,3]).max() print(data) 可以得到数组[1,2,3]中的最大值 3 np.one(3) 可以得到一列包含三个一的数组  np.zeros(3)可以得到一列包含三个0的数组 np.random.random(3

qust 三门问题_cipherxxx的博客-爱代码爱编程

定义变量: Main函数:  方法函数: 讲解: 首先定义三个全局变量,分别为int类型的总次数和获得礼品的次数,以及随机选择的一扇门。 主函数中,使用for函数迭代1000次,首先让玩家第一次的选择取一个1~3之间的随机数作为门的编号。(在上次尝试中将开的门的编号和门后有奖品的门的编号都作为随机数,结果在其一起迭代时产生的两个随机数

qust 爬虫-爱代码爱编程

打开网页链接:https://sh.lianjia.com/zufang/ 按F12打开网页源代码(我的电脑fn+f12会默认打开飞行模式 只按f12才能打开源代码) 使用左上角的后,选择浦东 我们得到: 需要导入的库 主函数    爬取的链接为: https://sh.lianjia.com/zufang/ 保存路径