#include "neuralnet.h" #include "controller.h" #include "filenames.h" #include #include #include using namespace std; using namespace FANN; void NeuralNet::saveNut() { if (Controller::inst().getCurRating() == -1) { cerr << "Error: current rating -1 during saving." << endl; exit(1); } ostringstream input_line; input_line << current_index << ";"; input_line.precision(numeric_limits::max_digits10); const auto& results = Controller::inst().getRateProcessing().getResults(); for (const auto& result : result_names) { auto pos = results.find(result); if (pos == results.end()) { cerr << "Could not find " << result << " in results." << endl; exit(1); } inputTrainData.push_back(pos->second); input_line << scientific << pos->second << ";"; } ofstream input_file; input_file.open(FileNames::inputName, ios_base::app); input_file << input_line.str() << "\n"; outputTrainData.push_back(Controller::inst().getCurRating()); ofstream output_file; output_file.open(FileNames::outputName, ios_base::app); output_file << current_index << ";"; output_file << Controller::inst().getCurRating() << ";" << "\n"; ostringstream img_file; img_file << FileNames::imgPath << "nut_" << to_string(current_index) << ".jpg"; imwrite(img_file.str(), *Controller::inst().getNutToRate()); current_index++; if (current_index % 5 == 0) { trainAndSave(); } } void NeuralNet::trainAndSave() { setlocale(LC_ALL, "en_GB.UTF-8"); getScalingFactors(); scaleData(); training_data data; data.set_train_data(scaledOutputTrainData.size(), result_names.size(), &scaledInputTrainData[0], 1, &scaledOutputTrainData[0]); net.train_on_data(data, 100000, 1000, 0.01); if (!net.save(FileNames::neuralNetName)) { cerr << "Error saving neural net:" << net.get_errstr() << endl; exit(1); } } void NeuralNet::scaleData() { scaledInputTrainData = vector(inputTrainData.size()); for(int i = 0; i(scaling_input_data[i])) * get <1>(scaling_input_data[i]); } } scaledOutputTrainData = vector(outputTrainData.size()); for(int i = 0; i>(result_names.size()); for(int i = 0; i& input) { float input_arr[input.size()]; for (unsigned int i = 0; i 0) { input_arr[i] = (pos->second - get<0>(scaling_input_data[i])) * get<1>(scaling_input_data[i]); } else { input_arr[i] = pos->second; } } float ret = 0.0f; if (use_neural_net) { float* output; output = net.run(input_arr); ret = output[0]; } else { ret = 0.25 * input_arr[0] + 0.125* input_arr[1] + 0.125* (1.0f/input_arr[2]) + 0.25 * input_arr[3] + 0.25 * input_arr[4]; } return min(1.0f, max(ret, 0.0f)); } void NeuralNet::init(Json::Value jsonResults) { for(int i = 0; i