本文實例為大家分享了Python實現(xiàn)感知器模型、兩層神經(jīng)網(wǎng)絡(luò),供大家參考,具體內(nèi)容如下
python 3.4 因為使用了 numpy
這里我們首先實現(xiàn)一個感知器模型來實現(xiàn)下面的對應(yīng)關(guān)系
[[0,0,1], ——- 0
[0,1,1], ——- 1
[1,0,1], ——- 0
[1,1,1]] ——- 1
從上面的數(shù)據(jù)可以看出:輸入是三通道,輸出是單通道。
這里的激活函數(shù)我們使用 sigmoid 函數(shù) f(x)=1/(1+exp(-x))
其導(dǎo)數(shù)推導(dǎo)如下所示:
L0=W*X;
z=f(L0);
error=y-z;
delta =error * f'(L0) * X;
W=W+delta;
python 代碼如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
|
import numpy as np #sigmoid function def nonlin(x, deriv = False ): if (deriv = = True ): return x * ( 1 - x) return 1 / ( 1 + np.exp( - x)) # input dataset X = np.array([[ 0 , 0 , 1 ], [ 0 , 1 , 1 ], [ 1 , 0 , 1 ], [ 1 , 1 , 1 ]]) # output dataset y = np.array([[ 0 , 1 , 0 , 1 ]]).T #seed( ) 用于指定隨機數(shù)生成時所用算法開始的整數(shù)值, #如果使用相同的seed( )值,則每次生成的隨即數(shù)都相同, #如果不設(shè)置這個值,則系統(tǒng)根據(jù)時間來自己選擇這個值, #此時每次生成的隨機數(shù)因時間差異而不同。 np.random.seed( 1 ) # init weight value with mean 0 syn0 = 2 * np.random.random(( 3 , 1 )) - 1 for iter in range ( 1000 ): # forward propagation L0 = X L1 = nonlin(np.dot(L0,syn0)) # error L1_error = y - L1 L1_delta = L1_error * nonlin(L1, True ) # updata weight syn0 + = np.dot(L0.T,L1_delta) print ( "Output After Training:" ) print (L1) |
從輸出結(jié)果可以看出基本實現(xiàn)了對應(yīng)關(guān)系。
下面再用兩層網(wǎng)絡(luò)來實現(xiàn)上面的任務(wù),這里加了一個隱層,隱層包含4個神經(jīng)元。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
|
import numpy as np def nonlin(x, deriv = False ): if (deriv = = True ): return x * ( 1 - x) else : return 1 / ( 1 + np.exp( - x)) #input dataset X = np.array([[ 0 , 0 , 1 ], [ 0 , 1 , 1 ], [ 1 , 0 , 1 ], [ 1 , 1 , 1 ]]) #output dataset y = np.array([[ 0 , 1 , 1 , 0 ]]).T #the first-hidden layer weight value syn0 = 2 * np.random.random(( 3 , 4 )) - 1 #the hidden-output layer weight value syn1 = 2 * np.random.random(( 4 , 1 )) - 1 for j in range ( 60000 ): l0 = X #the first layer,and the input layer l1 = nonlin(np.dot(l0,syn0)) #the second layer,and the hidden layer l2 = nonlin(np.dot(l1,syn1)) #the third layer,and the output layer l2_error = y - l2 #the hidden-output layer error if (j % 10000 ) = = 0 : print "Error:" + str (np.mean(l2_error)) l2_delta = l2_error * nonlin(l2,deriv = True ) l1_error = l2_delta.dot(syn1.T) #the first-hidden layer error l1_delta = l1_error * nonlin(l1,deriv = True ) syn1 + = l1.T.dot(l2_delta) syn0 + = l0.T.dot(l1_delta) print "outout after Training:" print l2 |
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持服務(wù)器之家。
原文鏈接:http://blog.csdn.net/zhangjunhit/article/details/53487109