【Python-ML】感知器学习算法(perceptron)
生活随笔
收集整理的這篇文章主要介紹了
【Python-ML】感知器学习算法(perceptron)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
1、數學模型
?
2、權值訓練
?
3、Python代碼
?
感知器收斂的前提是兩個類別必須是線性可分的,且學習速率足夠小。如果兩個類別無法通過一個線性決策邊界進行劃分,要為模型在訓練集上的學習迭代次數設置一個最大值,或者設置一個允許錯誤分類樣本數量的閾值,否則感知器訓練算法將永遠不停地更新權值。
?
# -*- coding: utf-8 -*- ''' Created on 2017年12月15日 @author: Jason.F @summary: 感知器學習算法 ''' import numpy as np import time import matplotlib.pyplot as plt import pandas as pd class perceptron(object):''' Perceptron classifier.Parameterseta:float=Learning rate (between 0.0 and 1.0)n_iter:int=Passes over the training dataset.Attributesw_:ld-array=weights after fitting.errors_:list=Number of misclassifications in every epoch.'''def __init__(self,eta=0.01,n_iter=10):self.eta=etaself.n_iter=n_iterdef fit(self,X,y):'''Fit training data.ParametersX:{array-like},shape=[n_samples,n_features]Training vectors,where n_samples is the number of the samples and n_features is the number of features.y:array-like,shape=[n_samples]Target values.Returnsself:object'''self.w_=np.zeros(1+X.shape[1])self.errors_=[]for _ in range(self.n_iter):errors=0for xi , target in zip(X,y):update=self.eta * (target - self.predict(xi))self.w_[1:]+=update *xiself.w_[0]+=updateerrors += int (update !=0.0)self.errors_.append(errors)return selfdef net_input(self,X):'''Calculate net input'''return np.dot(X, self.w_[1:])+self.w_[0]def predict(self,X):'''Return class label after unit step'''return np.where(self.net_input(X) >=0.0,1,-1)if __name__ == "__main__": start = time.clock() train =pd.read_csv('https://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data',header=None)ppn = perceptron(eta=0.01,n_iter=10)X_train = train.drop([4], axis=1)X_train=X_train.values #dataframe convert to arrayy_train = train[4].valuesy_train=np.where(y_train == 'Iris-setosa',-1,1)ppn.fit(X_train,y_train)#預測print (ppn.predict([6.9,3.0,5.1,1.8]))#繪制錯誤分類樣本數量plt.plot(range(1,len(ppn.errors_)+1),ppn.errors_,marker='o')plt.xlabel('Epochs')plt.ylabel('Number of misclassifications')plt.show()end = time.clock() print('finish all in %s' % str(end - start))代碼中用UCI機器學習庫中的數據集做試驗。可設置不同的學習速率eta和迭代次數n_iter觀察收斂情況。
總結
以上是生活随笔為你收集整理的【Python-ML】感知器学习算法(perceptron)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 【数据平台】Pytorch库初识
- 下一篇: 【Python-ML】自适应线性神经网络