怎樣用Python實現兩層神經網路和感知器模型

來源:互聯網
上載者:User
本文給大家分享怎樣用Python實現兩層神經網路和感知器模型,具體內容和例子如下所示,可供大家參考

python 3.4 因為使用了 numpy

這裡我們首先實現一個感知器模型來實現下面的對應關係

[[0,0,1], ——- 0  [0,1,1], ——- 1  [1,0,1], ——- 0  [1,1,1]] ——- 1

從上面的資料可以看出:輸入是三通道,輸出是單通道。


這裡的啟用函數我們使用 sigmoid 函數 f(x)=1/(1+exp(-x))

其導數推導如下所示:

L0=W*X; z=f(L0); error=y-z; delta =error * f'(L0) * X; W=W+delta;

python 代碼如下:

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( ) 用於指定隨機數產生時所用演算法開始的整數值,#如果使用相同的seed( )值,則每次產生的隨即數都相同,#如果不設定這個值,則系統根據時間來自己選擇這個值,#此時每次產生的隨機數因時間差異而不同。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)


從輸出結果可以看出基本實現了對應關係。

下面再用兩層網路來實現上面的任務,這裡加了一個隱層,隱層包含4個神經元。


   import numpy as np def nonlin(x, deriv = False):  if(deriv == True):    return x*(1-x)  else:    return 1/(1+np.exp(-x)) #input datasetX = np.array([[0,0,1],       [0,1,1],       [1,0,1],       [1,1,1]]) #output datasety = np.array([[0,1,1,0]]).T #the first-hidden layer weight valuesyn0 = 2*np.random.random((3,4)) - 1 #the hidden-output layer weight valuesyn1 = 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


相信看了這些案例你已經掌握了方法,更多精彩請關注php中文網其它相關文章!

相關閱讀:

php如何?棧資料結構以及括弧匹配演算法的程式碼範例詳解

php中最簡單的字串匹配演算法,php匹配演算法_PHP教程

最簡單的php中字串匹配演算法教程

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.