This code demonstrates training XOR using fann_train_epoch and will let you watch the training process by observing a psudo MSE (mean squared error).
Other training functions: fann_train_on_data, fann_train_on_file, fann_train.
fann_train_epoch is useful when you want to observe the ANN while it is training and perhaps save snapshots or compare competing networks during training.
fann_train_epoch is different from fann_train in that it takes a data resource (training file) whereas fann_train takes an array of inputs and a separate array of outputs so use fann_train_epoch for observing training on data files (callback training resources) and use fann_train when observing manually specified data.
Example code:
<?php
$num_input = 2;
$num_output = 1;
$num_layers = 3;
$num_neurons_hidden = 3;
$desired_error = 0.0001;
$max_epochs = 500000;
$current_epoch = 0;
$epochs_between_saves = 100; $epochs_since_last_save = 0;
$filename = dirname(__FILE__) . "/xor.data";
$psudo_mse_result = $desired_error * 10000; $best_mse = $psudo_mse_result; $ann = fann_create_standard($num_layers, $num_input, $num_neurons_hidden, $num_output);
if ($ann) {
echo 'Training ANN... ' . PHP_EOL;
fann_set_training_algorithm ($ann , FANN_TRAIN_BATCH);
fann_set_activation_function_hidden($ann, FANN_SIGMOID_SYMMETRIC);
fann_set_activation_function_output($ann, FANN_SIGMOID_SYMMETRIC);
$train_data = fann_read_train_from_file($filename);
while(($psudo_mse_result > $desired_error) && ($current_epoch <= $max_epochs)){
$current_epoch++;
$epochs_since_last_save++;
$psudo_mse_result = fann_train_epoch ($ann , $train_data );
echo 'Epoch ' . $current_epoch . ' : ' . $psudo_mse_result . PHP_EOL; if(($epochs_since_last_save >= $epochs_between_saves) && ($psudo_mse_result < $best_mse)){
$best_mse = $psudo_mse_result; fann_save($ann, dirname(__FILE__) . "/xor.net");
echo 'Saved ANN.' . PHP_EOL; $epochs_since_last_save = 0; }
} echo 'Training Complete! Saving Final Network.' . PHP_EOL;
fann_save($ann, dirname(__FILE__) . "/xor.net");
fann_destroy($ann); }
echo 'All Done!' . PHP_EOL;
?>