参考网站:https://www.python-course.eu/dividing_lines_between_classes.php
现在我们有了两类点簇,我们依然是通过眼睛直接可以将它们分类,但是我们能否通过算法自动的寻找出两类点的分界线。
我们设定直线的初始斜率为m,然后对两个类的所有点分别判断,如果第一类点在直线之上则加上一个Δm,如果在第二类点如果直线之下则减去一个Δm。
import matplotlib.pyplot as plt
import numpy as np
from itertools import repeat
from random import shuffle
def points_within_circle(radius,center=(0,0),number_of_points=100):
center_x, center_y = center
r = radius * np.sqrt(np.random.random((number_of_points,)))
theta = np.random.random((number_of_points,))*2*np.pi
x = center_x + r * np.cos(theta)
y = center_y + r * np.sin(theta)
return x, y
point1_x, point1_y = points_within_circle(2, (6, 2), 100)
point2_x, point2_y = points_within_circle(2, (2, 6), 100)
m = 0.1
X = np.arange(0, 8)
fig, ax = plt.subplots()
ax.scatter(point1_x, point1_y, c="red", label="class 1")
ax.scatter(point2_x, point2_y, c="black", label="class 2")
points = list(zip(point1_x, point1_y,repeat(0,len(point1_x))))
points += list(zip(point2_x, point2_y,repeat(1,len(point2_x))))
shuffle(points)
delta_m = 0.2
line = None
counter = 0
for x, y, label in points:
res = y - m * x
if label == 0 and res > 0:
m += delta_m
counter += 1
ax.plot(X, m * X,linewidth=2,label=str(counter))
elif label == 1 and res < 0:
m -= delta_m
counter += 1
ax.plot(X, m * X, linewidth=2, label=str(counter))
ax.legend()
ax.grid()
print(m)
plt.show()