kingzone 2020-04-21
假设分类模型样本是:
共有m
个样本, n
个特征, K
个类别, 定义为\(C_1, C_2, ... , C_K\)。
从样本中可以得到先验分布\(P(Y=C_k)(k=1,2,...,K)\), 也可以根据特定的先验知识定义先验分布。
接着需要得到条件概率分布\(P(X=x|Y=C_k)=P(X_1=x_1,X_2=x_2,...X_n=x_n|Y=C_k)\), 然后求得联合分布:
\(P(Y=C_k)\) 可以用最大似然法求出, 得到的\(P(Y=C_k)\)就是类别\(C_k\)在训练集中出现的频数。但是条件概率分布\(P(X=x|Y=C_k)=P(X_1=x_1,X_2=x_2,...X_n=x_n|Y=C_k)\),很难求出,朴素贝叶斯模型在这里做了一个大胆的假设,即X
的n
个维度之间相互独立,这样就可以得出:
我们只要计算出所有的K个条件概率\(P(Y=C_k|X=X^{(test)})\),然后找出最大的条件概率对应的类别,这就是朴素贝叶斯的预测。
假设预测的类别\(C_result\)是使\(P(Y=C_k|X=X^{(test)})\)最大化的类别,数学表达式为:
接着利用朴素贝叶斯的独立性假设,就可以得到朴素贝叶斯推断公式:
假设服从多项式分布,这样得到\(P(X_j=X^{(test)}_j|Y=C_k)\)是在样本类别\(C_k\)中,特征\(X^{(test)}_j\)出现的频率。即:
某些时候,可能某些类别在样本中没有出现,这样可能导致\(P(X_j=X^{(test)}_j|Y=C_k)\)为0,这样会影响后验的估计,为了解决这种情况,引入了拉普拉斯平滑,即此时有:
假设服从伯努利分布, 即特征\(X_j\)出现记为1,不出现记为0。即只要\(X_j\)出现即可,不关注\(X_j\)的次数。此时有:
通常假设\(X_j\)的先验概率为正态分布, 有:
优点:
缺点:
import math class NaiveBayes: def __init__(self): self.model = None # 数学期望 @staticmethod def mean(X): """计算均值 Param: X : list or np.ndarray Return: avg : float """ avg = 0.0 # ========= show me your code ================== avg = sum(X) / float(len(X)) # ========= show me your code ================== return avg # 标准差(方差) def stdev(self, X): """计算标准差 Param: X : list or np.ndarray Return: res : float """ res = 0.0 # ========= show me your code ================== avg = self.mean(X) res = math.sqrt(sum([pow(x - avg, 2) for x in X]) / float(len(X))) # ========= show me your code ================== return res # 概率密度函数 def gaussian_probability(self, x, mean, stdev): """根据均值和标注差计算x符号该高斯分布的概率 Parameters: ---------- x : 输入 mean : 均值 stdev : 标准差 Return: res : float, x符合的概率值 """ res = 0.0 # ========= show me your code ================== exponent = math.exp(-(math.pow(x - mean, 2) / (2 * math.pow(stdev, 2)))) res = (1 / (math.sqrt(2 * math.pi) * stdev)) * exponent # ========= show me your code ================== return res # 处理X_train def summarize(self, train_data): """计算每个类目下对应数据的均值和标准差 Param: train_data : list Return : [mean, stdev] """ summaries = [0.0, 0.0] # ========= show me your code ================== summaries = [(self.mean(i), self.stdev(i)) for i in zip(*train_data)] # ========= show me your code ================== 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): """计算数据在各个高斯分布下的概率 Paramter: input_data : 输入数据 Return: probabilities : {label : p} """ # summaries:{0.0: [(5.0, 0.37),(3.42, 0.40)], 1.0: [(5.8, 0.449),(2.7, 0.27)]} # input_data:[1.1, 2.2] probabilities = {} # ========= show me your code ================== 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) # ========= show me your code ================== return probabilities # 类别 def predict(self, X_test): # {0.0: 2.9680340789325763e-27, 1.0: 3.5749783019849535e-26} 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))
from sklearn.naive_bayes import GaussianNB from sklearn.datasets import load_iris import pandas as pd from sklearn.model_selection import train_test_split iris = load_iris() X_train, X_test, y_train, y_test = train_test_split(iris.data, iris.target, test_size=0.2) clf = GaussianNB().fit(X_train, y_train) print ("Classifier Score:", clf.score(X_test, y_test)) model = NaiveBayes() model.fit(X_train, y_train) print(model.predict([4.4, 3.2, 1.3, 0.2])) model.score(X_test, y_test)