话不多说,直接上代码.原理很
简单,注意的是这里的激活函数是单位阶跃函数.
# -*- coding: utf-8 -*-
"""
Spyder Editor
This is a temporary script file.
"""
#! /usr/bin/env python
#coding=utf-8
import numpy as np
import unittest
import matplotlib.pylab as plt
#感知器分类的学习
class Perceptron:
'''''
eta:学习率
n_iter:权重向量的训练次数
w_:权重向量
errors_:记录神经元判断出错的次数
'''
def __init__(self, alpha=0.01, n_iter=20):
self.alpha = alpha
self.n_iter = n_iter
def fit(self, X, Y):
m, n = shape(X)#返回训练数据集的行数与列数 这里的n代表有多少个
self.intercept = 0
self.W = mat(ones((n, 1)))
for i in range(self.n_iter):
for x, y in zip(X, Y):
y_ = float(x * self.W) + self.intercept
if y * y_ < 0: #由于是感知器,所以这里我们使用阶跃函数
self.W += x.T * self.alpha * y #修改其权值
self.intercept += self.alpha * y #修改其偏置值
if self.loss(X, Y) == 0: #如果所是函数的值符合要求,那么我们就返回
return i
def loss(self, X, Y):
sum_loss = 0.0
for x, y in zip(X, Y):
y_ = float(x * self.W) + self.intercept
if y * y_ < 0:
sum_loss += - y * y_
return sum_loss
class PerceptronTest(unittest.TestCase):
def test_fit(self):
X = mat(array([[2, 4.3], [1, 2.4], [1, 3.3], [2, 1.8], [3, 9.2], [4, 6.3], [5, 10.1], [2.3, 3.4], [3.2, 6]]))
Y = np.array([1, 1, 1, -1, 1, -1, 1, -1, -1])
icons = {1: 'ko', -1: 'bo'}
# print X
for x, y in zip(X, Y): #Python中的zip函数
plt.plot(x[0, 0], x[0, 1], icons[y])
perceptron = Perceptron(alpha=0.1, n_iter=20)
print (perceptron.fit(X, Y))
# points on the hyperplane
p1 = [0, -perceptron.intercept / perceptron.W[1, 0]]
p2 = [5, (-perceptron.intercept - 5 * perceptron.W[0, 0]) / perceptron.W[1, 0]]
# print the hyperplane
plt.plot([p1[0], p2[0]], [p1[1], p2[1]])
plt.title("gan zhi qi er fen lei")
plt.xlabel('X')
plt.ylabel('Y')
plt.show()
if __name__ == '__main__':
unittest.main() #这里是测试代码,供我们测试时使用...

简单,注意的是这里的激活函数是单位阶跃函数.