参考网站:https://www.python-course.eu/dividing_lines_between_classes.php
通过前几节的铺垫,今天我们就可以尝试创建一个最简单的神经网络了。
按照前面第0章介绍,神经网络有两个输入x1和x2,设置初始权重系数为[-0.5,0.5],创建一个简单神经元,将(6,2)输入,我们得到负数,将(2,6)输入,我们得到正数,我们将两类点簇分别输入,得到类似的结果,验证了我们创建的神经元对于这两类的分辨准确率为100%。
import time
import matplotlib.pyplot as plt
import numpy as np
from itertools import repeat
from random import shuffle
from collections import Counter
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)
class Perceptron:
def __init__(self, weights):
self.weights = np.array(weights)
def __call__(self, in_data):
weighted_input = self.weights * in_data
weighted_sum = weighted_input.sum()
return weighted_sum
p = Perceptron(weights=[-0.5, 0.5])
for point in zip(point1_x[:10], point1_y[:10]):
res = p(point)
print(res, end = "\n ")
for point in zip(point2_x[:10],point2_x[:10]):
res = p(point)
print(res, end = "\n")
evaluation = Counter()
for point in zip(point1_x, point1_y):
res = p(point)
if res < 0:
evaluation['corrects'] += 1
else:
evaluation['wrongs'] += 1
for point in zip(point2_x, point2_y):
res = p(point)
if res >= 0:
evaluation['corrects'] += 1
else:
evaluation['wrongs'] += 1
print(evaluation)
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")
m = 0.5/0.5
ax.plot(X, m * X, linewidth = 2)
ax.grid()
plt.show()