使用Python scikit-learn 庫實現神經網路演算法

來源:互聯網
上載者:User

標籤:normal   自己實現   png   (())   集中   資料集   sdn   shape   second   

1:神經網路演算法簡介

2:Backpropagation演算法詳細介紹

3:非線性轉化方程舉例

4:自己實現神經網路演算法NeuralNetwork

5:基於NeuralNetwork的XOR執行個體

6:基於NeuralNetwork的手寫數字識別執行個體

7:scikit-learn中BernoulliRBM使用執行個體

8:scikit-learn中的手寫數字識別執行個體

 

一:神經網路演算法簡介1:背景

以人腦神經網路為啟發,曆史上出現過很多版本,但最著名的是backpropagation

2:多層向前神經網路(Multilayer  Feed-Forward Neural Network)

                                                          

多層向前神經網路組成部分

輸入層(input layer),隱藏層(hiddenlayer),輸出層(output layer)

 

   每層由單元(units)組成   輸入層(input layer)是由訓練集的執行個體特徵向量傳入   經過串連結點的權重(weight)傳入下一層,一層的輸出是下一層的輸入   隱藏層的個數是任意的,輸出層和輸入層只有一個   每個單元(unit)也可以被稱作神經結點,根據生物學來源定義   稱為2層的神經網路(輸入層不算)   一層中加權的求和,然後根據非線性方程轉化輸出   作為多層向前神經網路,理論上,如果有足夠多的隱藏層(hidden layers)和足夠大的訓練集,可以類比出任何方程 3:設計神經網路結構    3.1使用神經網路訓練資料之前,必須確定神經網路層數,以及每層單元個數    3.2特徵向量在被傳入輸入層時通常被先標準化(normalize)和0和1之間(為了加強學習過程)    3.3離散型變數可以被編碼成每一個輸入單元對應一個特徵可能賦的值        比如:特徵值A可能取三個值(a0,a1,a2),可以使用三個輸入單元來代表A                    如果A=a0,那麼代表a0的單元值就取1,其他取0                    如果A=a1,那麼代表a1的單元值就取1,其他取0,以此類推    3.4神經網路即可以用來做分類(classification)問題,也可以解決迴歸(regression)問題         3.4.1對於分類問題,如果是2類,可以用一個輸入單元表示(0和1分別代表2類)                                         如果多於兩類,每一個類別用一個輸出單元表示                所以輸入層的單元數量通常等於類別的數量         3.4.2沒有明確的規則來設計最好有多少個隱藏層               3.4.2.1根據實驗測試和誤差,以及準確度來實驗並改進4:演算法驗證——交叉驗證法(Cross- Validation) 

解讀: 有一組輸入集A,B,可以分成三組,第一次以第一組為訓練集,求出一個準確度,第二次以第二組作為訓練集,求出一個準確度,求出準確度,第三次以第三組作為訓練集,求出一個準確度,然後對三個準確度求平均值


二:Backpropagation演算法詳細介紹

                                                            


1:通過迭代性來處理訓練集中的執行個體

 

2:輸入層輸入數

           經過權重計算得到第一層的資料,第一層的資料作為第二層的輸入,再次經過權重計算得到結果,結果和真實值之間是存在誤差的,然後根據誤差,反向的更新每兩個串連之間的權重

3:演算法詳細介紹

      輸入:D : 資料集,| 學習率(learning rate),一個多層前向神經網路

    輸出:一個訓練好的神經網路(a trained neural network)    3.1初始化權重(weights)和偏向(bias):隨機初始化在-1到1之間,或者-0.5到0.5之間,每個單元有一個偏向    3.2對於每一個訓練執行個體X,執行以下步驟:         3.2.1:由輸入層向前傳送,輸入->輸出對應的計算為:                                                                                          計算得到一個資料,經過f 函數轉化作為下一層的輸入,f函數為:          3.2.2:根據誤差(error)反向傳送                     對於輸出層(誤差計算):  Tj:真實值,Qj表示預測值                      對於隱藏層(誤差計算):  Errk 表示前一層的誤差, Wjk表示前一層與當前點的串連權重                                            權重更新:  l:指學習比率(變動率),手工指定,最佳化方法是,隨著資料的迭代逐漸減小                      偏向更新:  l:同上       3.3:終止條件           3.3.1權重的更新低於某個閥值           3.3.2預測的錯誤率低於某個閥值           3.3.3達到預設一定的迴圈次數

 

 

