Python与神经网络1.5:创建一个简单的神经网络

参考网站: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()

在这里插入图片描述
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值