Skip to content

Instantly share code, notes, and snippets.

@charlycoste
Last active October 21, 2016 08:39
Show Gist options
  • Save charlycoste/97833a9741929baf0d31bfc2381da170 to your computer and use it in GitHub Desktop.
Save charlycoste/97833a9741929baf0d31bfc2381da170 to your computer and use it in GitHub Desktop.
<?php
class Perceptron
{
private $weights;
public function __construct($n)
{
for ($i=0; $i<$n; $i++) {
$this->weights[$i] = rand()/getrandmax()-0.5;
}
}
public function feedforward(array $inputs)
{
return $this->activate(
array_sum(
array_map(
function($a,$b) {return $a * $b;},
$inputs,
$this->weights
)
)
);
}
private function activate($sum)
{
return $sum > 0 ? 1 : -1;
}
public function learn(array $inputs, $error)
{
$c = 0.01;
$this->weights = array_map(
function($weight, $input) use ($error, $c) {
return $weight + $c * $error * $input;
},
$this->weights,
$inputs
);
}
}
<?php
class Trainer
{
public function desired($inputs) {
list($x,$y) = $inputs;
return $y > (2 * $x + 1) ? 1 : -1;
}
public function generateInputs()
{
return [
rand()/getrandmax()*1000-500,
rand()/getrandmax()*1000-500,
1
];
}
public function train($perceptron, $inputs)
{
$desired = $this->desired($inputs);
//echo "La bonne réponse est : {$desired}\n";
$guess = $perceptron->feedforward($inputs);
//echo "Le perceptron pense que c'est {$guess}\n";
$error = $desired - $guess;
//echo "L'erreur est de : {$error}\n";
$perceptron->learn(
$inputs,
$error
);
}
}
<?php
$p = new Perceptron(3);
$t = new Trainer();
$note_max = 20;
$interro = [];
for($i=0; $i<$note_max; $i++) {
$interro[] = $t->generateInputs();
}
// Évaluation
$errors = 0;
foreach ($interro as $exercice) {
$guess = $p->feedforward($exercice);
$desired = $t->desired($exercice);
$errors += ($desired - $guess) > 0 ? 1 : 0;
}
$note = $note_max - $errors;
echo "Le perceptron a eu {$note}/{$note_max}\n";
// Entrainement
for($i=0;$i<10000;$i++) {
$exercice = $t->generateInputs();
$t->train($p, $exercice);
}
// Évaluation
$errors = 0;
foreach ($interro as $exercice) {
$guess = $p->feedforward($exercice);
$desired = $t->desired($exercice);
$errors += ($desired - $guess) > 0 ? 1 : 0;
}
$note = $note_max - $errors;
echo "Le perceptron a eu {$note}/{$note_max}\n";
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment