python实现神经网络感知器算法
作者:海峰-清欢 时间:2021-03-06 11:23:39
现在我们用python代码实现感知器算法。
# -*- coding: utf-8 -*-
import numpy as np
class Perceptron(object):
"""
eta:学习率
n_iter:权重向量的训练次数
w_:神经分叉权重向量
errors_:用于记录神经元判断出错次数
"""
def __init__(self, eta=0.01, n_iter=2):
self.eta = eta
self.n_iter = n_iter
pass
def fit(self, X, y):
"""
输入训练数据培训神经元
X:神经元输入样本向量
y: 对应样本分类
X:shape[n_samples,n_features]
x:[[1,2,3],[4,5,6]]
n_samples = 2 元素个数
n_features = 3 子向量元素个数
y:[1,-1]
初始化权重向量为0
加一是因为前面算法提到的w0,也就是步调函数阈值
"""
self.w_ = np.zeros(1 + X.shape[1])
self.errors_ = []
for _ in range(self.n_iter):
errors = 0
"""
zip(X,y) = [[1,2,3,1],[4,5,6,-1]]
xi是前面的[1,2,3]
target是后面的1
"""
for xi, target in zip(X, y):
"""
predict(xi)是计算出来的分类
"""
update = self.eta * (target - self.predict(xi))
self.w_[1:] += update * xi
self.w_[0] += update
print update
print xi
print self.w_
errors += int(update != 0.0)
self.errors_.append(errors)
pass
def net_input(self, X):
"""
z = w0*1+w1*x1+....Wn*Xn
"""
return np.dot(X, self.w_[1:]) + self.w_[0]
def predict(self, X):
return np.where(self.net_input(X) >= 0, 1, -1)
if __name__ == '__main__':
datafile = '../data/iris.data.csv'
import pandas as pd
df = pd.read_csv(datafile, header=None)
import matplotlib.pyplot as plt
import numpy as np
y = df.loc[0:100, 4].values
y = np.where(y == "Iris-setosa", 1, -1)
X = df.iloc[0:100, [0, 2]].values
# plt.scatter(X[:50, 0], X[:50, 1], color="red", marker='o', label='setosa')
# plt.scatter(X[50:100, 0], X[50:100, 1], color="blue", marker='x', label='versicolor')
# plt.xlabel("hblength")
# plt.ylabel("hjlength")
# plt.legend(loc='upper left')
# plt.show()
pr = Perceptron()
pr.fit(X, y)
其中数据为
控制台输出为
你们跑代码的时候把n_iter设置大点,我这边是为了看每次执行for循环时方便查看数据变化。
来源:http://blog.csdn.net/u013692888/article/details/76999252
标签:python,神经网络,感知器
0
投稿
猜你喜欢
首页访问感受提升三步曲
2007-12-13 20:36:00
Python for循环通过序列索引迭代过程解析
2021-11-30 05:36:50
Python使用Opencv打开笔记本电脑摄像头报错解问题及解决
2022-12-02 10:32:01
PHP header()函数常用方法总结
2023-09-06 16:51:50
微信小程序request请求后台接口php的实例详解
2023-11-11 14:24:04
举例讲解Linux系统下Python调用系统Shell的方法
2023-08-25 00:04:46
python做翻译软件详解,小白也看得明白
2023-08-08 06:25:44
Python实现炸金花游戏的示例代码
2022-01-15 05:24:17
accept-charset与Header P3P
2009-04-01 18:43:00
Python 相对路径报错:"No such file or directory"'原因及解决方法
2021-08-12 05:34:00
解析CSS列表样式属性list-style
2009-03-26 13:16:00
pygame游戏之旅 添加游戏介绍
2022-12-03 09:13:08
MySQL启动连接的命令以及与PHP程序连接的基本语法
2023-11-14 22:27:26
Python文本相似性计算之编辑距离详解
2022-04-28 12:14:23
一篇文章教你用Python绘画一个太阳系
2022-12-16 14:43:16
Pygame Rect区域位置的使用(图文)
2023-08-14 05:27:48
一文详解Go语言fmt标准库的常用占位符使用
2023-08-07 01:57:56
基于Python绘制子图及子图刻度的变换等的问题
2023-12-12 14:14:33
python 使用事件对象asyncio.Event来同步协程的操作
2023-02-24 12:46:41
用Python生成N层的杨辉三角的实现方法
2022-12-20 16:27:09