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))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.w

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值