本文是李航老师的《统计学习方法》[1]一书的代码复现。
作者:黄海广[2]
备注:代码都可以在github[3]中下载。
我将陆续将代码发布在公众号“机器学习初学者”,敬请关注。
代码目录
-
第 1 章 统计学习方法概论
-
第 2 章 感知机
-
第 3 章 k 近邻法
-
第 4 章 朴素贝叶斯
-
第 5 章 决策树
-
第 6 章 逻辑斯谛回归
-
第 7 章 支持向量机
-
第 8 章 提升方法
-
第 9 章 EM 算法及其推广
-
第 10 章 隐马尔可夫模型
-
第 11 章 条件随机场
-
第 12 章 监督学习方法总结
代码参考:wzyonggege[4],WenDesi[5],火烫火烫的[6]
第 4 章 朴素贝叶斯
模型:
-
高斯模型
-
多项式模型
-
伯努利模型
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
# data
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, :])
# print(data)
return data[:,:-1], data[:,-1]
X, y = create_data()
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3)
X_test[0], y_test[0]
(array([5.1, 3.8, 1.9, 0.4]), 0.0)
参考:https://machinelearningmastery.com/naive-bayes-classifier-scratch-python/
GaussianNB 高斯朴素贝叶斯
特征的可能性被假设为高斯
概率密度函数:
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) * 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)
'gaussianNB train done!'
print(model.predict([4.4, 3.2, 1.3, 0.2]))
0.0
model.score(X_test, y_test)
1.0
scikit-learn 实例
from sklearn.naive_bayes import GaussianNB
clf = GaussianNB()
clf.fit(X_train, y_train)
GaussianNB(priors=None, var_smoothing=1e-09)
clf.score(X_test, y_test)
1.0
clf.predict([[4.4, 3.2, 1.3, 0.2]])
array([0.])
参考资料
[1] 《统计学习方法》: https://baike.baidu.com/item/统计学习方法/10430179 [2] 黄海广: https://github.com/fengdu78 [3] github: https://github.com/fengdu78/lihang-code [4] wzyonggege: https://github.com/wzyonggege/statistical-learning-method [5] WenDesi: https://github.com/WenDesi/lihang_book_algorithm [6] 火烫火烫的: https://blog.csdn.net/tudaodiaozhale