戳藍色字關注我們喲!
感知器作為初代神經網絡,具有簡單、計算量小等優點,但只能解決線性問題。BP神經網絡在感知器的基礎上,增加了隱藏層,通過任意複雜的模式分類能力和優良的多維函數映射能力,解決了異或等感知器不能解決的問題,並且BP神經網絡也是CNN等複雜神經網絡等思想根源。
BP神經網絡是一種通過誤差反向傳播算法進行誤差校正的多層前饋神經網絡,其最核心的特點就是:信號是前向傳播,而誤差是反向傳播。前向傳播過程中,輸入信號經由輸入層、隱藏層逐層處理,到輸出層時,如果結果未到達期望要求,則進入反向傳播過程,將誤差信號原路返回,修改各層權重。
BP神經網絡包含輸入層、隱藏層和輸出層,其中,隱藏層可有多個,其中,輸入層和輸出層的節點個數是固定的(分別是輸入樣本的變量個數和輸出標籤個數),但隱藏層的節點個數不固定。以具有單隱藏層的BP神經網絡為例,其網絡結構如下圖:
以單隱藏層的BP神經網絡為例,各階段原理公式如下:
這裡,我們用手寫數字圖片建立一個僅有1層隱藏層的BP神經網絡,並進行訓練及預測。每張圖片大小為8*8,因此有64個圖片像素變量及1個偏置項,共65個輸入層節點;訓練目標是將手寫圖片判斷為0-9,因此有10個輸出層節點;隱藏層節點數這裡設置為100。圖片示例如下:
另外,這裡兩個激活函數我們都選用sigmoid函數,且這個函數都導數有一個特點,即f′(x)=f(x)(1−f(x))。import numpy as npfrom sklearn.datasets import load_digitsfrom sklearn.preprocessing import LabelBinarizer from sklearn.model_selection import train_test_split
def sigmoid(x): return 1/(1+np.exp(-x))def dsigmoid(x): return x*(1-x)class NeuralNetwork: def __init__(self,layers): self.V = np.random.random((layers[0]+1,layers[1]+1))*2-1 self.W = np.random.random((layers[1]+1,layers[2]))*2-1 def train(self,X,y,lr=0.11,epochs=10000): temp = np.ones([X.shape[0],X.shape[1]+1]) temp[:,0:-1] = X X = temp for n in range(epochs+1): i = np.random.randint(X.shape[0]) x = [X[i]] x = np.atleast_2d(x) L1 = sigmoid(np.dot(x,self.V)) L2 = sigmoid(np.dot(L1,self.W)) L2_delta = (y[i]-L2)*dsigmoid(L2) L1_delta = L2_delta.dot(self.W.T) self.W += lr*L1.T.dot(L2_delta) self.V += lr*x.T.dot(L1_delta) if n%1000==0: predictions = [] for j in range(X_test.shape[0]): o = self.predict(X_test[j]) predictions.append(np.argmax(o)) accuracy = np.mean(np.equal(predictions,y_test)) print('epoch:',n,'accuracy:',accuracy) def predict(self,x): temp = np.ones(x.shape[0]+1) temp[0:-1] = x x = temp x = np.atleast_2d(x)
L1 = sigmoid(np.dot(x,self.V)) L2 = sigmoid(np.dot(L1,self.W)) return L2digits = load_digits()X = digits.datay = digits.targetX -= X.min()X /= X.max()
nm = NeuralNetwork([64,100,10])X_train,X_test,y_train,y_test = train_test_split(X,y) labels_train = LabelBinarizer().fit_transform(y_train)labels_test = LabelBinarizer().fit_transform(y_test)
print('start')nm.train(X_train,labels_train,epochs=20000)print('end')輸出結果如下,可以看到隨著訓練次數提升,模型準確率穩定在0.95、0.96。相關推薦: