感知机算法实现-python

一.Python实现《李航统计学》第二章感知机算法。
先来说一下算法原原理吧:

  1. 感知机由输入空间到输出空间的函数为:
    y = s i g n ( w ∗ x + b ) y=sign(w*x+b) y=sign(wx+b)
    s i g n ( x ) = + 1 ( x > = 0 ) sign(x)= +1 (x>=0) sign(x)=+1(x>=0)
    s i g n ( x ) = − 1 ( x &lt; 0 ) sign(x) = -1(x&lt;0) sign(x)=1(x<0)

算法实现的步骤如下:

  1. 初始化w,b
  2. 遍历数据(x,y)
  3. 如果遇到sign(w*x(i)+b)!= y(i),则更新w,b
    w = w + l e a r n i n g − r a t e ∗ y ( i ) ∗ x ( i ) w = w +learning-rate*y(i)*x(i) w=w+learningratey(i)x(i)
    b = b + l e a r n i n g − r a t e ∗ y ( i ) b = b+learning-rate*y(i) b=b+learningratey(i)
  4. 然后结束本次遍历,转至步骤2,知道数据中没有分类错误的点存在。
import numpy as np
x = np.array([
	[3,3],
	[4,3],
	[1,1]
])
y = np.array([1,1,-1])
w = np.array([1,1])
b = 0
learning_rate = 0.1
for i in range(10):
	temp = -1
	for j in range(x.shape[0]):
		pred = np.sign(np.dot(w,x[j])+b)   
		if pred != y[j]:
			temp = j
			break
	if temp != -1:
		w = w + learning_rate*x[temp]*y[temp]
		b = b + learning_rate*y[temp]

基本迭代几次就可以得到该平面了。

版本二:

import numpy as np

def process(x,y,learning_rate=0.01,epoch=100):
    w = np.ones_like(x[1])
    b = 1
    for i in range(epoch):
        temp = -1
        for j in range(x.shape[0]):
            pred = np.sign(np.dot(w,x[j])+b)
            if pred != y[j]:
                temp = j
                break
        if temp != -1:
            w = w + learning_rate * x[temp] * y[temp]
            b = b + learning_rate * y[temp]
       
x = np.array([
	[3,3],
	[4,3],
	[1,1]
])
y = np.array([1,1,-1])


process(x,y,1,10)

版本三:

import numpy as np


class Perceptron:

    def fit(self,x,y,learning_rate=0.1, epoch=100):
        self.x = x
        self.y = y
        self.learning_rate = learning_rate
        self.epoch = epoch
        self.w = np.ones_like(x[1])
        self.b = 1
        for i in range(self.epoch):
            temp = -1
            for j in range(self.x.shape[0]):
                pred = np.sign(np.dot(self.w, self.x[j]) + self.b)
                if pred != self.y[j]:
                    temp = j
                    break
            if temp != -1:
                self.w = self.w + self.learning_rate * self.x[temp] * self.y[temp]
                self.b = self.b + self.learning_rate * self.y[temp]
    def pred(self,x):

        return np.sign(np.dot(self.w,x)+self.b)

x = np.array([
	[3,3],
	[4,3],
	[1,1]
])
y = np.array([1,1,-1])


a = Perceptron()
a.fit(x,y,1)

print(a.pred(np.array([1,1])))

上面以三种不同形式的代码实现了感知机,随着以后的深入学习,还会继续完善这些代码。

Thank for your reading !!!

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

FPGA之旅

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值