感知机模型

感知机是二分类的线性分类模型,其输入为实例的特征向量,输出为实例的类别

感知机模型的假设空间为分类超平面wx+b=0

模型复杂度主要体现在x(x(1),x(2),....x(d))的特征数量也就是x的维度d上

感知机模型的求解策略(伪代码):

输入:训练集T={(x1,y1),(x2,y2),....(xn,yn)}其中y为正1和负1,学习率n
输出:w,b,感知机模型f(x)=sign(wx+b)
(1)选取初始值w0,b,
(2)在数据集中选取(xi,yi)
(3)如果yi(wxi+b)<=0
    w=w+nyixi
    b=b+nyi
(4)转至(2)

对于感知机模型我们进行一次训练

(1)首先是感知机的自编程实现

 

import numpy as np
def main():
    x_train=np.array([[3,3],[4,3],[1,1]])
    y=np.array([1,1,-1])
    perceptron=Myperceptron()
    perceptron.fit(x_train,y)
    draw(x_train,perceptron.w,perceptron.b)

class Myperceptron:
    def _init_:
        self.w=None
        self.b=0
        l_rate=1

def fit(self, x_train,y_train):
    self.w=np.zeros(x_train.shape[1])
    i=0
    while(i<x_train.shape[0]):
        X=x_train
        Y=y_train
        if(Y*(np.dot(self.w,X)+self.b):
            self.w=self.w+self.l_rate*np.dot(Y,X)
            self.b=self.b+self.l_rate*Y
        else:
            i+=1

(2)使用sklearn的库

from sklearn.linear_model import Perceptron
import numpy as np
x_train=np.array([[3,3],[4,3],[1,1]])
y=np.array([1,1,-1])
perceptron=Perceptron()
perceptron.fit(x_train,y)
print("w:",perceptron.coef_,"\n","b:",perceptron.intercept_,"\n",,"n_iter.",perceptron.n_iter_)
perceptron.score(x_train,y)
print("correct rate:{:.0%}".format(res))

 

posted @ 2019-05-07 11:16  Cucucu  阅读(798)  评论(0编辑  收藏  举报