python实现神经网络感知器算法

yipeiwu_com5年前Python基础

现在我们用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循环时方便查看数据变化。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

一篇文章快速了解Python的GIL

一篇文章快速了解Python的GIL

前言:博主在刚接触Python的时候时常听到GIL这个词,并且发现这个词经常和Python无法高效的实现多线程划上等号。本着不光要知其然,还要知其所以然的研究态度,博主搜集了各方面的资料...

使用C++扩展Python的功能详解

使用C++扩展Python的功能详解

本文主要研究的是使用C++扩展Python的功能的相关问题,具体如下。 环境 VS2005Python2.5.4Windows7(32位) 简介 长话短说,这里说的扩展Python功能与...

python threading和multiprocessing模块基本用法实例分析

本文实例讲述了python threading和multiprocessing模块基本用法。分享给大家供大家参考,具体如下: 前言 这两天为了做一个小项目,研究了一下python的并发编...

Python 3.x基于Xml数据的Http请求方法

Python 3.x基于Xml数据的Http请求方法

1. 前言 由于公司的一个项目是基于B/S架构与WEB服务通信,使用XML数据作为通信数据,在添加新功能时,WEB端与客户端分别由不同的部门负责,所以在WEB端功能实现过程中,需要自己发...

python中redis查看剩余过期时间及用正则通配符批量删除key的方法

具体代码如下所示: # -*- coding: utf-8 -*- import redis import datetime ''' # 1. redis设置过期时间的两种方式 e...