<jupyter_start><jupyter_text>$$GaussianNB$$$$E(X)=\sum_{i=1}^{∞}x_ip_i$$$$D(X)=\sum_i^{n}(x_i-EX)^2p_i$$$$P(x_i|y_i)=\frac{1}{\sqrt{2\pi\sigma^{2}_{yk}}}exp(-\frac{(x_i-u_{yk})^2}{2\sigma^2_{yk}})$$<jupyter_code># 定义高斯贝叶斯模型
class NaiveBayes:
    def __init__(self):
        self.model = None
        
    # 均值
    @staticmethod
    def mean(X):
        return sum(X)/float(len(X))
    
    # 标准差
    def stdev(self,X):
        avg = self.mean(X)
        return np.sqrt(sum([np.power(x-avg,2) for x in X])/float(len(X)))
    
    # 概率密度函数
    def gaussian_probability(self,x,mean,stdev):
        exponent = np.exp(-(np.power(x-mean,2)/(2*np.power(stdev,2))))
        
        return (1/(np.sqrt(2*np.pi)*stdev))*exponent
    
    # process train set
    def summarize(self,train_data):
        summaries = [(self.mean(i),self.stdev(i)) for i in zip(*train_data)]
        return summaries
    
    # 计算平均值和标准差
    def fit(self,X,y):
        labels = list(set(y))
        data = {label:[] for label in labels}
        for f,label in zip(X,y):
            data[label].append(f)
            
        self.model = {
            label : self.summarize(value)
            for label,value in data.items()
        }
        
        return 'gaussianNB train done!'
    
    # 计算概率
    def calculate_probabilities(self,input_data):
        probabilities = {}
        for label,value in self.model.items():
            probabilities[label] = 1
            for i in range(len(value)):
                mean , stdev = value[i]
                probabilities[label] *= self.gaussian_probability(input_data[i],mean,stdev)
                
        return probabilities
    
    
    # 返回标签
    def predict(self,X_test):
        label = sorted(
            self.calculate_probabilities(X_test).items(),
            key = lambda x:x[-1])[-1][0]
        return label
    
    def score(self,X_test,y_test):
        right = 0
        for X,y in zip(X_test,y_test):
            label = self.predict(X)
            if label == y:
                right += 1
        return right/float(len(X_test))
clf = NaiveBayes()
clf.fit(X_train,y_train)
print(clf.predict([4.4,  3.2,  1.3,  0.2]))
clf.score(X_test,y_test)<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.15492321589882566, 'fraction_numerical': 0.012646793134598013, 'mean_word_length': 2.128531073446328, 'pattern_counts': {'":': 0, '<': 5, '<?xml version=': 0, '>': 5, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '1', 'dir': 'jupyter-structured-clean-dedup', 'id': '346849', 'license': 'MIT', 'n_tokens_mistral': 839, 'n_tokens_neox': 844, 'n_words': 129, 'path': 'Labs/朴素贝叶斯法/Labs/navie_bayes_by_hand.ipynb', 'repo_name': 'tsuirak/Statistical-Learning-Methods-lihang', 'size': '2214'}