贝叶斯公式(模型)
P ( Y ∣ X ) = P ( X , Y ) P ( X ) = P ( X ∣ Y ) ∗ P ( Y ) P ( X ) P(Y|X)=\frac{P(X,Y)}{P(X)}=\frac{P(X|Y)*P(Y)}{P(X)} P(Y∣X)=P(X)P(X,Y)=P(X)P(X∣Y)∗P(Y)
朴素贝叶斯方法是生成学习方法
将输入x分到后验概率最大的类y.
y = a r g m a x c k P ( Y = c k ) ∏ j = 1 n P ( X j = x ( j ) ∣ Y = c k ) y=\underset{c_{k}}{argmax}P(Y=c_{k})\prod_{j=1}^{n}P(X_{j}=x^{(j)}|Y=c_{k}) y=ckargmaxP(Y=ck)j=1∏nP(Xj=x(j)∣Y=ck),后验概率最大值介于0-1之间时,损失函数的期望风险最小,其中 X = x 1 , x 2 , . . . . . x n , 为n维向量的集合 X={x_{1},x_{2},.....x_{n}},\text{为n维向量的集合} X=x1,x2,.....xn,为n维向量的集合 Y = c 1 , c 2 , . . . . . c k , K为类别数 Y={c_{1},c_{2},.....c_{k}},\text{K为类别数} Y=c1,c2,.....ck,K为类别数,训练数据集 T = ( x 1 , y 1 ) , ( x 2 , y 2 ) , . . . . . ( x n , y n ) 由P(X,Y)独立同分布产生 T={(x_{1},y_{1}),(x_{2},y_{2}),.....(x_{n},y_{n})}\text{由P(X,Y)独立同分布产生} T=(x1,y1),(x2,y2),.....(xn,yn)由P(X,Y)独立同分布产生
# -*- coding: utf-8 -*-
"""
=========================
@Time : 2021/12/26 16:30
@Author : yhz
@File : GaussianNB.py
=========================
"""
# 导包
import numpy as np
import pandas as pd
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from collections import Counter
import math
# 加载数据
def create_data():
iris = load_iris()
df = pd.DataFrame(iris.data, columns=iris.feature_names)
df["label"] = iris.target
df.columns = ['sepal length', 'sepal width', 'petal length', 'petal width', 'label']
data = np.array(df.iloc[:100, :])
# data[:, :-1] 不取最后一列,#data[:, -1]只取最后一列
# print(data[:, -1])
return data[:, :-1], data[:, -1]
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 math.sqrt(sum([pow(x - avg, 2) for x in X]) / float(len(X)))
# 概率密度函数
def gaussian_probability(self, x, mean, stdev):
exponent = math.exp(-(math.pow(x - mean, 2) / (2 * math.pow(stdev, 2))))
return 1 / (math.sqrt((2 * math.pi) * math.pow(stdev, 2))) * exponent
# 处理X_train
def summarize(self, train_data):
summaries = []
for i in zip(*train_data):
summaries = [(self.mean(i), self.stdev(i))]
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)
# for label, value in data.items():
# print(value)
self.model = {
label: self.summarize(value)
for label, value in data.items()
}
return 'gaussianNB train done!'
# 计算概率
def calculate_probabilities(self, input_data):
# 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 = {}
for label, value in self.model.items():
print(label, value)
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):
# {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))
if __name__ == '__main__':
X, y = create_data()
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3)
# print(X_test[0], y_test[0])
model = NaiveBayes()
model.fit(X_train, y_train)
# print(model.predict([4.4, 3.2, 1.3, 0.2]))
# print(model.score(X_test, y_test))
#使用scikit-learn实例
from sklearn.naive_bayes import GaussianNB, BernoulliNB, MultinomialNB
# 高斯模型、伯努利模型和多项式模型
clf = GaussianNB()
clf.fit(X_train, y_train)
print(clf.score(X_test, y_test))
print(clf.predict([[4.4, 3.2, 1.3, 0.2]]))