本篇文章為大家展示了使用Python怎么實(shí)現(xiàn)一個NN神經(jīng)網(wǎng)絡(luò)算法,內(nèi)容簡明扼要并且容易理解,絕對能使你眼前一亮,通過這篇文章的詳細(xì)介紹希望你能有所收獲。
專注于為中小企業(yè)提供成都網(wǎng)站設(shè)計(jì)、成都做網(wǎng)站、外貿(mào)網(wǎng)站建設(shè)服務(wù),電腦端+手機(jī)端+微信端的三站合一,更高效的管理,為中小企業(yè)鹿寨免費(fèi)做網(wǎng)站提供優(yōu)質(zhì)的服務(wù)。我們立足成都,凝聚了一批互聯(lián)網(wǎng)行業(yè)人才,有力地推動了上千家企業(yè)的穩(wěn)健成長,幫助中小企業(yè)通過網(wǎng)站建設(shè)實(shí)現(xiàn)規(guī)模擴(kuò)充和轉(zhuǎn)變。運(yùn)行環(huán)境
Pyhton3
numpy(科學(xué)計(jì)算包)
matplotlib(畫圖所需,不畫圖可不必)
sklearn(人工智能包,生成數(shù)據(jù)使用)
計(jì)算過程
輸入樣例
none
代碼實(shí)現(xiàn)
# -*- coding:utf-8 -*- #!python3 __author__ = 'Wsine' import numpy as np import sklearn import sklearn.datasets import sklearn.linear_model import matplotlib.pyplot as plt import matplotlib import operator import time def createData(dim=200, cnoise=0.20): """ 輸出:數(shù)據(jù)集, 對應(yīng)的類別標(biāo)簽 描述:生成一個數(shù)據(jù)集和對應(yīng)的類別標(biāo)簽 """ np.random.seed(0) X, y = sklearn.datasets.make_moons(dim, noise=cnoise) plt.scatter(X[:, 0], X[:, 1], s=40, c=y, cmap=plt.cm.Spectral) #plt.show() return X, y def plot_decision_boundary(pred_func, X, y): """ 輸入:邊界函數(shù), 數(shù)據(jù)集, 類別標(biāo)簽 描述:繪制決策邊界(畫圖用) """ # 設(shè)置最小大值, 加上一點(diǎn)外邊界 x_min, x_max = X[:, 0].min() - .5, X[:, 0].max() + .5 y_min, y_max = X[:, 1].min() - .5, X[:, 1].max() + .5 h = 0.01 # 根據(jù)最小大值和一個網(wǎng)格距離生成整個網(wǎng)格 xx, yy = np.meshgrid(np.arange(x_min, x_max, h), np.arange(y_min, y_max, h)) # 對整個網(wǎng)格預(yù)測邊界值 Z = pred_func(np.c_[xx.ravel(), yy.ravel()]) Z = Z.reshape(xx.shape) # 繪制邊界和數(shù)據(jù)集的點(diǎn) plt.contourf(xx, yy, Z, cmap=plt.cm.Spectral) plt.scatter(X[:, 0], X[:, 1], c=y, cmap=plt.cm.Spectral) def calculate_loss(model, X, y): """ 輸入:訓(xùn)練模型, 數(shù)據(jù)集, 類別標(biāo)簽 輸出:誤判的概率 描述:計(jì)算整個模型的性能 """ W1, b1, W2, b2 = model['W1'], model['b1'], model['W2'], model['b2'] # 正向傳播來計(jì)算預(yù)測的分類值 z1 = X.dot(W1) + b1 a1 = np.tanh(z1) z2 = a1.dot(W2) + b2 exp_scores = np.exp(z2) probs = exp_scores / np.sum(exp_scores, axis=1, keepdims=True) # 計(jì)算誤判概率 corect_logprobs = -np.log(probs[range(num_examples), y]) data_loss = np.sum(corect_logprobs) # 加入正則項(xiàng)修正錯誤(可選) data_loss += reg_lambda/2 * (np.sum(np.square(W1)) + np.sum(np.square(W2))) return 1./num_examples * data_loss def predict(model, x): """ 輸入:訓(xùn)練模型, 預(yù)測向量 輸出:判決類別 描述:預(yù)測類別屬于(0 or 1) """ W1, b1, W2, b2 = model['W1'], model['b1'], model['W2'], model['b2'] # 正向傳播計(jì)算 z1 = x.dot(W1) + b1 a1 = np.tanh(z1) z2 = a1.dot(W2) + b2 exp_scores = np.exp(z2) probs = exp_scores / np.sum(exp_scores, axis=1, keepdims=True) return np.argmax(probs, axis=1) def initParameter(X): """ 輸入:數(shù)據(jù)集 描述:初始化神經(jīng)網(wǎng)絡(luò)算法的參數(shù) 必須初始化為全局函數(shù)! 這里需要手動設(shè)置! """ global num_examples num_examples = len(X) # 訓(xùn)練集的大小 global nn_input_dim nn_input_dim = 2 # 輸入層維數(shù) global nn_output_dim nn_output_dim = 2 # 輸出層維數(shù) # 梯度下降參數(shù) global epsilon epsilon = 0.01 # 梯度下降學(xué)習(xí)步長 global reg_lambda reg_lambda = 0.01 # 修正的指數(shù) def build_model(X, y, nn_hdim, num_passes=20000, print_loss=False): """ 輸入:數(shù)據(jù)集, 類別標(biāo)簽, 隱藏層層數(shù), 迭代次數(shù), 是否輸出誤判率 輸出:神經(jīng)網(wǎng)絡(luò)模型 描述:生成一個指定層數(shù)的神經(jīng)網(wǎng)絡(luò)模型 """ # 根據(jù)維度隨機(jī)初始化參數(shù) np.random.seed(0) W1 = np.random.randn(nn_input_dim, nn_hdim) / np.sqrt(nn_input_dim) b1 = np.zeros((1, nn_hdim)) W2 = np.random.randn(nn_hdim, nn_output_dim) / np.sqrt(nn_hdim) b2 = np.zeros((1, nn_output_dim)) model = {} # 梯度下降 for i in range(0, num_passes): # 正向傳播 z1 = X.dot(W1) + b1 a1 = np.tanh(z1) # 激活函數(shù)使用tanh = (exp(x) - exp(-x)) / (exp(x) + exp(-x)) z2 = a1.dot(W2) + b2 exp_scores = np.exp(z2) # 原始?xì)w一化 probs = exp_scores / np.sum(exp_scores, axis=1, keepdims=True) # 后向傳播 delta3 = probs delta3[range(num_examples), y] -= 1 dW2 = (a1.T).dot(delta3) db2 = np.sum(delta3, axis=0, keepdims=True) delta2 = delta3.dot(W2.T) * (1 - np.power(a1, 2)) dW1 = np.dot(X.T, delta2) db1 = np.sum(delta2, axis=0) # 加入修正項(xiàng) dW2 += reg_lambda * W2 dW1 += reg_lambda * W1 # 更新梯度下降參數(shù) W1 += -epsilon * dW1 b1 += -epsilon * db1 W2 += -epsilon * dW2 b2 += -epsilon * db2 # 更新模型 model = { 'W1': W1, 'b1': b1, 'W2': W2, 'b2': b2} # 一定迭代次數(shù)后輸出當(dāng)前誤判率 if print_loss and i % 1000 == 0: print("Loss after iteration %i: %f" % (i, calculate_loss(model, X, y))) plot_decision_boundary(lambda x: predict(model, x), X, y) plt.title("Decision Boundary for hidden layer size %d" % nn_hdim) #plt.show() return model def main(): dataSet, labels = createData(200, 0.20) initParameter(dataSet) nnModel = build_model(dataSet, labels, 3, print_loss=False) print("Loss is %f" % calculate_loss(nnModel, dataSet, labels)) if __name__ == '__main__': start = time.clock() main() end = time.clock() print('finish all in %s' % str(end - start)) plt.show()
上述內(nèi)容就是使用Python怎么實(shí)現(xiàn)一個NN神經(jīng)網(wǎng)絡(luò)算法,你們學(xué)到知識或技能了嗎?如果還想學(xué)到更多技能或者豐富自己的知識儲備,歡迎關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道。