深度学习-机器学习(神经网络的应用 上)
生活随笔
收集整理的這篇文章主要介紹了
深度学习-机器学习(神经网络的应用 上)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
1.用Python來實現神經網絡:
? ? ????????????????????????????????????************具體直接看代碼****************
#神經網絡算法(Neural Network) import numpy as npdef tanh(x): #雙曲函數return np.tanh(x)def tanh_deriv(x): #雙曲函數的導數return 1.0 - np.tanh(x)*np.tanh(x)def logistic(x): #邏輯函數return 1/(1 + np.exp(-x))def logistic_derivative(x): #邏輯函數的導數return logistic(x)*(1-logistic(x))class NeuralNetwork: #定義一個神經網絡的類def __init__(self, layers, activation='tanh'):#不指名activation=是默認為'tanh'"""layers:(list)每層里面以后多少個神經元,幾個數字就對應幾層,每個數字的值就對應有多少個神經元,最少要有兩層self相當于java中的thisactivation-->>激活函數"""if activation == 'logistic':self.activation = logistic #給邏輯函數取名為logisticself.activation_deriv = logistic_derivative #給邏輯函數的導數取名為logisticelif activation == 'tanh':self.activation = tanh #給雙曲函數取名為tanhself.activation_deriv = tanh_deriv #給雙曲函數的導數取名為tanh_derivself.weights = [] #定義一個空的權重list#初始化權重的賦值for i in range(1, len(layers) - 1):"""隨機產生權重 從第二層i開始:對i層的上一層(i-1)和i層的下一層(i+1),進行賦值"""#i層和i-1層的隨機賦值self.weights.append((2 * np.random.random((layers[i - 1] + 1, layers[i] + 1)) - 1) * 0.25)#i層和i+1層的隨機賦值self.weights.append((2 * np.random.random((layers[i] + 1, layers[i + 1])) - 1) * 0.25)def fit(self, X, y, learning_rate=0.2, epochs=10000): #learning_rate學習率,epochs=10000:循環的次數X = np.atleast_2d(X)#X為訓練集,通常為二維的矩陣。temp = np.ones([X.shape[0], X.shape[1]+1]) #對偏向的初始化(X.shape[0]為行數,X.shape[1]為列數)temp[:, 0:-1] = X #(:意思是取所有的行)X = tempy = np.array(y)for k in range(epochs): #epochs=10000循環的次數i = np.random.randint(X.shape[0])a = [X[i]] #隨機抽取一個數for l in range(len(self.weights)): #完成正向的所有更新a.append(self.activation(np.dot(a[l], self.weights[l]))) #對應相乘然后相加error = y[i] - a[-1] # 實際的值減去預測的值deltas = [error * self.activation_deriv(a[-1])] # 根據與輸出層算出的誤差,反向更新# Staring backprobagationfor l in range(len(a) - 2, 0, -1): # 我們需要從第二層開始到最后一層deltas.append(deltas[-1].dot(self.weights[l].T) * self.activation_deriv(a[l]))#更新隱藏層Errordeltas.reverse() #顛倒順序for i in range(len(self.weights)):layer = np.atleast_2d(a[i])delta = np.atleast_2d(deltas[i])self.weights[i] += learning_rate * layer.T.dot(delta) #權重更新(算法在CSDN上:神經網絡算法1)2 . 下一節? 本節訓練好的神經網絡該怎么用?
????? ??
總結
以上是生活随笔為你收集整理的深度学习-机器学习(神经网络的应用 上)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 深度学习-机器学习(神经网络 1)
- 下一篇: 深度学习—机器学习(神经网络2)