第4章 朴素贝叶斯
1.朴素贝叶斯法是典型的生成学习方法。生成方法由训练数据学习联合概率分布
P
(
X
,
Y
)
P(X,Y)
P(X,Y),然后求得后验概率分布
P
(
Y
∣
X
)
P(Y|X)
P(Y∣X)。具体来说,利用训练数据学习
P
(
X
∣
Y
)
P(X|Y)
P(X∣Y)和
P
(
Y
)
P(Y)
P(Y)的估计,得到联合概率分布:
P
(
X
,
Y
)
=
P
(
Y
)
P
(
X
∣
Y
)
P(X,Y)=P(Y)P(X|Y)
P(X,Y)=P(Y)P(X∣Y)
概率估计方法可以是极大似然估计或贝叶斯估计。
2.朴素贝叶斯法的基本假设是条件独立性,
P
(
X
a
m
p
;
=
x
∣
Y
=
c
k
)
=
P
(
X
(
1
)
=
x
(
1
)
,
⋯
,
X
(
n
)
=
x
(
n
)
∣
Y
=
c
k
)
a
m
p
;
=
∏
j
=
1
n
P
(
X
(
j
)
=
x
(
j
)
∣
Y
=
c
k
)
\begin{aligned} P(X&=x | Y=c_{k} )=P\left(X^{(1)}=x^{(1)}, \cdots, X^{(n)}=x^{(n)} | Y=c_{k}\right) \\ &=\prod_{j=1}^{n} P\left(X^{(j)}=x^{(j)} | Y=c_{k}\right) \end{aligned}
P(Xamp;=x∣Y=ck)=P(X(1)=x(1),⋯,X(n)=x(n)∣Y=ck)amp;=j=1∏nP(X(j)=x(j)∣Y=ck)
这是一个较强的假设。由于这一假设,模型包含的条件概率的数量大为减少,朴素贝叶斯法的学习与预测大为简化。因而朴素贝叶斯法高效,且易于实现。其缺点是分类的性能不一定很高。
3.朴素贝叶斯法利用贝叶斯定理与学到的联合概率模型进行分类预测。
P
(
Y
∣
X
)
=
P
(
X
,
Y
)
P
(
X
)
=
P
(
Y
)
P
(
X
∣
Y
)
∑
Y
P
(
Y
)
P
(
X
∣
Y
)
P(Y | X)=\frac{P(X, Y)}{P(X)}=\frac{P(Y) P(X | Y)}{\sum_{Y} P(Y) P(X | Y)}
P(Y∣X)=P(X)P(X,Y)=∑YP(Y)P(X∣Y)P(Y)P(X∣Y)
将输入
x
x
x分到后验概率最大的类
y
y
y。
y
=
arg
max
c
k
P
(
Y
=
c
k
)
∏
j
=
1
n
P
(
X
j
=
x
(
j
)
∣
Y
=
c
k
)
y=\arg \max _{c_{k}} P\left(Y=c_{k}\right) \prod_{j=1}^{n} P\left(X_{j}=x^{(j)} | Y=c_{k}\right)
y=argckmaxP(Y=ck)j=1∏nP(Xj=x(j)∣Y=ck)
后验概率最大等价于0-1损失函数时的期望风险最小化。
模型:
- 高斯模型
- 多项式模型
- 伯努利模型
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
#matplotlib inline
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()#导入iris数据集,是安德森鸢尾花卉数据集。iris_data是一个类似字典的对象。
df = pd.DataFrame(iris.data, columns=iris.feature_names)#DataFrame生成二维数据表,列标为iris表的特征名
df['label'] = iris.target#iris的每个样本都包含了品种信息,即目标属性(第5列,也叫target或label)
df.columns = ['sepal length', 'sepal width', 'petal length', 'petal width', 'label']#df的列标
data = np.array(df.iloc[:100, :])#将列表list或元组tuple转换为ndarray数组,iloc函数只根据行列号对数据进行索引,行到100,列为全部
print(data)#显示数据
return data[:,:-1], data[:,-1]
输出:
[[5.1 3.5 1.4 0.2 0. ]
[4.9 3. 1.4 0.2 0. ]
[4.7 3.2 1.3 0.2 0. ]
[4.6 3.1 1.5 0.2 0. ]
[5. 3.6 1.4 0.2 0. ]
[5.4 3.9 1.7 0.4 0. ]
[4.6 3.4 1.4 0.3 0. ]
[5. 3.4 1.5 0.2 0. ]
[4.4 2.9 1.4 0.2 0. ]
[4.9 3.1 1.5 0.1 0. ]
[5.4 3.7 1.5 0.2 0. ]
[4.8 3.4 1.6 0.2 0. ]
[4.8 3. 1.4 0.1 0. ]
[4.3 3. 1.1 0.1 0. ]
[5.8 4. 1.2 0.2 0. ]
[5.7 4.4 1.5 0.4 0. ]
[5.4 3.9 1.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
[5.6 2.9 3.6 1.3 1. ]
[6.7 3.1 4.4 1.4 1. ]
[5.6 3. 4.5 1.5 1. ]
[5.8 2.7 4.1 1. 1. ]
[6.2 2.2 4.5 1.5 1. ]
[5.6 2.5 3.9 1.1 1. ]
[5.9 3.2 4.8 1.8 1. ]
[6.1 2.8 4. 1.3 1. ]
[6.3 2.5 4.9 1.5 1. ]
[6.1 2.8 4.7 1.2 1. ]
[6.4 2.9 4.3 1.3 1. ]
[6.6 3. 4.4 1.4 1. ]
[6.8 2.8 4.8 1.4 1. ]
[6.7 3. 5. 1.7 1. ]
[6. 2.9 4.5 1.5 1. ]
[5.7 2.6 3.5 1. 1. ]
[5.5 2.4 3.8 1.1 1. ]
[5.5 2.4 3.7 1. 1. ]
[5.8 2.7 3.9 1.2 1. ]
[6. 2.7 5.1 1.6 1. ]
[5.4 3. 4.5 1.5 1. ]
[6. 3.4 4.5 1.6 1. ]
[6.7 3.1 4.7 1.5 1. ]
[6.3 2.3 4.4 1.3 1. ]
[5.6 3. 4.1 1.3 1. ]
[5.5 2.5 4. 1.3 1. ]
[5.5 2.6 4.4 1.2 1. ]
[6.1 3. 4.6 1.4 1. ]
[5.8 2.6 4. 1.2 1. ]
[5. 2.3 3.3 1. 1. ]
[5.6 2.7 4.2 1.3 1. ]
[5.7 3. 4.2 1.2 1. ]
[5.7 2.9 4.2 1.3 1. ]
[6.2 2.9 4.3 1.3 1. ]
[5.1 2.5 3. 1.1 1. ]
[5.7 2.8 4.1 1.3 1. ]]
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])#显示测试集的第一个
输出:
[5.8 2.6 4. 1.2] 1.0
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)))#pow(x,n) ,即计算 x 的 n 次幂函数。
# 概率密度函数
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) * stdev)) * exponent
# 处理X_train
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):
# 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():
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))
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))#得分率
输出:
0.0
1.0
from sklearn.naive_bayes import GaussianNB#先验为高斯分布的朴素贝叶斯
#from sklearn.naive_bayes import 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]]))#预测该点的值
输出:
1.0
[0.]