python实现感知器算法(批处理)实现感知器算法(批处理)
主要为大家详细介绍了python实现感知器算法,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
本文实例为大家分享了Python感知器算法实现的具体代码,供大家参考,具体内容如下
先创建感知器类:用于二分类
# -*- coding: utf-8 -*-
import numpy as np
class Perceptron(object):
"""
感知器:用于二分类
参照改写 https://blog.csdn.net/simple_the_best/article/details/54619495
属性:
w0:偏差
w:权向量
learning_rate:学习率
threshold:准则阈值
"""
def __init__(self,learning_rate=0.01,threshold=0.001):
self.learning_rate=learning_rate
self.threshold=threshold
def train(self,x,y):
"""训练
参数:
x:样本,维度为n*m(样本有m个特征,x输入就是m维),样本数量为n
y:类标,维度为n*1,取值1和-1(正样本和负样本)
返回:
self:object
"""
self.w0=0.0
self.w=np.full(x.shape[1],0.0)
k=0
while(True):
k+=1
dJw0=0.0
dJw=np.zeros(x.shape[1])
err=0.0
for i in range(0,x.shape[0]):
if not (y[i]==1 or y[i]==-1):
print("类标只能为1或-1!请核对!")
break
update=self.learning_rate*0.5*(y[i]-self.predict(x[i]))
dJw0+=update
dJw+=update*x[i]
err+=np.abs(0.5*(y[i]-self.predict(x[i])))
self.w0 += dJw0
self.w += dJw
if np.abs(np.sum(self.learning_rate*dJw))<self.threshold or k>500:
print("迭代次数:",k," 错分样本数:",err)
break
return self
def predict(self,x):
"""预测类别
参数:
x:样本,1*m维,1个样本,m维特征
返回:
yhat:预测的类标号,1或者-1,1代表正样本,-1代表负样本
"""
if np.matmul(self.w,x.T)+self.w0>0:
yhat=1
else:
yhat=-1
return yhat
def predict_value(self,x):
"""预测值
评论0