江东的笔记

Be overcome difficulties is victory

0%

梯度下降--感知机实现

用梯度下降法来优化感知机模型

任务:用梯度下降的方法优化感知机

首先导入包

1
2
3
# 首先导入包:
import matplotlib.pyplot as plt
import numpy as np

数据的准备

1
2
3
4
# x = np.array([[-1., 2.], [0., 0.], [0., 2.], [1., 0]])
x = np.array([[0., 2.], [1., 0], [-1., 2.], [0., 0.]])
# y = np.array([1, 1, -1, -1])
y = np.array([-1, -1, 1, 1])

可视化函数的定义

1
2
3
4
5
6
7
8
9
10
11
12
def plot_plot(x, omega, b):
xx = np.linspace(-5, 5, 100)
yy = - 1 / omega[1] * (omega[0] * xx + b)
plt.figure()
plt.scatter(x[:, 0], x[:, 1], c=y)
plt.plot(xx, yy)
plt.xlabel('x1')
plt.ylabel('x2')
plt.title('({}) * x1 + ({}) * x2 + ({}) = 0'.format(*omega, b))
plt.xlim(-3, 3)
plt.ylim(-3, 3)
plt.grid()

随机初始化

1
2
3
omega = np.array([0., 0.])
b = 0.0
eta = 1.0

感知机函数

1
2
def sign(pp, b, omega):
return np.sign(np.dot(pp, omega) + b)

实现梯度下降

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
check = False
while not check:
check = True
ter = list(zip(x, y))
np.random.shuffle(ter)
np.random.seed(10)
print(ter)
for xi, yi in ter:
if sign(xi, b, omega) * yi <= 0:
print(xi)
print(omega, b)
omega += eta * xi * yi
b += eta * yi
print(omega, b)
check = False
print()
plot_plot(x, omega, b)

最终优化的曲结果在这里插入图片描述