PyBrain - 迴圈網路操作



迴圈網路與前饋網路相同,僅有的區別是你需要記住每個步驟的資料。必須儲存每個步驟的歷史記錄。

我們將學習如何:

  • 建立迴圈網路
  • 新增模組和連線

建立迴圈網路

要建立迴圈網路,我們將使用 RecurrentNetwork 類,如下所示:

rn.py

from pybrain.structure import RecurrentNetwork
recurrentn = RecurrentNetwork()
print(recurrentn)

python rn.py

C:\pybrain\pybrain\src>python rn.py
RecurrentNetwork-0
Modules:
[]
Connections:
[]
Recurrent Connections:
[]

我們可以看到針對迴圈網路的新連線,稱為迴圈連線。現在沒有可用資料。

現在,讓我們建立層並將其新增到模組並建立連線。

新增模組和連線

我們將建立層,即輸入、隱藏和輸出。這些層將被新增到輸入和輸出模組。接下來,我們將建立用於輸入到隱藏、隱藏到輸出的連線,以及用於隱藏到隱藏的迴圈連線。

以下是具有模組和連線的迴圈網路的程式碼。

rn.py

from pybrain.structure import RecurrentNetwork
from pybrain.structure import LinearLayer, SigmoidLayer
from pybrain.structure import FullConnection
recurrentn = RecurrentNetwork()

#creating layer for input => 2 , hidden=> 3 and output=>1
inputLayer = LinearLayer(2, 'rn_in')
hiddenLayer = SigmoidLayer(3, 'rn_hidden')
outputLayer = LinearLayer(1, 'rn_output')

#adding the layer to feedforward network
recurrentn.addInputModule(inputLayer)
recurrentn.addModule(hiddenLayer)
recurrentn.addOutputModule(outputLayer)

#Create connection between input ,hidden and output
input_to_hidden = FullConnection(inputLayer, hiddenLayer)
hidden_to_output = FullConnection(hiddenLayer, outputLayer)
hidden_to_hidden = FullConnection(hiddenLayer, hiddenLayer)

#add connection to the network
recurrentn.addConnection(input_to_hidden)
recurrentn.addConnection(hidden_to_output)
recurrentn.addRecurrentConnection(hidden_to_hidden)
recurrentn.sortModules()

print(recurrentn)

python rn.py

C:\pybrain\pybrain\src>python rn.py
RecurrentNetwork-6
Modules:
[<LinearLayer 'rn_in'>, <SigmoidLayer 'rn_hidden'>, 
   <LinearLayer 'rn_output'>]
Connections:
[<FullConnection 'FullConnection-4': 'rn_hidden' -> 'rn_output'>, 
   <FullConnection 'FullConnection-5': 'rn_in' -> 'rn_hidden'>]
Recurrent Connections:
[<FullConnection 'FullConnection-3': 'rn_hidden' -> 'rn_hidden'>]

在上面的輸出中,我們可以看到模組、連線和迴圈連線。

現在,讓我們使用啟用方法(如以下所示)來啟用網路:

rn.py

將以下程式碼新增到之前建立的程式碼:

#activate network using activate() method
act1 = recurrentn.activate((2, 2))
print(act1)

act2 = recurrentn.activate((2, 2))
print(act2)

python rn.py

C:\pybrain\pybrain\src>python rn.py
[-1.24317586]
[-0.54117783]
廣告