PyBrain - Strati

I livelli sono fondamentalmente un insieme di funzioni che vengono utilizzate sui livelli nascosti di una rete.

In questo capitolo esamineremo i seguenti dettagli sui livelli:

  • Capire lo strato
  • Creazione di un livello utilizzando Pybrain

Capire i livelli

Abbiamo visto esempi in precedenza in cui abbiamo usato i livelli come segue:

  • TanhLayer
  • SoftmaxLayer

Esempio utilizzando TanhLayer

Di seguito è riportato un esempio in cui abbiamo utilizzato TanhLayer per costruire una rete:

testnetwork.py

from pybrain.tools.shortcuts import buildNetwork
from pybrain.structure import TanhLayer
from pybrain.datasets import SupervisedDataSet
from pybrain.supervised.trainers import BackpropTrainer

# Create a network with two inputs, three hidden, and one output
nn = buildNetwork(2, 3, 1, bias=True, hiddenclass=TanhLayer)

# Create a dataset that matches network input and output sizes:
norgate = SupervisedDataSet(2, 1)

# Create a dataset to be used for testing.
nortrain = SupervisedDataSet(2, 1)

# Add input and target values to dataset
# Values for NOR truth table
norgate.addSample((0, 0), (1,))
norgate.addSample((0, 1), (0,))
norgate.addSample((1, 0), (0,))
norgate.addSample((1, 1), (0,))

# Add input and target values to dataset
# Values for NOR truth table
nortrain.addSample((0, 0), (1,))
nortrain.addSample((0, 1), (0,))
nortrain.addSample((1, 0), (0,))
nortrain.addSample((1, 1), (0,))

#Training the network with dataset norgate.
trainer = BackpropTrainer(nn, norgate)

# will run the loop 1000 times to train it.
for epoch in range(1000):
   trainer.train()
trainer.testOnData(dataset=nortrain, verbose = True)

Produzione

L'output per il codice precedente è il seguente:

python testnetwork.py

C:\pybrain\pybrain\src>python testnetwork.py
Testing on data:
('out: ', '[0.887 ]')
('correct:', '[1 ]')
error: 0.00637334
('out: ', '[0.149 ]')
('correct:', '[0 ]')
error: 0.01110338
('out: ', '[0.102 ]')
('correct:', '[0 ]')
error: 0.00522736
('out: ', '[-0.163]')
('correct:', '[0 ]')
error: 0.01328650
('All errors:', [0.006373344564625953, 0.01110338071737218, 
   0.005227359234093431, 0.01328649974219942])
('Average error:', 0.008997646064572746)
('Max error:', 0.01328649974219942, 'Median error:', 0.01110338071737218)

Esempio di utilizzo di SoftMaxLayer

Di seguito è riportato un esempio in cui abbiamo utilizzato SoftmaxLayer per costruire una rete:

from pybrain.tools.shortcuts import buildNetwork
from pybrain.structure.modules import SoftmaxLayer
from pybrain.datasets import SupervisedDataSet
from pybrain.supervised.trainers import BackpropTrainer

# Create a network with two inputs, three hidden, and one output
nn = buildNetwork(2, 3, 1, bias=True, hiddenclass=SoftmaxLayer)

# Create a dataset that matches network input and output sizes:
norgate = SupervisedDataSet(2, 1)

# Create a dataset to be used for testing.
nortrain = SupervisedDataSet(2, 1)

# Add input and target values to dataset
# Values for NOR truth table
norgate.addSample((0, 0), (1,))
norgate.addSample((0, 1), (0,))
norgate.addSample((1, 0), (0,))
norgate.addSample((1, 1), (0,))

# Add input and target values to dataset
# Values for NOR truth table
nortrain.addSample((0, 0), (1,))
nortrain.addSample((0, 1), (0,))
nortrain.addSample((1, 0), (0,))
nortrain.addSample((1, 1), (0,))

#Training the network with dataset norgate.
trainer = BackpropTrainer(nn, norgate)

# will run the loop 1000 times to train it.
for epoch in range(1000):
trainer.train()
trainer.testOnData(dataset=nortrain, verbose = True)

Produzione

L'output è il seguente:

C:\pybrain\pybrain\src>python example16.py
Testing on data:
('out: ', '[0.918 ]')
('correct:', '[1 ]')
error: 0.00333524
('out: ', '[0.082 ]')
('correct:', '[0 ]')
error: 0.00333484
('out: ', '[0.078 ]')
('correct:', '[0 ]')
error: 0.00303433
('out: ', '[-0.082]')
('correct:', '[0 ]')
error: 0.00340005
('All errors:', [0.0033352368788838365, 0.003334842961037291, 
   0.003034328685718761, 0.0034000458892589056])
('Average error:', 0.0032761136037246985)
('Max error:', 0.0034000458892589056, 'Median error:', 0.0033352368788838365)

Creazione di strati in Pybrain

In Pybrain, puoi creare il tuo livello come segue:

Per creare un livello, devi usare NeuronLayer class come classe base per creare tutti i tipi di livelli.

Esempio

from pybrain.structure.modules.neuronlayer import NeuronLayer
class LinearLayer(NeuronLayer):
   def _forwardImplementation(self, inbuf, outbuf):
      outbuf[:] = inbuf
   def _backwardImplementation(self, outerr, inerr, outbuf, inbuf):
      inerr[:] = outer

Per creare un livello, dobbiamo implementare due metodi: _forwardImplementation () e _backwardImplementation () .

The _forwardImplementation() takes in 2 arguments inbufe outbuf, che sono array di Scipy. La sua dimensione dipende dalle dimensioni di input e output dei livelli.

Il _backwardImplementation () viene utilizzato per calcolare la derivata dell'output rispetto all'input fornito.

Quindi, per implementare un livello in Pybrain, questo è lo scheletro della classe del livello -

from pybrain.structure.modules.neuronlayer import NeuronLayer
class NewLayer(NeuronLayer):
   def _forwardImplementation(self, inbuf, outbuf):
      pass
   def _backwardImplementation(self, outerr, inerr, outbuf, inbuf):
      pass

Nel caso in cui desideri implementare una funzione polinomiale quadratica come livello, possiamo farlo come segue:

Considera di avere una funzione polinomiale come -

f(x) = 3x2

La derivata della funzione polinomiale di cui sopra sarà la seguente:

f(x) = 6 x

La classe del livello finale per la funzione polinomiale di cui sopra sarà la seguente:

testlayer.py

from pybrain.structure.modules.neuronlayer import NeuronLayer
class PolynomialLayer(NeuronLayer):
   def _forwardImplementation(self, inbuf, outbuf):
      outbuf[:] = 3*inbuf**2
   def _backwardImplementation(self, outerr, inerr, outbuf, inbuf):
      inerr[:] = 6*inbuf*outerr

Ora utilizziamo il livello creato come mostrato di seguito:

testlayer1.py

from testlayer import PolynomialLayer
from pybrain.tools.shortcuts import buildNetwork
from pybrain.tests.helpers import gradientCheck

n = buildNetwork(2, 3, 1, hiddenclass=PolynomialLayer)
n.randomize()

gradientCheck(n)

GradientCheck () verificherà se il livello sta funzionando correttamente o no. Abbiamo bisogno di passare la rete in cui il livello è utilizzato per GradientCheck (n). Se il livello funziona correttamente, darà l'output come "Perfect Gradient".

Produzione

C:\pybrain\pybrain\src>python testlayer1.py
Perfect gradient