感知機是二分類的線性分類模型,其輸入為實例的特征向量,輸出為實例的類別
感知機模型的假設空間為分類超平面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))