神經網絡結構
(一)信號的正向傳播
隱藏層輸出 = 激活函數(輸入 * 權值)
最終輸出 = 激活函數 (隱藏層輸出 * 權值)
**
(二)誤差的反向傳播
最終輸出層delta = (標籤 - 最終輸出)* 激活函數的導數(最終輸出)
隱藏層delta = 下一層delta * (下一個權值的轉置)*激活函數的倒數(隱藏層輸出)
(三)權值的增量
最後權值的增量 = 學習率 * 對應輸入值的轉置 * 對應delta
(四)激活函數
(1)sigmoid函數
(2)ReLu函數
(3)Tanh函數
(4)Softsign函數
等等…
(關於BP網絡–手寫數字識別代碼)
import numpy as np
from sklearn.datasets import load_digits #導入手寫數字的圖像
from sklearn.preprocessing import LabelBinarizer #進行標籤二值化
from sklearn.model_selection import train_test_split #進行訓練集和測試集的區分
from sklearn.metrics import classification_report,confusion_matrix #對結果進行評估
import matplotlib.pyplot as plt #畫圖
#載入數據
digits = load_digits()
#定義數據
X = digits.data
#定義標籤
Y = digits.target
#定義神經網絡模型 結構:64-100-10
#定義權值矩陣 範圍0~1
V = np.random.random((64,100)) * 2 - 1
W = np.random.random((100,10)) * 2 - 1
#學習率
lr = 0.1
#數據切分 3/4訓練集 1/4測試集
X_train,X_test,Y_train,Y_test = train_test_split(X,Y)
#標籤二值化
labels_train = LabelBinarizer().fit_transform(Y)
#激活函數
def sigmoid(x):
return 1/(1+np.exp(-x))
#激活函數導數
def dsigmoid(x):
return x * (1-x)
#訓練函數
def train(steps):
global W,V,X,Y,lr
for n in range(steps+1):
#隨機生成一個數據
i = np.random.randint(X.shape[0])
#將這個數據複製
x = X[i]
#轉化爲2維數據
x = np.atleast_2d(x)
#BP算法
#每一層的輸出
L1 = sigmoid(x.dot(V))
L2 = sigmoid(L1.dot(W))
#計算
delta_L2 = (labels_train[i]-L2)*dsigmoid(L2)
delta_L1 = delta_L2.dot(W.T) * dsigmoid(L1)
#權值的增量
delta_W = lr * L1.T.dot(delta_L2)
delta_V = lr * x.T.dot(delta_L1)
#更新權值
W = W + delta_W
V = V + delta_V
#每訓練1000次算一遍準確率
if n%1000 == 0:
output = predict(X_test)
predictions = np.argmax(output,axis=1)
#.mean 求平均 .equal 判斷是否相等 ,返回1或0
acc = np.mean(np.equal(predictions,Y_test)) #預測值與標籤測試值判斷是否相等 然後求平均
print("steps:",n,"acc:",acc)
def predict(x):
L1 = sigmoid(x.dot(V))
L2 = sigmoid(L1.dot(W))
return L2
train(10000)
output = predict(X_test)
predictions = np.argmax(output,axis=1)
print(classification_report(predictions,Y_test))
print(confusion_matrix(predictions,Y_test))