反向傳播算法實(shí)戰(zhàn)
本次的反向傳播算法是基于上篇文章神經(jīng)網(wǎng)絡(luò)之反向傳播算法(BP)詳細(xì)公式推導(dǎo)
實(shí)現(xiàn)的抡四,如果對(duì)反向傳播算法不太了解,強(qiáng)烈建議參考上篇文章。
我們將實(shí)現(xiàn)一個(gè) 4
層的全連接網(wǎng)絡(luò),來(lái)完成二分類任務(wù)海雪。網(wǎng)絡(luò)輸入節(jié)點(diǎn)數(shù)為 2
,隱藏 層的節(jié)點(diǎn)數(shù)設(shè)計(jì)為:25舱殿、50
和25
奥裸,輸出層兩個(gè)節(jié)點(diǎn),分別表示屬于類別 1
的概率和類別 2
的概率沪袭,如下圖所示湾宙。這里并沒(méi)有采用 Softmax
函數(shù)將網(wǎng)絡(luò)輸出概率值之和進(jìn)行約束, 而是直接利用均方誤差函數(shù)計(jì)算與 One-hot
編碼的真實(shí)標(biāo)簽之間的誤差冈绊,所有的網(wǎng)絡(luò)激活 函數(shù)全部采用 Sigmoid
函數(shù)创倔,這些設(shè)計(jì)都是為了能直接利用我們的梯度傳播公式。
import numpy as np
import matplotlib.pyplot as plt
from sklearn import datasets
from sklearn.model_selection import train_test_split
1. 準(zhǔn)備數(shù)據(jù)
X, y = datasets.make_moons(n_samples=1000, noise=0.2, random_state=100)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42)
print(X.shape, y.shape) # (1000, 2) (1000,)
(1000, 2) (1000,)
def make_plot(X, y, plot_name):
plt.figure(figsize=(12, 8))
plt.title(plot_name, fontsize=30)
plt.scatter(X[y==0, 0], X[y==0, 1])
plt.scatter(X[y==1, 0], X[y==1, 1])
make_plot(X, y, "Classification Dataset Visualization ")
2. 網(wǎng)絡(luò)層
- 通過(guò)新建類
Layer
實(shí)現(xiàn)一個(gè)網(wǎng)絡(luò)層焚碌,需要傳入網(wǎng)絡(luò)層的輸入節(jié)點(diǎn)數(shù)畦攘、輸出節(jié)點(diǎn)數(shù)、激 活函數(shù)類型等參數(shù) - 權(quán)值
weights
和偏置張量bias
在初始化時(shí)根據(jù)輸入十电、輸出節(jié)點(diǎn)數(shù)自動(dòng) 生成并初始化
class Layer:
# 全鏈接網(wǎng)絡(luò)層
def __init__(self, n_input, n_output, activation=None, weights=None, bias=None):
"""
:param int n_input: 輸入節(jié)點(diǎn)數(shù)
:param int n_output: 輸出節(jié)點(diǎn)數(shù)
:param str activation: 激活函數(shù)類型
:param weights: 權(quán)值張量知押,默認(rèn)類內(nèi)部生成
:param bias: 偏置叹螟,默認(rèn)類內(nèi)部生成
"""
self.weights = weights if weights is not None else np.random.randn(n_input, n_output) * np.sqrt(1 / n_output)
self.bias = bias if bias is not None else np.random.rand(n_output) * 0.1
self.activation = activation # 激活函數(shù)類型,如’sigmoid’
self.activation_output = None # 激活函數(shù)的輸出值 o
self.error = None # 用于計(jì)算當(dāng)前層的 delta 變量的中間變量
self.delta = None # 記錄當(dāng)前層的 delta 變量台盯,用于計(jì)算梯度
def activate(self, X):
# 前向計(jì)算函數(shù)
r = np.dot(X, self.weights) + self.bias # X@W + b
# 通過(guò)激活函數(shù)罢绽,得到全連接層的輸出 o (activation_output)
self.activation_output = self._apply_activation(r)
return self.activation_output
def _apply_activation(self, r): # 計(jì)算激活函數(shù)的輸出
if self.activation is None:
return r # 無(wú)激活函數(shù),直接返回
elif self.activation == 'relu':
return np.maximum(r, 0)
elif self.activation == 'tanh':
return np.tanh(r)
elif self.activation == 'sigmoid':
return 1 / (1 + np.exp(-r))
return r
def apply_activation_derivative(self, r):
# 計(jì)算激活函數(shù)的導(dǎo)數(shù)
# 無(wú)激活函數(shù)静盅, 導(dǎo)數(shù)為 1
if self.activation is None:
return np.ones_like(r)
# ReLU 函數(shù)的導(dǎo)數(shù)
elif self.activation == 'relu':
grad = np.array(r, copy=True)
grad[r > 0] = 1.
grad[r <= 0] = 0.
return grad
# tanh 函數(shù)的導(dǎo)數(shù)實(shí)現(xiàn)
elif self.activation == 'tanh':
return 1 - r ** 2
# Sigmoid 函數(shù)的導(dǎo)數(shù)實(shí)現(xiàn)
elif self.activation == 'sigmoid':
return r * (1 - r)
return r
3. 網(wǎng)絡(luò)模型
- 創(chuàng)建單層網(wǎng)絡(luò)類后良价,我們實(shí)現(xiàn)網(wǎng)絡(luò)模型的
NeuralNetwork
類 - 它內(nèi)部維護(hù)各層的網(wǎng)絡(luò) 層
Layer
類對(duì)象,可以通過(guò)add_layer
函數(shù)追加網(wǎng)絡(luò)層蒿叠, - 實(shí)現(xiàn)創(chuàng)建不同結(jié)構(gòu)的網(wǎng)絡(luò)模型目 的明垢。
y_test.flatten().shape # (300,)
(300,)
class NeuralNetwork:
def __init__(self):
self._layers = [] # 網(wǎng)絡(luò)層對(duì)象列表
def add_layer(self, layer):
self._layers.append(layer)
def feed_forward(self, X):
# 前向傳播(求導(dǎo))
for layer in self._layers:
X = layer.activate(X)
return X
def backpropagation(self, X, y, learning_rate):
# 反向傳播算法實(shí)現(xiàn)
# 向前計(jì)算,得到最終輸出值
output = self.feed_forward(X)
for i in reversed(range(len(self._layers))): # 反向循環(huán)
layer = self._layers[i]
if layer == self._layers[-1]: # 如果是輸出層
layer.error = y - output
# 計(jì)算最后一層的 delta市咽,參考輸出層的梯度公式
layer.delta = layer.error * layer.apply_activation_derivative(output)
else: # 如果是隱藏層
next_layer = self._layers[i + 1]
layer.error = np.dot(next_layer.weights, next_layer.delta)
layer.delta = layer.error*layer.apply_activation_derivative(layer.activation_output)
# 循環(huán)更新權(quán)值
for i in range(len(self._layers)):
layer = self._layers[i]
# o_i 為上一網(wǎng)絡(luò)層的輸出
o_i = np.atleast_2d(X if i == 0 else self._layers[i - 1].activation_output)
# 梯度下降算法痊银,delta 是公式中的負(fù)數(shù),故這里用加號(hào)
layer.weights += layer.delta * o_i.T * learning_rate
def train(self, X_train, X_test, y_train, y_test, learning_rate, max_epochs):
# 網(wǎng)絡(luò)訓(xùn)練函數(shù)
# one-hot 編碼
y_onehot = np.zeros((y_train.shape[0], 2))
y_onehot[np.arange(y_train.shape[0]), y_train] = 1
mses = []
for i in range(max_epochs): # 訓(xùn)練 100 個(gè) epoch
for j in range(len(X_train)): # 一次訓(xùn)練一個(gè)樣本
self.backpropagation(X_train[j], y_onehot[j], learning_rate)
if i % 10 == 0:
# 打印出 MSE Loss
mse = np.mean(np.square(y_onehot - self.feed_forward(X_train)))
mses.append(mse)
print('Epoch: #%s, MSE: %f, Accuracy: %.2f%%' %
(i, float(mse), self.accuracy(self.predict(X_test), y_test.flatten()) * 100))
return mses
def accuracy(self, y_predict, y_test): # 計(jì)算準(zhǔn)確度
return np.sum(y_predict == y_test) / len(y_test)
def predict(self, X_predict):
y_predict = self.feed_forward(X_predict) # 此時(shí)的 y_predict 形狀是 [600 * 2]施绎,第二個(gè)維度表示兩個(gè)輸出的概率
y_predict = np.argmax(y_predict, axis=1)
return y_predict
4. 網(wǎng)絡(luò)訓(xùn)練
nn = NeuralNetwork() # 實(shí)例化網(wǎng)絡(luò)類
nn.add_layer(Layer(2, 25, 'sigmoid')) # 隱藏層 1, 2=>25
nn.add_layer(Layer(25, 50, 'sigmoid')) # 隱藏層 2, 25=>50
nn.add_layer(Layer(50, 25, 'sigmoid')) # 隱藏層 3, 50=>25
nn.add_layer(Layer(25, 2, 'sigmoid')) # 輸出層, 25=>2
# nn.train(X_train, X_test, y_train, y_test, learning_rate=0.01, max_epochs=50)
def plot_decision_boundary(model, axis):
x0, x1 = np.meshgrid(
np.linspace(axis[0], axis[1], int((axis[1] - axis[0])*100)).reshape(1, -1),
np.linspace(axis[2], axis[3], int((axis[3] - axis[2])*100)).reshape(-1, 1)
)
X_new = np.c_[x0.ravel(), x1.ravel()]
y_predic = model.predict(X_new)
zz = y_predic.reshape(x0.shape)
from matplotlib.colors import ListedColormap
custom_cmap = ListedColormap(['#EF9A9A', '#FFF590', '#90CAF9'])
plt.contourf(x0, x1, zz, linewidth=5, cmap=custom_cmap)
plt.figure(figsize=(12, 8))
plot_decision_boundary(nn, [-2, 2.5, -1, 2])
plt.scatter(X[y==0, 0], X[y==0, 1])
plt.scatter(X[y==1, 0], X[y==1, 1])
<matplotlib.collections.PathCollection at 0x29018d6dfd0>
y_predict = nn.predict(X_test)
y_predict[:10] # array([1, 1, 0, 1, 0, 0, 0, 1, 1, 1], dtype=int64)
array([1, 1, 0, 1, 0, 0, 0, 1, 1, 1], dtype=int64)
y_test[:10] # array([1, 1, 0, 1, 0, 0, 0, 1, 1, 1], dtype=int64)
array([1, 1, 0, 1, 0, 0, 0, 1, 1, 1], dtype=int64)
nn.accuracy(y_predict, y_test.flatten()) # 0.86
0.86