4:結合執行個體講解演算法

                                                                  

                                                                  

                                                                

              0.9對用的是L,學習率

 

測試代碼如下:

1.NeutralNetwork.py檔案代碼

#coding:utf-8

import numpy as np

#定義雙曲函數和他們的導數
def tanh(x):
return np.tanh(x)

def tanh_deriv(x):
return 1.0 - np.tanh(x)**2

def logistic(x):
return 1/(1 + np.exp(-x))

def logistic_derivative(x):
return logistic(x)*(1-logistic(x))

#定義NeuralNetwork 神經網路演算法
class NeuralNetwork:
#初始化,layes表示的是一個list,eg[10,10,3]表示第一層10個神經元,第二層10個神經元,第三層3個神經元
def __init__(self, layers, activation=‘tanh‘):
"""
:param layers: A list containing the number of units in each layer.
Should be at least two values
:param activation: The activation function to be used. Can be
"logistic" or "tanh"
"""
if activation == ‘logistic‘:
self.activation = logistic
self.activation_deriv = logistic_derivative
elif activation == ‘tanh‘:
self.activation = tanh
self.activation_deriv = tanh_deriv

self.weights = []
#迴圈從1開始,相當於以第二層為基準,進行權重的初始化
for i in range(1, len(layers) - 1):
#對當前神經節點的前驅賦值
self.weights.append((2*np.random.random((layers[i - 1] + 1, layers[i] + 1))-1)*0.25)
#對當前神經節點的後繼賦值
self.weights.append((2*np.random.random((layers[i] + 1, layers[i + 1]))-1)*0.25)

#訓練函數 ,X矩陣,每行是一個執行個體 ,y是每個執行個體對應的結果,learning_rate 學習率,
# epochs,表示抽樣的方法對神經網路進行更新的最大次數
def fit(self, X, y, learning_rate=0.2, epochs=10000):
X = np.atleast_2d(X) #確定X至少是二維的資料
temp = np.ones([X.shape[0], X.shape[1]+1]) #初始化矩陣
temp[:, 0:-1] = X # adding the bias unit to the input layer
X = temp
y = np.array(y) #把list轉換成array的形式

for k in range(epochs):
#隨機選取一行,對神經網路進行更新
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])]

#開始反向計算誤差,更新權重
for l in range(len(a) - 2, 0, -1): # we need to begin at the second to last layer
deltas.append(deltas[-1].dot(self.weights[l].T)*self.activation_deriv(a[l]))
deltas.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)

#預測函數
def predict(self, x):
x = np.array(x)
temp = np.ones(x.shape[0]+1)
temp[0:-1] = x
a = temp
for l in range(0, len(self.weights)):
a = self.activation(np.dot(a, self.weights[l]))
return a

2、測試代碼


#coding:utf-8
‘‘‘
#基於NeuralNetwork的XOR(異或)樣本
import numpy as np
from NeuralNetwork import NeuralNetwork

nn = NeuralNetwork([2,2,1], ‘tanh‘)
X = np.array([[0, 0], [0, 1], [1, 0], [1, 1]])
y = np.array([0, 1, 1, 0])
nn.fit(X, y)
for i in [[0, 0], [0, 1], [1, 0], [1,1]]:
print(i,nn.predict(i))
‘‘‘
‘‘‘
#基於NeuralNetwork的手寫數字識別樣本
import numpy as np
from sklearn.datasets import load_digits
from sklearn.metrics import confusion_matrix,classification_report
from sklearn.preprocessing import LabelBinarizer
from sklearn.cross_validation import train_test_split
from NeuralNetwork import NeuralNetwork

