您好,登錄后才能下訂單哦!
python怎樣搭建多層神經網絡?這個問題可能是我們日常工作經常見到的。通過這個問題,希望你能收獲更多。下面是解決這個問題的步驟內容。
模型的搭建按照自己的想法設計,源碼共7個.py文件,如下圖:
按照創建先后順序,分別是:data.py,layer.py,network.py,activation.py,loss.py,train.py,evaluate.py。data.py用于獲取數據并對數據進行預處理,layer.py創建了一個Layer類,用來表示第L層,network.py抽象了一個網絡類,將傳入的若干層通過計算輸入輸出連接起來,組成一個網絡,data.py用來讀取數據,loss.py明確了交叉熵損失函數和其導數,activation.py分別寫了激活函數relu和sigmoid以及其導函數,train.py創建了層次并組成網絡,然后對數據進行訓練并保存模型,最后evaluate.py用于對測試集進行測試。
網絡分為2大塊,正向傳播和反向傳播:
但是不管是正向還是反向,網絡中的每一層都可以抽象出來,因此創建一個layer類:
正向傳播的L層:
反向傳播的L層:
在寫代碼之前,最重要的是確定每個變量和參數的維度:
正向傳播:
注意:n[L]表示當前層(即第L層)中的神經元個數,n[L-1]表示前一層(即L-1層)的神經元個數,例如在本次程序中,n[0]=12288,n[1]=1000,n[2]=500,n[3]=1
反向傳播:
1. data.py
# coding: utf-8
# 2019/7/20 18:59
import h6py
import numpy as np
def get_train():
f = h6py.File('dataset/train_catvnoncat.h6','r')
x_train = np.array(f['train_set_x'])#訓練集數據 將數據轉化為np.array
y_train = np.array(f['train_set_y'])#訓練集標簽
return x_train,y_train
def get_test():
f = h6py.File('dataset/test_catvnoncat.h6', 'r')
x_test = np.array(f['test_set_x'])#測試集數據 將數據轉化為np.array
y_test = np.array(f['test_set_y'])#測試集標簽
return x_test,y_test
def preprocess(X):
#將X標準化,從0-255變成0-1
# X =X / 255
#將數據從(m,64,64,3)變成(m,12288)
X = X.reshape([X.shape[0], X.shape[1]*X.shape[2]*X.shape[3]]).T
return X
if __name__ == '__main__':
x1,y1 = get_train()
x2,y2 = get_test()
print(x1.shape,y1.shape)
print(x2.shape,y2.shape)
from matplotlib import pyplot as plt
plt.figure()
for i in range(1,16):
plt.subplot(3,5,i)
plt.imshow(x1[i])
print(y1[i])
plt.show()
2. layer.py
# coding: utf-8
# 2019/7/21 9:22
import numpy as np
class Layer:
def __init__(self,nL,nL_1,activ,activ_deri, learning_rate):
#參數分別表示:當前層神經元個數,前一層神經元個數,激活函數,激活函數的導函數,學習率
self.nL = nL
self.nL_1 = nL_1
self.g = activ
self.g_d = activ_deri
self.alpha = learning_rate
self.W = np.random.randn(nL,nL_1)*0.01
self.b = np.random.randn(nL,1)*0.01
#正向傳播:
#1、計算Z=WX+b
#2、計算A=g(Z)
def forward(self,AL_1):
self.AL_1 = AL_1
assert (AL_1.shape[0] == self.nL_1)
self.Z = np.dot(self.W,AL_1)+self.b
assert (self.Z.shape[0] == self.nL)
AL = self.g(self.Z)
return AL
#反向傳播:
#1、m表示樣本個數
#2、計算dZ,dW,db,dAL_1
#3、梯度下降,更新W和b
def backward(self,dAL):
assert (dAL.shape[0] == self.nL)
m = dAL.shape[1]
dZ = np.multiply(dAL,self.g_d(self.Z))
assert (dZ.shape[0] == self.nL)
dW = np.dot(dZ,self.AL_1.T)/m
assert (dW.shape == (self.nL,self.nL_1))
db = np.mean(dZ,axis=1,keepdims=True)
assert (db.shape == (self.nL,1))
dAL_1 = np.dot(self.W.T,dZ)
assert (dAL_1.shape[0] == self.nL_1)
#梯度下降
self.W -= self.alpha*dW
self.b -= self.alpha*db
return dAL_1
3. network.py
# coding: utf-8
# 2019/7/21 10:45
import numpy as np
class Network:
def __init__(self,layers,loss,loss_der):
self.layers = layers
self.loss = loss
self.loss_der = loss_der
#根據輸入的數據來調用正向傳播函數,不斷更新A,最后得到預測結果
def predict(self,X):
A = X
for layer in self.layers:
A = layer.forward(A)
return A
#連接每個層組建網絡:
#1、根據輸入的數據進行正向傳播,得到預測結果Y_predict
#2、根據Y_predict和真實值Y,通過損失函數來計算成本值J
#3、根據J來計算反向傳播的輸入值dA
#4、調用反向傳播函數來更新dA
def train(self,X,Y,epochs=10):
for i in range(epochs):
Y_predict = self.predict(X)
J = np.mean(self.loss(Y, Y_predict))
print('epoch %d:loss=%f'%(i,J))
dA = self.loss_der(Y,Y_predict)
for layer in reversed(self.layers):
#更新dA
dA= layer.backward(dA)
4. loss.py
# coding: utf-8
# 2019/7/21 11:34
import numpy as np
#交叉熵損失函數
def cross_entropy(y, y_predict):
y_predict = np.clip(y_predict,1e-10,1-1e-10) #防止0*log(0)出現。導致計算結果變為NaN
return -(y * np.log(y_predict) + (1 - y) * np.log(1 - y_predict))
#交叉熵損失函數的導函數
def cross_entropy_der(y,y_predict):
return -y/y_predict+(1-y)/(1-y_predict)
5. activation.py
# coding: utf-8
# 2019/7/21 9:49
import numpy as np
def sigmoid(z):
return 1 / (1 + np.exp(-z))
#sigmoid導函數
def sigmoid_der(z):
x = np.exp(-z)
return x/((1+x)**2)
def relu(z):無錫婦科醫院 http://www.xasgyy.net/
return np.maximum(0,z)
#relu導函數
def relu_der(z):
return (z>=0).astype(np.float64)
6. train.py
# coding: utf-8
# 2019/7/21 12:13
import data,layer,loss,network,activation
import pickle,time
#對數據集進行訓練并保存模型
#1、搭建3層網絡層
#2、將3個層組建成網絡
#3、獲取訓練集數據
#4、對輸入值X進行預處理
#5、將數據輸入網絡進行訓練,epochs為1000
#6、將整個模型保存
if __name__ == '__main__':
learning_rate = 0.01
L1 = layer.Layer(1000,64*64*3, activation.relu, activation.relu_der, learning_rate)
L2 = layer.Layer(500,1000,activation.relu, activation.relu_der, learning_rate)
L3 = layer.Layer(1,500, activation.sigmoid, activation.sigmoid_der, learning_rate)
net = network.Network([L1,L2,L3], loss.cross_entropy, loss.cross_entropy_der)
X,Y = data.get_train()
X = data.preprocess(X)
net.train(X,Y,1000)
with open('models/model_%s.pickle'%(time.asctime().replace(':','_').replace(' ','-')),'wb') as f:
pickle.dump(net,f)
7. evaluate.py
# coding: utf-8
# 2019/7/21 14:17
import data
import pickle
import numpy as np
if __name__ == '__main__':
model_name = 'model_Sun-Jul-21-14_41_42-2019.pickle'
#導入模型
with open('models/'+model_name,'rb') as f:
net = pickle.load(f)
#獲取測試數據集
X,Y = data.get_test()
X = data.preprocess(X)
#根據輸入數據X進行預測
Y_predict = net.predict(X)
Y_pred_float = (Y_predict>0.5).astype(np.float64)
#計算精確度
accuracy = np.sum(np.equal(Y_pred_float,Y).astype(np.int))/Y.shape[0]
print('accuracy:',accuracy)
結果
看完上訴內容,你們對python搭建多層神經網絡大概了解了嗎?如果想了解更多相關文章內容,歡迎關注億速云行業資訊頻道,感謝各位的閱讀!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。