PyBrain - 连接

连接的工作方式与层类似;唯一的区别是它将数据从网络中的一个节点转移到另一个节点。

在本章中,我们将学习 −

  • 了解连接
  • 创建连接

了解连接

以下是创建网络时使用的连接的工作示例。

示例

ffy.py

from pybrain.structure import FeedForwardNetwork
from pybrain.structure import LinearLayer, SigmoidLayer
from pybrain.structure import FullConnection

network = FeedForwardNetwork()

#为输入 => 2 、隐藏 => 3 和输出 =>1 创建层
inputLayer = LinearLayer(2)
hiddenLayer = SigmoidLayer(3)
outputLayer = LinearLayer(1)

#将层添加到前馈网络
network.addInputModule(inputLayer)
network.addModule(hiddenLayer)
network.addOutputModule(outputLayer)

#在输入、隐藏和输出之间创建连接
input_to_hidden = FullConnection(inputLayer, hiddenLayer)
hidden_​​to_output = FullConnection(hiddenLayer, outputLayer)

#将连接添加到网络
network.addConnection(input_to_hidden)
network.addConnection(hidden_to_output)
network.sortModules()

print(network)

输出

C:\pybrain\pybrain\src>python ffn.py
FeedForwardNetwork-6
Modules:
[<LinearLayer 'LinearLayer-3'>, <SigmoidLayer 'SigmoidLayer-7'>, 
   <LinearLayer 'LinearLayer-8'>]
Connections:
[<FullConnection 'FullConnection-4': 'SigmoidLayer-7' -> 'LinearLayer-8'>, 
   <FullConnection 'FullConnection-5': 'LinearLayer-3' -> 'SigmoidLayer-7'>]

创建连接

在 Pybrain 中,我们可以使用连接模块创建连接,如下所示 −

示例

connect.py

from pybrain.structure.connections.connection import Connection
class YourConnection(Connection):
   def __init__(self, *args, **kwargs):
      Connection.__init__(self, *args, **kwargs)
   def _forwardImplementation(self, inbuf, outbuf):
      outbuf += inbuf
   def _backwardImplementation(self, outerr, inerr, inbuf):
      inerr += outer

要创建连接,有两种方法 - _forwardImplementation()_backwardImplementation()

使用传入模块的输出缓冲区 inbuf 和传出模块的输入缓冲区 outbuf 调用 _forwardImplementation()。将 inbuf 添加到传出模块 outbuf

使用 outerrinerrinbuf 调用 _backwardImplementation()。传出模块错误被添加到 _backwardImplementation() 中的传入模块错误中。

现在让我们在网络中使用 YourConnection

testconnection.py

from pybrain.structure import FeedForwardNetwork
from pybrain.structure import LinearLayer, SigmoidLayer
from connect import YourConnection

network = FeedForwardNetwork()

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

#将层添加到前馈网络
network.addInputModule(inputLayer)
network.addModule(hiddenLayer)
network.addOutputModule(outputLayer)

#在输入、隐藏和输出之间创建连接
input_to_hidden = YourConnection(inputLayer, hiddenLayer)
hidden_​​to_output = YourConnection(hiddenLayer, outputLayer)

#将连接添加到网络
network.addConnection(input_to_hidden)
network.addConnection(hidden_to_output)
network.sortModules()

print(network)

输出

C:\pybrain\pybrain\src>python testconnection.py
FeedForwardNetwork-6
Modules:
[<LinearLayer 'LinearLayer-3'>, <SigmoidLayer 'SigmoidLayer-7'>, 
   <LinearLayer 'LinearLayer-8'>]
Connections:
[<YourConnection 'YourConnection-4': 'LinearLayer-3' -> 'SigmoidLayer-7'>, 
   <YourConnection 'YourConnection-5': 'SigmoidLayer-7' -> 'LinearLayer-8'>]