上一篇文章给出了感知机算法的原理,这里给出Python实现感知机算法的代码:
感知机原始形式实现代码:
# -*- coding: utf-8 -*-
"""
Created on Sun Jul 14 09:48:09 2019
@author: 等等登登-Ande
E-mail:18356768364@163.com
感知机算法原始形式实现(perception)
data为输入数据
label为标签
n为学习率
inter为迭代次数
"""
import numpy as np
import matplotlib.pyplot as plt
def perception(data,label,n,inter):
raw,col = np.shape(data)
w = np.random.randn(1,col)
b = np.random.randn(1)
x1 = -1
y1 = (-1/w[:,1])*(np.dot(w[:,0],x1)+b)
x2 = 2
y2 = (-1/w[:,1])*(np.dot(w[:,0],x2)+b)
plt.plot([x1,x2],[y1,y2],color='red')
plt.scatter(data[1:15,0],data[1:15,1],color='blue',marker='x')
plt.scatter(data[16:,0],data[16:,1],color='red',marker='o')
plt.show()
for times in range(inter):
for i in range(raw):
if -label[i-1]*(np.dot(w,(data[:][i-