Skip to content

Commit

Permalink
Neural networks partial training and persistency (#91)
Browse files Browse the repository at this point in the history
* Neural networks partial training and persistency

* cs fixes

* Add partialTrain to nn docs

* Test for invalid partial training classes provided
  • Loading branch information
dmonllao authored and akondas committed May 23, 2017
1 parent 3dff40e commit de50490
Show file tree
Hide file tree
Showing 7 changed files with 175 additions and 25 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,19 @@ $mlp->train(
$samples = [[1, 0, 0, 0], [0, 1, 1, 0], [1, 1, 1, 1], [0, 0, 0, 0]],
$targets = ['a', 'a', 'b', 'c']
);
```

Use partialTrain method to train in batches. Example:

```
$mlp->partialTrain(
$samples = [[1, 0, 0, 0], [0, 1, 1, 0]],
$targets = ['a', 'a']
);
$mlp->partialTrain(
$samples = [[1, 1, 1, 1], [0, 0, 0, 0]],
$targets = ['b', 'c']
);
```

Expand Down
9 changes: 0 additions & 9 deletions src/Phpml/Classification/MLPClassifier.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,17 +4,8 @@

namespace Phpml\Classification;

use Phpml\Classification\Classifier;
use Phpml\Exception\InvalidArgumentException;
use Phpml\NeuralNetwork\Network\MultilayerPerceptron;
use Phpml\NeuralNetwork\Training\Backpropagation;
use Phpml\NeuralNetwork\ActivationFunction;
use Phpml\NeuralNetwork\Layer;
use Phpml\NeuralNetwork\Node\Bias;
use Phpml\NeuralNetwork\Node\Input;
use Phpml\NeuralNetwork\Node\Neuron;
use Phpml\NeuralNetwork\Node\Neuron\Synapse;
use Phpml\Helper\Predictable;

class MLPClassifier extends MultilayerPerceptron implements Classifier
{
Expand Down
4 changes: 4 additions & 0 deletions src/Phpml/Exception/InvalidArgumentException.php
Original file line number Diff line number Diff line change
Expand Up @@ -108,4 +108,8 @@ public static function invalidClassesNumber()
return new self('Provide at least 2 different classes');
}

public static function inconsistentClasses()
{
return new self('The provided classes don\'t match the classes provided in the constructor');
}
}
8 changes: 8 additions & 0 deletions src/Phpml/NeuralNetwork/Network/LayeredNetwork.php
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,14 @@ public function getLayers(): array
return $this->layers;
}

/**
* @return void
*/
public function removeLayers()
{
unset($this->layers);
}

/**
* @return Layer
*/
Expand Down
76 changes: 66 additions & 10 deletions src/Phpml/NeuralNetwork/Network/MultilayerPerceptron.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
namespace Phpml\NeuralNetwork\Network;

use Phpml\Estimator;
use Phpml\IncrementalEstimator;
use Phpml\Exception\InvalidArgumentException;
use Phpml\NeuralNetwork\Training\Backpropagation;
use Phpml\NeuralNetwork\ActivationFunction;
Expand All @@ -15,10 +16,20 @@
use Phpml\NeuralNetwork\Node\Neuron\Synapse;
use Phpml\Helper\Predictable;

abstract class MultilayerPerceptron extends LayeredNetwork implements Estimator
abstract class MultilayerPerceptron extends LayeredNetwork implements Estimator, IncrementalEstimator
{
use Predictable;

/**
* @var int
*/
private $inputLayerFeatures;

/**
* @var array
*/
private $hiddenLayers;

/**
* @var array
*/
Expand All @@ -29,6 +40,16 @@ abstract class MultilayerPerceptron extends LayeredNetwork implements Estimator
*/
private $iterations;

/**
* @var ActivationFunction
*/
protected $activationFunction;

/**
* @var int
*/
private $theta;

/**
* @var Backpropagation
*/
Expand All @@ -50,22 +71,33 @@ public function __construct(int $inputLayerFeatures, array $hiddenLayers, array
throw InvalidArgumentException::invalidLayersNumber();
}

$nClasses = count($classes);
if ($nClasses < 2) {
if (count($classes) < 2) {
throw InvalidArgumentException::invalidClassesNumber();
}
$this->classes = array_values($classes);

$this->classes = array_values($classes);
$this->iterations = $iterations;
$this->inputLayerFeatures = $inputLayerFeatures;
$this->hiddenLayers = $hiddenLayers;
$this->activationFunction = $activationFunction;
$this->theta = $theta;

$this->initNetwork();
}

$this->addInputLayer($inputLayerFeatures);
$this->addNeuronLayers($hiddenLayers, $activationFunction);
$this->addNeuronLayers([$nClasses], $activationFunction);
/**
* @return void
*/
private function initNetwork()
{
$this->addInputLayer($this->inputLayerFeatures);
$this->addNeuronLayers($this->hiddenLayers, $this->activationFunction);
$this->addNeuronLayers([count($this->classes)], $this->activationFunction);

$this->addBiasNodes();
$this->generateSynapses();

$this->backpropagation = new Backpropagation($theta);
$this->backpropagation = new Backpropagation($this->theta);
}

/**
Expand All @@ -74,6 +106,22 @@ public function __construct(int $inputLayerFeatures, array $hiddenLayers, array
*/
public function train(array $samples, array $targets)
{
$this->reset();
$this->initNetwork();
$this->partialTrain($samples, $targets, $this->classes);
}

/**
* @param array $samples
* @param array $targets
*/
public function partialTrain(array $samples, array $targets, array $classes = [])
{
if (!empty($classes) && array_values($classes) !== $this->classes) {
// We require the list of classes in the constructor.
throw InvalidArgumentException::inconsistentClasses();
}

for ($i = 0; $i < $this->iterations; ++$i) {
$this->trainSamples($samples, $targets);
}
Expand All @@ -83,13 +131,21 @@ public function train(array $samples, array $targets)
* @param array $sample
* @param mixed $target
*/
protected abstract function trainSample(array $sample, $target);
abstract protected function trainSample(array $sample, $target);

/**
* @param array $sample
* @return mixed
*/
protected abstract function predictSample(array $sample);
abstract protected function predictSample(array $sample);

/**
* @return void
*/
protected function reset()
{
$this->removeLayers();
}

/**
* @param int $nodes
Expand Down
10 changes: 6 additions & 4 deletions src/Phpml/NeuralNetwork/Training/Backpropagation.php
Original file line number Diff line number Diff line change
Expand Up @@ -17,12 +17,12 @@ class Backpropagation
/**
* @var array
*/
private $sigmas;
private $sigmas = null;

/**
* @var array
*/
private $prevSigmas;
private $prevSigmas = null;

/**
* @param int $theta
Expand All @@ -38,14 +38,12 @@ public function __construct(int $theta)
*/
public function backpropagate(array $layers, $targetClass)
{

$layersNumber = count($layers);

// Backpropagation.
for ($i = $layersNumber; $i > 1; --$i) {
$this->sigmas = [];
foreach ($layers[$i - 1]->getNodes() as $key => $neuron) {

if ($neuron instanceof Neuron) {
$sigma = $this->getSigma($neuron, $targetClass, $key, $i == $layersNumber);
foreach ($neuron->getSynapses() as $synapse) {
Expand All @@ -55,6 +53,10 @@ public function backpropagate(array $layers, $targetClass)
}
$this->prevSigmas = $this->sigmas;
}

// Clean some memory (also it helps make MLP persistency & children more maintainable).
$this->sigmas = null;
$this->prevSigmas = null;
}

/**
Expand Down
80 changes: 78 additions & 2 deletions tests/Phpml/Classification/MLPClassifierTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,8 @@
namespace tests\Phpml\Classification;

use Phpml\Classification\MLPClassifier;
use Phpml\NeuralNetwork\Training\Backpropagation;
use Phpml\NeuralNetwork\Node\Neuron;
use Phpml\ModelManager;
use PHPUnit\Framework\TestCase;

class MLPClassifierTest extends TestCase
Expand Down Expand Up @@ -53,7 +53,7 @@ public function testSynapsesGeneration()
public function testBackpropagationLearning()
{
// Single layer 2 classes.
$network = new MLPClassifier(2, [2], ['a', 'b'], 1000);
$network = new MLPClassifier(2, [2], ['a', 'b']);
$network->train(
[[1, 0], [0, 1], [1, 1], [0, 0]],
['a', 'b', 'a', 'b']
Expand All @@ -65,6 +65,50 @@ public function testBackpropagationLearning()
$this->assertEquals('b', $network->predict([0, 0]));
}

public function testBackpropagationTrainingReset()
{
// Single layer 2 classes.
$network = new MLPClassifier(2, [2], ['a', 'b'], 1000);
$network->train(
[[1, 0], [0, 1]],
['a', 'b']
);

$this->assertEquals('a', $network->predict([1, 0]));
$this->assertEquals('b', $network->predict([0, 1]));

$network->train(
[[1, 0], [0, 1]],
['b', 'a']
);

$this->assertEquals('b', $network->predict([1, 0]));
$this->assertEquals('a', $network->predict([0, 1]));
}

public function testBackpropagationPartialTraining()
{
// Single layer 2 classes.
$network = new MLPClassifier(2, [2], ['a', 'b'], 1000);
$network->partialTrain(
[[1, 0], [0, 1]],
['a', 'b']
);

$this->assertEquals('a', $network->predict([1, 0]));
$this->assertEquals('b', $network->predict([0, 1]));

$network->partialTrain(
[[1, 1], [0, 0]],
['a', 'b']
);

$this->assertEquals('a', $network->predict([1, 0]));
$this->assertEquals('b', $network->predict([0, 1]));
$this->assertEquals('a', $network->predict([1, 1]));
$this->assertEquals('b', $network->predict([0, 0]));
}

public function testBackpropagationLearningMultilayer()
{
// Multi-layer 2 classes.
Expand Down Expand Up @@ -96,6 +140,26 @@ public function testBackpropagationLearningMulticlass()
$this->assertEquals(4, $network->predict([0, 0, 0, 0, 0]));
}

public function testSaveAndRestore()
{
// Instantinate new Percetron trained for OR problem
$samples = [[0, 0], [1, 0], [0, 1], [1, 1]];
$targets = [0, 1, 1, 1];
$classifier = new MLPClassifier(2, [2], [0, 1]);
$classifier->train($samples, $targets);
$testSamples = [[0, 0], [1, 0], [0, 1], [1, 1]];
$predicted = $classifier->predict($testSamples);

$filename = 'perceptron-test-'.rand(100, 999).'-'.uniqid();
$filepath = tempnam(sys_get_temp_dir(), $filename);
$modelManager = new ModelManager();
$modelManager->saveToFile($classifier, $filepath);

$restoredClassifier = $modelManager->restoreFromFile($filepath);
$this->assertEquals($classifier, $restoredClassifier);
$this->assertEquals($predicted, $restoredClassifier->predict($testSamples));
}

/**
* @expectedException \Phpml\Exception\InvalidArgumentException
*/
Expand All @@ -104,6 +168,18 @@ public function testThrowExceptionOnInvalidLayersNumber()
new MLPClassifier(2, [], [0, 1]);
}

/**
* @expectedException \Phpml\Exception\InvalidArgumentException
*/
public function testThrowExceptionOnInvalidPartialTrainingClasses()
{
$classifier = new MLPClassifier(2, [2], [0, 1]);
$classifier->partialTrain(
[[0, 1], [1, 0]],
[0, 2],
[0, 1, 2]
);
}
/**
* @expectedException \Phpml\Exception\InvalidArgumentException
*/
Expand Down

0 comments on commit de50490

Please sign in to comment.