6.3神經網絡實例1--python機器學習

參考彭亮老師的視頻教程:轉載請註明出處及彭亮老師原創
視頻教程: http://pan.baidu.com/s/1kVNe5EJ


1. 簡單非線性關係數據集測試(XOR):

X:                  Y
0 0                 0
0 1                 1
1 0                 1
1 1                 0



Code:

from NeuralNetwork import NeuralNetwork
import numpy as np

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))

2. 手寫數字識別:

每個圖片8x8 
識別數字:0,1,2,3,4,5,6,7,8,9


Code:

import numpy as np 
from sklearn.datasets import load_digits 
from sklearn.metrics import confusion_matrix, classification_report 
from sklearn.preprocessing import LabelBinarizer 
from NeuralNetwork import NeuralNetwork
from sklearn.cross_validation import train_test_split


digits = load_digits()  
X = digits.data  
y = digits.target  
X -= X.min() # normalize the values to bring them into the range 0-1  
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)




發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章