digits = load_digits()
X = digits.data
y = digits.target
X -= X.min()
X /= X.max()

nn =NeuralNetwork([64,100,10],‘logistic‘)
X_train, X_test, y_train, y_test = train_test_split(X, y)
labels_train = LabelBinarizer().fit_transform(y_train)
labels_test = LabelBinarizer().fit_transform(y_test)
print "start fitting"
nn.fit(X_train,labels_train,epochs=3000)
predictions = []
for i in range(X_test.shape[0]):
o = nn.predict(X_test[i])
predictions.append(np.argmax(o))
print confusion_matrix(y_test, predictions)
print classification_report(y_test, predictions)
‘‘‘

#scikit-learn中的手寫數字識別執行個體
import numpy as np
import matplotlib.pyplot as plt

from scipy.ndimage import convolve
from sklearn import linear_model, datasets, metrics
from sklearn.cross_validation import train_test_split
from sklearn.neural_network import BernoulliRBM
from sklearn.pipeline import Pipeline


###############################################################################
# Setting up

def nudge_dataset(X, Y):

direction_vectors = [
[[0, 1, 0],
[0, 0, 0],
[0, 0, 0]],

[[0, 0, 0],
[1, 0, 0],
[0, 0, 0]],

[[0, 0, 0],
[0, 0, 1],
[0, 0, 0]],

[[0, 0, 0],
[0, 0, 0],
[0, 1, 0]]]

shift = lambda x, w: convolve(x.reshape((8, 8)), mode=‘constant‘,
weights=w).ravel()
X = np.concatenate([X] +
[np.apply_along_axis(shift, 1, X, vector)
for vector in direction_vectors])
Y = np.concatenate([Y for _ in range(5)], axis=0)
return X, Y

# Load Data
digits = datasets.load_digits()
X = np.asarray(digits.data, ‘float32‘)
X, Y = nudge_dataset(X, digits.target)
X = (X - np.min(X, 0)) / (np.max(X, 0) + 0.0001) # 0-1 scaling

X_train, X_test, Y_train, Y_test = train_test_split(X, Y,
test_size=0.2,
random_state=0)

# Models we will use
logistic = linear_model.LogisticRegression()
rbm = BernoulliRBM(random_state=0, verbose=True)

classifier = Pipeline(steps=[(‘rbm‘, rbm), (‘logistic‘, logistic)])

###############################################################################
# Training

# Hyper-parameters. These were set by cross-validation,
# using a GridSearchCV. Here we are not performing cross-validation to
# save time.
rbm.learning_rate = 0.06
rbm.n_iter = 20
# More components tend to give better prediction performance, but larger
# fitting time
rbm.n_components = 100
logistic.C = 6000.0

# Training RBM-Logistic Pipeline
classifier.fit(X_train, Y_train)

# Training Logistic regression
logistic_classifier = linear_model.LogisticRegression(C=100.0)
logistic_classifier.fit(X_train, Y_train)

###############################################################################
# Evaluation

print()
print("Logistic regression using RBM features:\n%s\n" % (
metrics.classification_report(
Y_test,
classifier.predict(X_test))))

print("Logistic regression using raw pixel features:\n%s\n" % (
metrics.classification_report(
Y_test,
logistic_classifier.predict(X_test))))

###############################################################################
# Plotting

plt.figure(figsize=(4.2, 4))
for i, comp in enumerate(rbm.components_):
plt.subplot(10, 10, i + 1)
plt.imshow(comp.reshape((8, 8)), cmap=plt.cm.gray_r,
interpolation=‘nearest‘)
plt.xticks(())
plt.yticks(())
plt.suptitle(‘100 components extracted by RBM‘, fontsize=16)
plt.subplots_adjust(0.08, 0.02, 0.92, 0.85, 0.08, 0.23)

plt.show()


‘‘‘
from sklearn.neural_network import BernoulliRBM
X = [[0,0],[1,1]]
y = [0,1]
clf = BernoulliRBM().fit(X,y)
print

測試結果如下:

 

使用Python scikit-learn 庫實現神經網路演算法

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.