您好,登錄后才能下訂單哦!
本篇文章為大家展示了使用Python怎么實(shí)現(xiàn)一個(gè)NN神經(jīng)網(wǎng)絡(luò)算法,內(nèi)容簡(jiǎn)明扼要并且容易理解,絕對(duì)能使你眼前一亮,通過(guò)這篇文章的詳細(xì)介紹希望你能有所收獲。
運(yùn)行環(huán)境
Pyhton3
numpy(科學(xué)計(jì)算包)
matplotlib(畫圖所需,不畫圖可不必)
sklearn(人工智能包,生成數(shù)據(jù)使用)
計(jì)算過(guò)程
輸入樣例
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ù)集, 對(duì)應(yīng)的類別標(biāo)簽 描述:生成一個(gè)數(shù)據(jù)集和對(duì)應(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ù)最小最大值和一個(gè)網(wǎng)格距離生成整個(gè)網(wǎng)格 xx, yy = np.meshgrid(np.arange(x_min, x_max, h), np.arange(y_min, y_max, h)) # 對(duì)整個(gè)網(wǎng)格預(yù)測(cè)邊界值 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ì)算整個(gè)模型的性能 """ W1, b1, W2, b2 = model['W1'], model['b1'], model['W2'], model['b2'] # 正向傳播來(lái)計(jì)算預(yù)測(cè)的分類值 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)修正錯(cuò)誤(可選) 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ù)測(cè)向量 輸出:判決類別 描述:預(yù)測(cè)類別屬于(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ù)! 這里需要手動(dòng)設(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í)步長(zhǎng) 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ò)模型 描述:生成一個(gè)指定層數(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)一個(gè)NN神經(jīng)網(wǎng)絡(luò)算法,你們學(xué)到知識(shí)或技能了嗎?如果還想學(xué)到更多技能或者豐富自己的知識(shí)儲(chǔ)備,歡迎關(guān)注億速云行業(yè)資訊頻道。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。