机器学习入门及感知机模型笔记
绪论
一边学习林軒田的机器学习基石和技法、李航的统计学习方法和PRML,一边输出学习过程中自己理解做的笔记,欢迎大家一起交流,由于文中公式太多,目前兼容性不太好,就统一截图上传了。
正文
机器学习流程
机器学习案例(感知机理论)
Python实现感知机模型
import numpy as np
from matplotlib import pyplot as plt
plt.rcParams['font.sans-serif'] = ['SimHei'] # 用来正常显示中文标签
plt.rcParams['axes.unicode_minus'] = False # 用来正常显示负号
class Perceptron:
def __init__(self, x, y, eta=0.3):
# 超参数:步长
self.eta = eta
# 初始化参数w0, b0
self.w = np.zeros(x.shape[1])
self.b = 0
# 保存训练集
self.x = x
self.y = y
# 迭代次数,用来评估模型训练速度
self.iter_num = 0
def train(self):
# 取出所有误分类点
wrong_points = np.where(self.y * (np.dot(self.x, self.w.T) + self.b) <= 0)
self.iter_num = 0
# 梯度下降直至没有误分类点
while wrong_points[0].any():
self.iter_num += 1
# 打乱顺序,随机取出一个误分类点
np.random.shuffle(wrong_points[0])
x = self.x[wrong_points[0][0]]
y = self.y[wrong_points[0][0]]
self.w += self.eta * x * y
self.b += self.eta * y
wrong_points = np.where(self.y * (np.dot(self.x, self.w.T) + self.b) <= 0)
# 预测函数
def predict(self, x):
if np.dot(x, self.w.T) + self.b > 0:
return 1
else:
return -1
# 绘制分类结果
def draw(self):
# 训练集点,正例蓝色,负例红色
x1 = self.x[np.where(self.y > 0)][:, 0]
y1 = self.x[np.where(self.y > 0)][:, 1]
x2 = self.x[np.where(self.y < 0)][:, 0]
y2 = self.x[np.where(self.y < 0)][:, 1]
# 超平面S
x3 = np.arange(0, 6, 0.1)
y3 = (self.w[0] * x3 + self.b) / (-self.w[1])
plt.plot(x1, y1, 'go', x2, y2, 'ro')
plt.plot(x3, y3,'b--', label='超平面S')
plt.legend()
plt.show()
def main():
# 数据集
x = np.array([[3, 0.5], [6, 1.1], [1.5, 1.1], [2, 0.8], [0.8, 0.5], [3.3, 2.2], [1.7, 2.5], [2.7, 2.8], [4.3, 5.3], [1.5, 3.2], [0.8, 2.3], [2.4, 5]])
y = np.array([1, 1, 1, 1, 1, 1, -1, -1, -1, -1, -1, -1])
perceptron = Perceptron(x, y)
perceptron.train()
perceptron.draw()
print("迭代次数:", perceptron.iter_num)
if __name__ == "__main__":
main()
输出结果:
总结
1)还需要进一步证明算法的收敛性
2)进一步学习感知机的对偶形式
参考文献
[1] 机器学习基石和技法.林軒田
[2] 统计学习方法.李航
[3] prml && github