This code can be used to read training data from MySQL rather than a text file.
<?php
function get_training_data_from_db($id) {
$table_name = "TrainingSets";
$field = "TrainingData";
$connection=mysqli_connect("host","username","password","database"); $result=mysqli_query($connection,"SELECT $field FROM $table_name");
$data=mysqli_fetch_assoc($result);
mysqli_close($connection);
return $data[$field];
}
function prepare_data_from_db($training_data) {
$training_data = explode( "\n", $training_data ); $num_data = count($training_data);
for($i=0;$i<$num_data;$i++) {
if($i % 2) { $training_data['outputs'][] = explode( " ", $training_data[$i]);
}else{ $training_data['inputs'][] = explode( " ", $training_data[$i]);
}
}
foreach ($training_data as $key => $value) {
if (is_numeric($key)) {
unset($training_data[$key]);
}
}
return $training_data; }
function create_train_callback($num_data, $num_input, $num_output) {
global $training_data;
global $current_dataset;
$dataset = array("input" => $training_data['inputs'][$current_dataset],
"output" => $training_data['outputs'][$current_dataset]);
$current_dataset++;
return $dataset;
}
$record_id = 1; $current_dataset = 0;
$num_input = 2;
$num_output = 1;
$num_layers = 3;
$num_neurons = 3;
$desired_error = 0.001;
$max_epochs = 500000;
$epochs_between_reports = 1000;
$training_data = get_training_data_from_db($record_id); $training_data = prepare_data_from_db($training_data); $num_data = count($training_data["input"]); $train_data = fann_create_train_from_callback($num_data, $num_input, $num_output, "create_train_callback");
if ($train_data) {
$ann = fann_create_standard($num_layers, $num_input, $num_neurons, $num_output);
if ($ann) {
fann_set_activation_function_hidden($ann, FANN_SIGMOID_SYMMETRIC);
fann_set_activation_function_output($ann, FANN_SIGMOID_SYMMETRIC);
if (fann_train_on_data($ann, $train_data, $max_epochs, $epochs_between_reports, $desired_error)){
print('XOR trained.<br>' . PHP_EOL);
$input = array(-1, 1);
$calc_out = fann_run($ann, $input);
printf("xor test (%f,%f) -> %f\n", $input[0], $input[1], $calc_out[0]);
fann_destroy($ann);
}
}
}
?>