Esempio n. 1
0
void GazeTracker::trainNN() {
	std::cout << "Getting data" << std::endl;
	struct fann_train_data *data = fann_create_train_from_callback(_inputCount, _nnEyeWidth * _nnEyeHeight, 2, getTrainingData);
	//fann_save_train(data, "data.txt");

	std::cout << "Getting left data" << std::endl;
	struct fann_train_data *dataLeft = fann_create_train_from_callback(_inputCount, _nnEyeWidth * _nnEyeHeight, 2, getTrainingDataLeft);
	//fann_save_train(dataLeft, "dataLeft.txt");

	fann_set_training_algorithm(_ANN, FANN_TRAIN_RPROP);
	fann_set_learning_rate(_ANN, 0.75);
	fann_set_training_algorithm(_ANNLeft, FANN_TRAIN_RPROP);
	fann_set_learning_rate(_ANNLeft, 0.75);

	std::cout << "Training" << std::endl;
	fann_train_on_data(_ANN, data, 200, 20, 0.01);

	std::cout << "Training left" << std::endl;
	fann_train_on_data(_ANNLeft, dataLeft, 200, 20, 0.01);

	double mse = fann_get_MSE(_ANN);
	double mseLeft = fann_get_MSE(_ANNLeft);

	std::cout << "MSE: " << mse << ", MSE left: " << mseLeft << std::endl;
}
Esempio n. 2
0
void GazeTracker::trainNN()
{
	cout << "Getting data" << endl;
	struct fann_train_data* data = fann_create_train_from_callback(input_count, nn_eyewidth * nn_eyeheight, 2, getTrainingData);
	//fann_save_train(data, "data.txt");

	cout << "Getting left data" << endl;
	struct fann_train_data* data_left = fann_create_train_from_callback(input_count, nn_eyewidth * nn_eyeheight, 2, getTrainingData_left);
	//fann_save_train(data_left, "data_left.txt");

	fann_set_training_algorithm(ANN, FANN_TRAIN_RPROP);
	fann_set_learning_rate(ANN, 0.75);
	fann_set_training_algorithm(ANN_left, FANN_TRAIN_RPROP);
	fann_set_learning_rate(ANN_left, 0.75);
	
	cout << "Training" << endl;
	fann_train_on_data(ANN, data, 200, 20, 0.01);

	cout << "Training left" << endl;
	fann_train_on_data(ANN_left, data_left, 200, 20, 0.01);
	
	double mse = fann_get_MSE(ANN);
	double mse_left = fann_get_MSE(ANN_left);
	
	cout << "MSE: " << mse << ", MSE left: " << mse_left << endl;
}
Esempio n. 3
0
void ViFann::setTraining(const Algorithm &algorithm)
{
	mAlgorithm = algorithm;
	if(mAlgorithm == Incremental) fann_set_training_algorithm(mNetwork, FANN_TRAIN_INCREMENTAL);
	else if(mAlgorithm == Batch) fann_set_training_algorithm(mNetwork, FANN_TRAIN_BATCH);
	else if(mAlgorithm == RProp) fann_set_training_algorithm(mNetwork, FANN_TRAIN_RPROP);
	else if(mAlgorithm == QuickProp) fann_set_training_algorithm(mNetwork, FANN_TRAIN_QUICKPROP);
}
Esempio n. 4
0
int main( int argc, char** argv )
{
	const unsigned int num_input = 3;
	const unsigned int num_output = 1;
	const unsigned int num_layers = 4;
	const unsigned int num_neurons_hidden = 5;
	const float desired_error = (const float) 0.0001;
	const unsigned int max_epochs = 5000;
	const unsigned int epochs_between_reports = 1000;
	struct fann_train_data * data = NULL;
	struct fann *ann = fann_create_standard(num_layers, num_input, num_neurons_hidden, num_neurons_hidden, num_output);
	fann_set_activation_function_hidden(ann, FANN_SIGMOID_SYMMETRIC);
	fann_set_activation_function_output(ann, FANN_LINEAR);
	fann_set_training_algorithm(ann, FANN_TRAIN_RPROP);
	data = fann_read_train_from_file("../../datasets/scaling.data");
	fann_set_scaling_params(
		    ann,
			data,
			-1,	/* New input minimum */
			1,	/* New input maximum */
			-1,	/* New output minimum */
			1);	/* New output maximum */

	fann_scale_train( ann, data );

	fann_train_on_data(ann, data, max_epochs, epochs_between_reports, desired_error);
	fann_destroy_train( data );
	fann_save(ann, "scaling.net");
	fann_destroy(ann);
	return 0;
}
int main()
{
	fann_type *calc_out;
	const unsigned int num_input = 2;
	const unsigned int num_output = 1;
	const unsigned int num_layers = 3;
	const unsigned int num_neurons_hidden = 9;
	const float desired_error = (const float) 0;
	const unsigned int max_epochs = 500000;
	const unsigned int epochs_between_reports = 1000;
	struct fann *ann;
	struct fann_train_data *data;

	unsigned int i = 0;
	unsigned int decimal_point;

	printf("Creating network.\n");
	ann = fann_create_standard(num_layers, num_input, num_neurons_hidden, num_output);

	data = fann_read_train_from_file("osyslec_train.data");

	fann_set_activation_steepness_hidden(ann, 1);
	fann_set_activation_steepness_output(ann, 1);

	fann_set_activation_function_hidden(ann, FANN_SIGMOID);
	fann_set_activation_function_output(ann, FANN_SIGMOID);

	fann_set_train_stop_function(ann, FANN_STOPFUNC_BIT);
	fann_set_bit_fail_limit(ann, 0.01f);

	fann_set_training_algorithm(ann, FANN_TRAIN_RPROP);

	fann_init_weights(ann, data);
	
	printf("Training network.\n");
	fann_train_on_data(ann, data, max_epochs, epochs_between_reports, desired_error);

	printf("Testing network. %f\n", fann_test_data(ann, data));

	for(i = 0; i < fann_length_train_data(data); i++)
	{
		calc_out = fann_run(ann, data->input[i]);
		printf("GG test (%f,%f) -> %f, should be %f, difference=%f\n",
			   data->input[i][0], data->input[i][1], calc_out[0], data->output[i][0],
			   fann_abs(calc_out[0] - data->output[i][0]));
	}

	printf("Saving network.\n");

	fann_save(ann, "osyslec_train_float.net");

	decimal_point = fann_save_to_fixed(ann, "osyslec_train_fixed.net");
	fann_save_train_to_fixed(data, "osyslec_train_fixed.data", decimal_point);

	printf("Cleaning up.\n");
	fann_destroy_train(data);
	fann_destroy(ann);

	return 0;
}
Esempio n. 6
0
int 
main(int argc, char **argv)
{
	const unsigned int num_input = 360;
	const unsigned int num_output = 1;
	const unsigned int num_layers = 4;
	const unsigned int num_neurons_hidden = num_input / 2;
	const float desired_error = (const float) 0.001;
	const unsigned int max_epochs = 300;
	const unsigned int epochs_between_reports = 10;
	struct fann_train_data * data = NULL;
	struct fann *ann = fann_create_standard(num_layers, num_input, num_neurons_hidden, num_neurons_hidden / 2, num_output);
	unsigned int i, j;

	if (argc != 2)
	{
		fprintf(stderr, "Use: %s arquivoTreino\n", argv[0]); 
		exit(1);
	}

	fann_set_activation_function_hidden(ann, FANN_ELLIOT);
	fann_set_activation_function_output(ann, FANN_LINEAR);
	fann_set_training_algorithm(ann, FANN_TRAIN_RPROP);
	fann_set_learning_rate(ann, 0.1);
	fann_set_learning_momentum(ann, 0.6);
	data = fann_read_train_from_file(argv[1]);

	fann_train_on_data(ann, data, max_epochs, epochs_between_reports, desired_error);

	free(data);
	fann_save(ann, ARQ_RNA);
	fann_destroy(ann);

	return 0;
}
Esempio n. 7
0
 void Classifier::createNew()
 {
     fann_destroy(neuralNetwork);
     neuralNetwork = fann_create_standard(NUM_LAYERS, NUM_INP, numHidden, NUM_OUTP);
     //fann_set_activation_function_hidden(neuralNetwork, FANN_SIGMOID_SYMMETRIC);
     //fann_set_activation_function_output(neuralNetwork, FANN_SIGMOID_SYMMETRIC);
     fann_set_activation_function_hidden(neuralNetwork, FANN_LINEAR_PIECE_SYMMETRIC);
     fann_set_activation_function_output(neuralNetwork, FANN_LINEAR_PIECE_SYMMETRIC);
     fann_set_training_algorithm(neuralNetwork,FANN_TRAIN_INCREMENTAL);
 }
Esempio n. 8
0
/***
 * @function rspamd_fann.create(nlayers, [layer1, ... layern])
 * Creates new neural network with `nlayers` that contains `layer1`...`layern`
 * neurons in each layer
 * @param {number} nlayers number of layers
 * @param {number} layerI number of neurons in each layer
 * @return {fann} fann object
 */
static gint
lua_fann_create (lua_State *L)
{
#ifndef WITH_FANN
	return 0;
#else
	struct fann *f, **pfann;
	guint nlayers, *layers, i;

	nlayers = luaL_checknumber (L, 1);

	if (nlayers > 0) {
		layers = g_malloc (nlayers * sizeof (layers[0]));

		if (lua_type (L, 2) == LUA_TNUMBER) {
			for (i = 0; i < nlayers; i ++) {
				layers[i] = luaL_checknumber (L, i + 2);
			}
		}
		else if (lua_type (L, 2) == LUA_TTABLE) {
			for (i = 0; i < nlayers; i ++) {
				lua_rawgeti (L, 2, i + 1);
				layers[i] = luaL_checknumber (L, -1);
				lua_pop (L, 1);
			}
		}

		f = fann_create_standard_array (nlayers, layers);
		fann_set_activation_function_hidden (f, FANN_SIGMOID_SYMMETRIC);
		fann_set_activation_function_output (f, FANN_SIGMOID_SYMMETRIC);
		fann_set_training_algorithm (f, FANN_TRAIN_INCREMENTAL);
		fann_randomize_weights (f, 0, 1);

		if (f != NULL) {
			pfann = lua_newuserdata (L, sizeof (gpointer));
			*pfann = f;
			rspamd_lua_setclass (L, "rspamd{fann}", -1);
		}
		else {
			lua_pushnil (L);
		}

		g_free (layers);
	}
	else {
		lua_pushnil (L);
	}

	return 1;
#endif
}
Esempio n. 9
0
int main()
{
	const unsigned int num_input = 2;
	const unsigned int num_output = 1;
	const unsigned int num_layers = 3;
	const unsigned int num_neurons_hidden = 3;
	const float desired_error = (const float) 0.001;
	const unsigned int max_epochs = 500000;
	const unsigned int epochs_between_reports = 1000;
	unsigned int i;
	fann_type *calc_out;

	struct fann_train_data *data;

	struct fann *ann = fann_create_standard(num_layers,
								   num_input, num_neurons_hidden, num_output);

	data = fann_read_train_from_file("xor.data");

	fann_set_activation_function_hidden(ann, FANN_SIGMOID_SYMMETRIC);
	fann_set_activation_function_output(ann, FANN_SIGMOID_SYMMETRIC);

	fann_set_training_algorithm(ann, FANN_TRAIN_QUICKPROP);

	train_on_steepness_file(ann, "xor.data", max_epochs,
							epochs_between_reports, desired_error, (float) 1.0, (float) 0.1,
							(float) 20.0);

	fann_set_activation_function_hidden(ann, FANN_THRESHOLD_SYMMETRIC);
	fann_set_activation_function_output(ann, FANN_THRESHOLD_SYMMETRIC);

	for(i = 0; i != fann_length_train_data(data); i++)
	{
		calc_out = fann_run(ann, data->input[i]);
		printf("XOR test (%f, %f) -> %f, should be %f, difference=%f\n",
			   data->input[i][0], data->input[i][1], calc_out[0], data->output[i][0],
			   (float) fann_abs(calc_out[0] - data->output[i][0]));
	}


	fann_save(ann, "xor_float.net");

	fann_destroy(ann);
	fann_destroy_train(data);

	return 0;
}
int main()
{
	struct fann *ann;
	struct fann_train_data *train_data, *test_data;
	const float desired_error = (const float) 0.001;
	unsigned int max_neurons = 40;
	unsigned int neurons_between_reports = 1;

	printf("Reading data.\n");

	train_data = fann_read_train_from_file("../benchmarks/datasets/two-spiral.train");
	test_data = fann_read_train_from_file("../benchmarks/datasets/two-spiral.test");

	fann_scale_train_data(train_data, 0, 1);
	fann_scale_train_data(test_data, 0, 1);

	printf("Creating network.\n");

	ann = fann_create_shortcut(2, fann_num_input_train_data(train_data), fann_num_output_train_data(train_data));

	fann_set_training_algorithm(ann, FANN_TRAIN_RPROP);
	fann_set_activation_function_hidden(ann, FANN_SIGMOID_SYMMETRIC);
	fann_set_activation_function_output(ann, FANN_LINEAR_PIECE);
	fann_set_train_error_function(ann, FANN_ERRORFUNC_LINEAR);

	fann_print_parameters(ann);

	printf("Training network.\n");

	fann_cascadetrain_on_data(ann, train_data, max_neurons, neurons_between_reports, desired_error);

	fann_print_connections(ann);

	printf("\nTrain error: %f, Test error: %f\n\n", fann_test_data(ann, train_data),
		   fann_test_data(ann, test_data));

	printf("Saving network.\n");

	fann_save(ann, "two_spirali.net");

	printf("Cleaning up.\n");
	fann_destroy_train(train_data);
	fann_destroy_train(test_data);
	fann_destroy(ann);

	return 0;
}
static struct sml_ann_bridge *
_sml_ann_bridge_new(struct fann *ann, bool trained)
{
    struct sml_ann_bridge *iann = calloc(1, sizeof(struct sml_ann_bridge));

    if (!iann) {
        sml_critical("Could not create an struct sml_ann_bridge");
        return NULL;
    }
    sol_vector_init(&iann->confidence_intervals, sizeof(Confidence_Interval));
    iann->ann = ann;
    iann->trained = trained;
    iann->last_train_error = NAN;
    if (iann->trained)
        fann_set_training_algorithm(iann->ann, FANN_TRAIN_INCREMENTAL);
    return iann;
}
NeuralNet::NeuralNet(){
    cout << "Initializing neural network" << endl;
    this->numInputNeurons = 144;
    this->numOutputNeurons = 1;
    this->numLayers = 3;
    this->numHiddenNeurons = 140;
    this->ptrNeuralNet = fann_create_standard(numLayers, numInputNeurons, numHiddenNeurons, numOutputNeurons);
    fann_set_activation_steepness_hidden(this->ptrNeuralNet, 1);
    fann_set_activation_steepness_output(this->ptrNeuralNet, 1);
    //sigmoidal function
    fann_set_activation_function_hidden(this->ptrNeuralNet, FANN_SIGMOID_SYMMETRIC);
    fann_set_activation_function_output(this->ptrNeuralNet, FANN_SIGMOID_SYMMETRIC);

    fann_set_train_stop_function(this->ptrNeuralNet, FANN_STOPFUNC_BIT);
    fann_set_bit_fail_limit(this->ptrNeuralNet, 0.01f);

    fann_set_training_algorithm(this->ptrNeuralNet, FANN_TRAIN_RPROP);
}
Esempio n. 13
0
/*! ann:set_training_algorithm(function)
 *# Sets the training function for the neural network.\n
 *# Valid algorithms are {{fann.FANN_TRAIN_INCREMENTAL}},
 *# {{fann.FANN_TRAIN_BATCH}}, {{fann.FANN_TRAIN_RPROP}} or
 *# {{fann.FANN_TRAIN_QUICKPROP}}
 *x ann:set_training_algorithm(fann.FANN_TRAIN_QUICKPROP)
 *-
 */
static int ann_set_training_algorithm(lua_State *L)
{
	struct fann **ann;
	int alg;

	ann = luaL_checkudata(L, 1, FANN_METATABLE);
	luaL_argcheck(L, ann != NULL, 1, "'neural net' expected");

	alg = luaL_checkinteger(L, 2);

	if(alg < FANN_TRAIN_INCREMENTAL || alg > FANN_TRAIN_QUICKPROP)
		luaL_error(L, "%d is not a valid algorithm", alg);

#ifdef FANN_VERBOSE
	printf("Setting training algorithm to %d\n", alg);
#endif

	fann_set_training_algorithm(*ann, alg);
	return 0;
}
Esempio n. 14
0
int main()
{
	const float desired_error = (const float) 0.0001;
	const unsigned int max_epochs = 350;
	const unsigned int epochs_between_reports = 25;
	struct fann *ann;
	struct fann_train_data *train_data;

	unsigned int i = 0;

	printf("Creating network.\n");

	train_data = fann_read_train_from_file("ann_training_data");
    // Using incremental training -> shuffle training data    
    fann_shuffle_train_data(train_data);

//	ann = fann_create_standard(num_layers,
//					  train_data->num_input, num_neurons_hidden, train_data->num_output);

    //ann = fann_create_standard(500, 2, 50, 50, 21);
    unsigned int layers[4] = {150, 70, 30, 22};
    ann = fann_create_standard_array(4, layers);
	printf("Training network.\n");

	fann_set_activation_function_hidden(ann, FANN_SIGMOID_SYMMETRIC_STEPWISE);
	fann_set_activation_function_output(ann, FANN_LINEAR_PIECE); //FANN_SIGMOID_STEPWISE);

    fann_set_training_algorithm(ann, FANN_TRAIN_INCREMENTAL);

	fann_train_on_data(ann, train_data, max_epochs, epochs_between_reports, desired_error);

	printf("Saving network.\n");

	fann_save(ann, "mymoves_gestures.net");

	printf("Cleaning up.\n");
	fann_destroy_train(train_data);
	fann_destroy(ann);

	return 0;
}
Esempio n. 15
0
int main()
{
	const unsigned int num_layers = 3;
	const unsigned int num_neurons_hidden = 96;
	const float desired_error = (const float) 0.001;
	struct fann *ann;
	struct fann_train_data *train_data, *test_data;

	float momentum;

	train_data = fann_read_train_from_file("../benchmarks/datasets/robot.train");
	test_data = fann_read_train_from_file("../benchmarks/datasets/robot.test");

	for ( momentum = 0.0; momentum < 0.7; momentum += 0.1 )
	{
		printf("============= momentum = %f =============\n", momentum);

		ann = fann_create_standard(num_layers,
						train_data->num_input, num_neurons_hidden, train_data->num_output);

		fann_set_training_algorithm(ann, FANN_TRAIN_INCREMENTAL);

		fann_set_learning_momentum(ann, momentum);

		fann_train_on_data(ann, train_data, 2000, 500, desired_error);

		printf("MSE error on train data: %f\n", fann_test_data(ann, train_data));
		printf("MSE error on test data : %f\n", fann_test_data(ann, test_data));

		fann_destroy(ann);
	}

	fann_destroy_train(train_data);
	fann_destroy_train(test_data);
	return 0;
}
Esempio n. 16
0
int main() {

	printf("Reading XML.. .. ..\n");
	ezxml_t f1 = ezxml_parse_file("test.xml"), classification, temp, algo, temp2;
	 
	classification = ezxml_child(f1, "classification");
	temp = ezxml_child(classification, "algorithm");
	algo = ezxml_child(temp, "MultiLayerPerceptron");

	const unsigned int num_input = atoi(ezxml_child(classification, "input")->txt);
	const unsigned int num_output = atoi(ezxml_child(classification, "output")->txt);
	const unsigned int num_layers = atoi(ezxml_child(classification, "numberOfLayers")->txt);
	const unsigned int num_neurons_hidden = atoi(ezxml_child(algo, "hiddenNeurons")->txt);
	const float desired_error = (const float) (atof(ezxml_child(algo, "desiredError")->txt));
	const unsigned int max_epochs = atoi(ezxml_child(algo, "maxEpochs")->txt);
	const unsigned int epochs_between_reports = atoi(ezxml_child(algo, "epochsBetweenReports")->txt);

	fann_type *calc_out;
	
	struct fann *ann;
	struct fann_train_data *data;

	unsigned int i = 0;
	unsigned int decimal_point;

	printf("Creating network.\n");
	ann = fann_create_standard(num_layers, num_input, num_neurons_hidden, num_output);

	data = fann_read_train_from_file(ezxml_child(classification, "datafile")->txt);

	fann_set_activation_steepness_hidden(ann, atoi(ezxml_child(algo, "hiddenActivationSteepness")->txt));
	fann_set_activation_steepness_output(ann, atoi(ezxml_child(algo, "outputActivationSteepness")->txt));

	fann_set_activation_function_hidden(ann, FANN_SIGMOID_SYMMETRIC);
	fann_set_activation_function_output(ann, FANN_SIGMOID_SYMMETRIC);
	
	temp2 = ezxml_child(algo, "trainStopFuction");
	const char *stopFunc = temp2->txt;
	if(stopFunc == "FANN_STOPFUNC_BIT"){
		fann_set_train_stop_function(ann, FANN_STOPFUNC_BIT);
	} else {
		fann_set_train_stop_function(ann, FANN_STOPFUNC_MSE);
	}
	fann_set_bit_fail_limit(ann, 0.01f);

	fann_set_training_algorithm(ann, FANN_TRAIN_RPROP);

	fann_init_weights(ann, data);
	
	printf("Training network.\n");
	fann_train_on_data(ann, data, max_epochs, epochs_between_reports, desired_error);

	printf("Testing network. %f\n", fann_test_data(ann, data));

	for(i = 0; i < fann_length_train_data(data); i++)
	{
		calc_out = fann_run(ann, data->input[i]);
		printf("Test Results (%f,%f,%f) -> %f, should be %f, difference=%f\n",
			   data->input[i][0], data->input[i][1], data->input[i][2], calc_out[0], data->output[i][0],
			   fann_abs(calc_out[0] - data->output[i][0]));
	}

	printf("Saving network.\n");

	fann_save(ann, "xor_float.net");

	decimal_point = fann_save_to_fixed(ann, "xor_fixed.net");
	fann_save_train_to_fixed(data, "xor_fixed.data", decimal_point);

	printf("Cleaning up.\n");
	fann_destroy_train(data);
	fann_destroy(ann);

	ezxml_free(f1);

	return 0;
}
Esempio n. 17
0
/*
arguments (all required):
 - data filename
 - topology, as number of neurons per layer separated by dashes
 - epochs (integer)
 - learning rate (0.0-1.0 float)
 - output filename
*/
int main(int argc, char **argv)
{
    // Argument 1: data filename.
    const char *datafn = argv[1];

    // Argument 2: topology.
    unsigned int layer_sizes[MAX_LAYERS];
    unsigned int num_layers = 0;
    char *token = strtok(argv[2], "-");
    while (token != NULL) {
        layer_sizes[num_layers] = atoi(token);
        ++num_layers;
        token = strtok(NULL, "-");
    }

    // Argument 3: epoch count.
    unsigned int max_epochs = atoi(argv[3]);

    // Argument 4: learning rate.
    float learning_rate = atof(argv[4]);

    // Argument 5: output filename.
    const char *outfn = argv[5];

    struct fann *ann;
	ann = fann_create_standard_array(num_layers, layer_sizes);

    // Misc parameters.
    fann_set_training_algorithm(ann, FANN_TRAIN_RPROP);
	fann_set_activation_steepness_hidden(ann, 0.5);
	fann_set_activation_steepness_output(ann, 0.5);
	fann_set_activation_function_hidden(ann, FANN_SIGMOID);
	fann_set_activation_function_output(ann, FANN_SIGMOID);
    //fann_set_train_stop_function(ann, FANN_STOPFUNC_BIT);
    //fann_set_bit_fail_limit(ann, 0.01f);

    struct fann_train_data *data;
    data = fann_read_train_from_file(datafn);
	fann_init_weights(ann, data);
	
    fann_set_learning_rate(ann, learning_rate);
	fann_train_on_data(
        ann,
        data,
        max_epochs,
        10,  // epochs between reports
        DESIRED_ERROR
    );

	printf("Testing network. %f\n", fann_test_data(ann, data));

    fann_type *calc_out;
	for(unsigned int i = 0; i < fann_length_train_data(data); ++i)
	{
		calc_out = fann_run(ann, data->input[i]);
	}
	
	printf("RMSE = %f\n", sqrt(fann_get_MSE(ann)));

	fann_save(ann, outfn);

	fann_destroy_train(data);
	fann_destroy(ann);

	return 0;
}
Esempio n. 18
0
void Trainer::set_training_algorithm(const TrainingAlgorithm& algorithm) {
  std::cerr << "Set training algo to " << algorithm.name() << std::endl;
  fann_set_training_algorithm(ann_, algorithm.train_enum());
}
Esempio n. 19
0
struct fann * setup_net(struct fann_train_data * data)
{
	struct fann *ann;
#if MIMO_FANN
#if OPTIMIZE == 0
	ann = fann_create_standard( 3, data->num_input, H_DIM, data->num_output);
	fann_set_activation_function_hidden(ann, FANN_SIGMOID_SYMMETRIC);
	fann_set_activation_function_output(ann, FANN_SIGMOID_SYMMETRIC);
#endif

#if OPTIMIZE == 1
	unsigned int i, j;
	struct fann_descr *descr=(struct fann_descr*) calloc(1, sizeof(struct fann_descr));
	fann_setup_descr(descr, 2, data->num_input);


	i=0;

	fann_setup_layer_descr(
					&(descr->layers_descr[i]),
					"connected_any_any",
					1,
					NULL
					);

		for (j=0; j< descr->layers_descr[i].num_neurons; j++)
		{
						fann_setup_neuron_descr(
							descr->layers_descr[i].neurons_descr+j,
							H_DIM,
							"scalar_rprop_sigmoid_symmetric",
							NULL
							);
		}

	i=1;

	fann_setup_layer_descr(
					&(descr->layers_descr[i]),
					"connected_any_any",
					1,
					NULL
					);

		for (j=0; j< descr->layers_descr[i].num_neurons; j++)
		{
						fann_setup_neuron_descr(
							descr->layers_descr[i].neurons_descr+j,
							data->num_output,
							"scalar_rprop_sigmoid_symmetric",
							NULL
							);
		}
	ann = fann_create_from_descr( descr );
#endif

#if OPTIMIZE >= 2
	{
		unsigned int layers[] = { data->num_input, H_DIM, data->num_output };
		/*char *type;
		asprintf(&type, "%s_%s_%s", vals(implementation), vals(algorithm), vals(activation));*/

		ann = fann_create_standard_array_typed(layer_type, neuron_type, 3,  layers);

	}
#endif
#else /*MIMO_FANN*/

#ifdef SPARSE
	ann = fann_create_sparse( SPARSE, 3, data->num_input, H_DIM, data->num_output);
#else
	ann = fann_create_standard( 3, data->num_input, H_DIM, data->num_output);
#endif
	fann_set_activation_function_hidden(ann, FANN_SIGMOID_SYMMETRIC);
	fann_set_activation_function_output(ann, FANN_SIGMOID_SYMMETRIC);

#endif /*MIMO_FANN*/ 

	fann_set_train_stop_function(ann, FANN_STOPFUNC_BIT);
	fann_set_bit_fail_limit(ann, 0.01f);
	fann_set_activation_steepness_hidden(ann, 1);
	fann_set_activation_steepness_output(ann, 1);

#if INIT_WEIGHTS == 1
	fann_randomize_weights(ann,0,1);
#endif
#if INIT_WEIGHTS == 2
	fann_init_weights(ann, data);
#endif

#ifdef USE_RPROP
	fann_set_training_algorithm(ann, FANN_TRAIN_RPROP);
#else
	fann_set_training_algorithm(ann, FANN_TRAIN_BATCH);
#endif

	return ann;
}
Esempio n. 20
0
int main(int argc, const char* argv[])
{
	
	if (argc < 2) {
    printf("Usage: ./dinneuro filename\n");
    return -1;
	}
	
	//подготавливаем выборки
	if (csv2fann2(argv[1], 59, 50, 100, true)) { printf("Converted\n"); }
	
	//получим данные о количестве входных и выходных параметров
	int *params;
	const char * filename;
	const char * normfilename;
	filename = "data.data";
	//filename = "scaling.data";
	normfilename = "normalized.train";
	params = getparams(filename);
	
    unsigned int num_threads = omp_get_thread_num();
	float error;
	const unsigned int num_input = params[1];
	const unsigned int num_output = params[2];
	//printf("num_input=%d num_output=%d\n", num_input, num_output);
	const unsigned int num_layers = 4;
	//const unsigned int num_neurons_hidden = num_output;
	const unsigned int num_neurons_hidden = 5;
	const float desired_error = (const float) 0.0001;
	const unsigned int max_epochs = 5000;
	const unsigned int epochs_between_reports = 1000;
	struct fann_train_data * data = NULL;
	struct fann *ann = fann_create_standard(num_layers, num_input, num_neurons_hidden, num_neurons_hidden, num_output);
	fann_set_activation_function_hidden(ann, FANN_LINEAR);
	fann_set_activation_function_output(ann, FANN_SIGMOID_SYMMETRIC);
	fann_set_training_algorithm(ann, FANN_TRAIN_RPROP);
	//printf("test\n");
	data = fann_read_train_from_file(filename);
	
	printf("Readed train from %s\n", filename);
	
	fann_set_scaling_params(
		    ann,
			data,
			-1,	/* New input minimum */
			1,	/* New input maximum */
			-1,	/* New output minimum */
			1);	/* New output maximum */

	fann_scale_train( ann, data );
	printf("Scaled\n");
	
	//сохраним нормализованную обучающу выборку в файл
	fann_save_train(data, normfilename);
	printf("Saved scaled file %s\n", normfilename);
	
	unsigned int i;
	printf("Start learning...\n");
	for(i = 1; i <= max_epochs; i++)
	{
		error = num_threads > 1 ? fann_train_epoch_irpropm_parallel(ann, data, num_threads) : fann_train_epoch(ann, data);
		//если ошибка обучения меньше или равно заданной - выходим из цикла обучения
		//if (error <= desired_error) { printf ("Desired error detected. Finishing teaching.\n"); break; }
		//если текущий счетчик делится без остатка на epochs_between_reports - пишем лог
		//if (i % epochs_between_reports == 0) { printf("Epochs     %8d. Current error: %.10f\n", i, error); }
		
	}
	printf("End learning.\n");
	printf("MSE = %f\n", fann_get_MSE(ann));

	//fann_train_on_data(ann, data, max_epochs, epochs_between_reports, desired_error);
	fann_destroy_train( data );
	fann_save(ann, "scaling.net");
	fann_destroy(ann);
	
	//проверка
	printf("Testing...\n");
	fann_type *calc_out;
	//printf("fann_length_train_data=%d\n",fann_length_train_data(data));
	printf("Creating network.\n");
	ann = fann_create_from_file("scaling.net");
	if(!ann)
	{
		printf("Error creating ann --- ABORTING.\n");
		return 0;
	}
	
	//печатаем параметры сети
	//fann_print_connections(ann);
	//fann_print_parameters(ann);
	
	printf("Testing network.\n");
	data = fann_read_train_from_file(filename);
	for(i = 0; i < fann_length_train_data(data); i++)
	{
		fann_reset_MSE(ann);
    	fann_scale_input( ann, data->input[i] );
		calc_out = fann_run( ann, data->input[i] );
		fann_descale_output( ann, calc_out );
		printf("Result %f original %f error %f or %.2f%%\n",
			calc_out[0], data->output[i][0],
			(float) fann_abs(calc_out[0] - data->output[i][0]), (100*(float) fann_abs(calc_out[0] - data->output[i][0]))/(float)calc_out[0]);
	}

	fann_destroy_train( data );
	fann_destroy(ann);

return 0;
}
Esempio n. 21
0
int main(int argc, char **argv)
{
	if(argc < 3)
	{
		printf("Usage: train_net <input.train> <output.net>\n");
		exit(-1);
		
	}
	const unsigned int num_input = 2;
	const unsigned int num_output = 1;
	const unsigned int num_layers = 3;
	const unsigned int num_neurons_hidden = 8;
	const float desired_error = (const float) 0.000042;
	const unsigned int max_epochs = 500000;
	const unsigned int epochs_between_reports = 1000;

	struct fann *ann = fann_create_standard(num_layers, num_input, num_neurons_hidden, num_output);

	fann_set_activation_function_hidden(ann, FANN_SIGMOID_SYMMETRIC);
	fann_set_activation_function_output(ann, FANN_SIGMOID_SYMMETRIC);

// 	fann_set_activation_steepness_hidden(ann, 1);
// 	fann_set_activation_steepness_output(ann, 1);

// 	fann_set_activation_function_hidden(ann, FANN_SIGMOID_SYMMETRIC);
// 	fann_set_activation_function_output(ann, FANN_SIGMOID_SYMMETRIC);

// 	fann_set_train_stop_function(ann, FANN_STOPFUNC_BIT);
 	fann_set_bit_fail_limit(ann, 0.01f);

	fann_set_training_algorithm(ann, FANN_TRAIN_RPROP);


	
	//fann_train_on_file(ann, argv[1], max_epochs, epochs_between_reports, desired_error);

	struct fann_train_data *data;
	data = fann_read_train_from_file(argv[1]);
	fann_init_weights(ann, data);

	printf("Training network on data from %s.\n", argv[1]);
	fann_train_on_data(ann, data, max_epochs, epochs_between_reports, desired_error);

	printf("Testing network. %f\n", fann_test_data(ann, data));

	double error, errorSum = 0;
	unsigned int i = 0, size = fann_length_train_data(data);
	fann_type *calc_out;
	for(i = 0; i < size; i++)
	{
		calc_out = fann_run(ann, data->input[i]);
		error = fann_abs(calc_out[0] - data->output[i][0]) * 1000;
		printf("Distance test (%d dBm,%f%%) -> %f meters, should be %f meters, difference=%f meters\n",
			   (int)(data->input[i][0] * 150 - 150), data->input[i][1], calc_out[0] * 1000, data->output[i][0] * 1000,
			   error);
		errorSum += error;
	}

	printf("Average Error: %f\n", errorSum / size);
	fann_save(ann, argv[2]);

	fann_destroy(ann);

	return 0;
}
Esempio n. 22
0
/***
 * @function rspamd_fann.create_full(params)
 * Creates new neural network with parameters:
 * - `layers` {table/numbers}: table of layers in form: {N1, N2, N3 ... Nn} where N is number of neurons in a layer
 * - `activation_hidden` {string}: activation function type for hidden layers (`tanh` by default)
 * - `activation_output` {string}: activation function type for output layer (`tanh` by default)
 * - `sparsed` {float}: create sparsed ANN, where number is a coefficient for sparsing
 * - `learn` {string}: learning algorithm (quickprop, rprop or incremental)
 * - `randomize` {boolean}: randomize weights (true by default)
 * @return {fann} fann object
 */
static gint
lua_fann_create_full (lua_State *L)
{
#ifndef WITH_FANN
	return 0;
#else
	struct fann *f, **pfann;
	guint nlayers, *layers, i;
	const gchar *activation_hidden = NULL, *activation_output, *learn_alg = NULL;
	gdouble sparsed = 0.0;
	gboolean randomize_ann = TRUE;
	GError *err = NULL;

	if (lua_type (L, 1) == LUA_TTABLE) {
		lua_pushstring (L, "layers");
		lua_gettable (L, 1);

		if (lua_type (L, -1) != LUA_TTABLE) {
			return luaL_error (L, "bad layers attribute");
		}

		nlayers = rspamd_lua_table_size (L, -1);
		if (nlayers < 2) {
			return luaL_error (L, "bad layers attribute");
		}

		layers = g_new0 (guint, nlayers);

		for (i = 0; i < nlayers; i ++) {
			lua_rawgeti (L, -1, i + 1);
			layers[i] = luaL_checknumber (L, -1);
			lua_pop (L, 1);
		}

		lua_pop (L, 1); /* Table */

		if (!rspamd_lua_parse_table_arguments (L, 1, &err,
				"sparsed=N;randomize=B;learn=S;activation_hidden=S;activation_output=S",
				&sparsed, &randomize_ann, &learn_alg, &activation_hidden, &activation_output)) {
			g_free (layers);

			if (err) {
				gint r;

				r = luaL_error (L, "invalid arguments: %s", err->message);
				g_error_free (err);
				return r;
			}
			else {
				return luaL_error (L, "invalid arguments");
			}
		}

		if (sparsed != 0.0) {
			f = fann_create_standard_array (nlayers, layers);
		}
		else {
			f = fann_create_sparse_array (sparsed, nlayers, layers);
		}

		if (f != NULL) {
			pfann = lua_newuserdata (L, sizeof (gpointer));
			*pfann = f;
			rspamd_lua_setclass (L, "rspamd{fann}", -1);
		}
		else {
			g_free (layers);
			return luaL_error (L, "cannot create fann");
		}

		fann_set_activation_function_hidden (f,
				string_to_activation_func (activation_hidden));
		fann_set_activation_function_output (f,
				string_to_activation_func (activation_output));
		fann_set_training_algorithm (f, string_to_learn_alg (learn_alg));

		if (randomize_ann) {
			fann_randomize_weights (f, 0, 1);
		}

		g_free (layers);
	}
	else {
		return luaL_error (L, "bad arguments");
	}

	return 1;
#endif
}
Esempio n. 23
0
int main(int argc,char **argv)
{
    unlink(histfile);
    srand ( time ( NULL ) );
    // printf ( "Reading data.\n" );
    train_data = fann_read_train_from_file ( "train.dat" );
    test_data = fann_read_train_from_file ( "test.dat" );
//   signal ( 2, sig_term );

    //  fann_scale_train_data ( train_data, 0, 1.54 );
    // fann_scale_train_data ( test_data, 0, 1.54 );
    //cln_test_data=fann_duplicate_train_data(test_data);
    cln_train_data=fann_duplicate_train_data(train_data);


    printf ( "Creating cascaded network.\n" );
    ann =
        fann_create_shortcut ( 2, fann_num_input_train_data ( train_data ),
                               fann_num_output_train_data ( train_data ) );
    fann_set_training_algorithm ( ann, FANN_TRAIN_RPROP );
    fann_set_activation_function_hidden ( ann, FANN_SIGMOID );
    fann_set_activation_function_output ( ann, FANN_SIGMOID);
    fann_set_train_error_function ( ann, FANN_ERRORFUNC_LINEAR );

    //  if (fann_set_scaling_params(ann, train_data,-1.0f,1.0f,0.0f, 1.0f)==-1)
    //    printf("set scaling error: %s\n",fann_get_errno((struct fann_error*)ann));

    //    fann_scale_train_input(ann,train_data);
    // fann_scale_output_train_data(train_data,0.0f,1.0f);
//	   fann_scale_input_train_data(train_data, -1.0,1.0f);
    // fann_scale_output_train_data(test_data,-1.0f,1.0f);
    // fann_scale_input_train_data(test_data, -1.0,1.0f);
//fann_scale_train(ann,train_data);
    //  fann_scale_train(ann,weight_data);
    //  fann_scale_train(ann,test_data);
    /*
     * fann_set_cascade_output_change_fraction(ann, 0.1f);
     *  ;
     * fann_set_cascade_candidate_change_fraction(ann, 0.1f);
     *
     */


    //  fann_set_cascade_output_stagnation_epochs ( ann, 180 );

    //fann_set_cascade_weight_multiplier ( ann, ( fann_type ) 0.1f );


    fann_set_callback ( ann, cascade_callback );
    if ( !multi )
    {

        /*  */
        //  steepness[0] = 0.22;
        steepness[0] = 0.9;
        steepness[1] = 1.0;

        /*
         * steepness[1] = 0.55;
         *  ;
         * steepness[1] = 0.33;
         *  ;
         * steepness[3] = 0.11;
         *  ;
         * steepness[1] = 0.01;
         *
         */

        /*
         *  steepness = 0.5;
         *
         */
        // fann_set_cascade_activation_steepnesses ( ann, steepness, 2);

        /*
         * activation = FANN_SIN_SYMMETRIC;
         */

        /*
         * activation[0] = FANN_SIGMOID;
         *
         */
        activation[0] = FANN_SIGMOID;

        /*
         * activation[2] = FANN_ELLIOT_SYMMETRIC;
         *
         */
        activation[1] = FANN_LINEAR_PIECE;

        /*
         * activation[4] = FANN_GAUSSIAN_SYMMETRIC;
         *  ;
         * activation[5] = FANN_SIGMOID;
         *
         */
        activation[2] = FANN_ELLIOT;
        activation[3] = FANN_COS;
        /*
         *
         *
         */
        activation[4] = FANN_SIN;
        fann_set_cascade_activation_functions ( ann, activation, 5);
        /*   fann_set_cascade_num_candidate_groups ( ann,
                                                  fann_num_input_train_data
                                                  ( train_data ) ); */

    }
    else
    {

        /*
         * fann_set_cascade_activation_steepnesses(ann, &steepness, 0.75);
         *
         */
        // fann_set_cascade_num_candidate_groups ( ann, 1 );

    }

    /* TODO: weight mult > 0.01 */
    /*  if ( training_algorithm == FANN_TRAIN_QUICKPROP )
      {
          fann_set_learning_rate ( ann, 0.35f );


      }
      else
      {
          fann_set_learning_rate ( ann, 0.7f );

      }
      fann_set_bit_fail_limit ( ann, ( fann_type ) 0.9f );*/

    /*
     * fann_set_train_stop_function(ann, FANN_STOPFUNC_BIT);
     *
     */

    //fann_scale_output_train_data(train_data,0.0f,1.0f);
    //fann_scale_input_train_data(train_data, -1.0f,1.0f);
//	fann_scale_output_train_data(test_data, 0.0f,1.0f);
    //fann_scale_input_train_data(test_data, -1.0f,1.0f);

    // fann_randomize_weights ( ann, -0.2f, 0.2f );
    fann_init_weights ( ann, train_data );



    printf ( "Training network.\n" );
    fann_cascadetrain_on_data ( ann, train_data, max_neurons,
                                1, desired_error );
    fann_print_connections ( ann );
    mse_train = fann_test_data ( ann, train_data );
    bit_fail_train = fann_get_bit_fail ( ann );
    mse_test = fann_test_data ( ann, test_data );
    bit_fail_test = fann_get_bit_fail ( ann );
    printf
    ( "\nTrain error: %.08f, Train bit-fail: %d, Test error: %.08f, Test bit-fail: %d\n\n",
      mse_train, bit_fail_train, mse_test, bit_fail_test );

    printf ( "Saving cascaded network.\n" );
    fann_save ( ann, "cascaded.net" );
    //  printf ( "Cleaning up.\n" );
    fann_destroy_train ( train_data );
    fann_destroy_train ( test_data );
    fann_destroy ( ann );
    return 0;

}
Esempio n. 24
0
int main()
{
	struct fann *ann;
	struct fann_train_data *train_data, *test_data;
	const float desired_error = (const float)0.0;
	unsigned int max_neurons = 30;
	unsigned int neurons_between_reports = 1;
	unsigned int bit_fail_train, bit_fail_test;
	float mse_train, mse_test;
	unsigned int i = 0;
	fann_type *output;
	fann_type steepness;
	int multi = 0;
	enum fann_activationfunc_enum activation;
	enum fann_train_enum training_algorithm = FANN_TRAIN_RPROP;
	
	printf("Reading data.\n");
	 
	train_data = fann_read_train_from_file("../benchmarks/datasets/parity8.train");
	test_data = fann_read_train_from_file("../benchmarks/datasets/parity8.test");

	fann_scale_train_data(train_data, -1, 1);
	fann_scale_train_data(test_data, -1, 1);
	
	printf("Creating network.\n");
	
	ann = fann_create_shortcut(2, fann_num_input_train_data(train_data), fann_num_output_train_data(train_data));
		
	fann_set_training_algorithm(ann, training_algorithm);
	fann_set_activation_function_hidden(ann, FANN_SIGMOID_SYMMETRIC);
	fann_set_activation_function_output(ann, FANN_LINEAR);
	fann_set_train_error_function(ann, FANN_ERRORFUNC_LINEAR);
	
	if(!multi)
	{
		/*steepness = 0.5;*/
		steepness = 1;
		fann_set_cascade_activation_steepnesses(ann, &steepness, 1);
		/*activation = FANN_SIN_SYMMETRIC;*/
		activation = FANN_SIGMOID_SYMMETRIC;
		
		fann_set_cascade_activation_functions(ann, &activation, 1);		
		fann_set_cascade_num_candidate_groups(ann, 8);
	}	
		
	if(training_algorithm == FANN_TRAIN_QUICKPROP)
	{
		fann_set_learning_rate(ann, 0.35);
		fann_randomize_weights(ann, -2.0,2.0);
	}
	
	fann_set_bit_fail_limit(ann, 0.9);
	fann_set_train_stop_function(ann, FANN_STOPFUNC_BIT);
	fann_print_parameters(ann);
		
	fann_save(ann, "cascade_train2.net");
	
	printf("Training network.\n");

	fann_cascadetrain_on_data(ann, train_data, max_neurons, neurons_between_reports, desired_error);
	
	fann_print_connections(ann);
	
	mse_train = fann_test_data(ann, train_data);
	bit_fail_train = fann_get_bit_fail(ann);
	mse_test = fann_test_data(ann, test_data);
	bit_fail_test = fann_get_bit_fail(ann);
	
	printf("\nTrain error: %f, Train bit-fail: %d, Test error: %f, Test bit-fail: %d\n\n", 
		   mse_train, bit_fail_train, mse_test, bit_fail_test);
	
	for(i = 0; i < train_data->num_data; i++)
	{
		output = fann_run(ann, train_data->input[i]);
		if((train_data->output[i][0] >= 0 && output[0] <= 0) ||
		   (train_data->output[i][0] <= 0 && output[0] >= 0))
		{
			printf("ERROR: %f does not match %f\n", train_data->output[i][0], output[0]);
		}
	}
	
	printf("Saving network.\n");
	
	fann_save(ann, "cascade_train.net");
	
	printf("Cleaning up.\n");
	fann_destroy_train(train_data);
	fann_destroy_train(test_data);
	fann_destroy(ann);
	
	return 0;
}
Esempio n. 25
0
int main ( int argc, char **argv )
{
    srand(time(NULL));
    if ( argc<=1 )
    {
        //      printf ( "neuro num\r\n" );
        //     exit ( 0 );
    }

    if (argc>2)
    {
        //desired_error=atof(argv[2]);
        numn=atoi(argv[1]);
        l1n=atoi(argv[2]);
        if (argc>3)
            l2n=atoi(argv[3]);
        if (argc>4)
            l3n=atoi(argv[4]);
        if (argc>5)
            l4n=atoi(argv[5]);
        if (argc>6)
            l5n=atoi(argv[6]);
        if (argc>7)
            l6n=atoi(argv[7]);
    }

    signal ( 2, sig_term );



    srand ( time ( NULL ) );

    printf("loading training data...");

    train_data = fann_read_train_from_file ( "train.dat" );
    test_data = fann_read_train_from_file ( "test.dat" );

    weight_data=fann_merge_train_data(train_data,test_data);

    cln_weight_data=fann_duplicate_train_data(weight_data);
    cln_test_data=fann_duplicate_train_data(test_data);
    cln_train_data=fann_duplicate_train_data(train_data);

    //num_neurons_hidden = atoi ( argv[1] );



    srand(time(NULL));

    y=atoi(argv[2]);

    lay=atoi(argv[1]);
    ln=lay+2;
    if (lay==1)
        y2=train_data->num_output;
    best_perc=1;

    printf("\r\ndoing %ux%u [layers=%u,out=%u]",lay,y,ln, train_data->num_output);
    while (true)

    {
        neur1=1+(rand()%y);
        neur2=1+(rand()%y);
        conn_rate=0.5f+((rand()%50)*0.01f);
        printf("\r\n%2dx%-4d: ",neur1,neur2);
        //  printf("create network: layers=%d l1n=%d l2n=%d l3n=%d l4n=%d\ l5n=%d l6n=%dr\n",numn,l1n,l2n,l3n,l4n,l5n,l6n);
        ann = fann_create_standard (//conn_rate,
                  ln,
                  train_data->num_input,
                  neur1,
                  neur2,
                  train_data->num_output );
        //fann_init_weights ( ann, train_data );
        printf(" [%p] ",ann);

        if ( ( int ) ann==NULL )
        {
            printf ( "error" );
            exit ( 0 );
        }



        fann_set_activation_function_hidden(ann,FANN_SIGMOID);
        fann_set_activation_function_output(ann,FANN_SIGMOID);

        rebuild_functions(neur1);
        fann_set_training_algorithm ( ann, FANN_TRAIN_RPROP );
        fann_set_sarprop_temperature(ann,15000.0f);
        //fann_randomize_weights ( ann, -((rand()%10)*0.1f), ((rand()%10)*0.1f) );
        fann_init_weights(ann,train_data);
        got_inc=0;
        prev_epoch_mse=1;
        //
        epochs=0;

        unsigned last_best_perc_epoch=0;
        unsigned last_sync_epoch=0;
        unsigned last_ftest_secs=0;

        last_sync_epoch=0;
        last_best_perc_epoch=0;
        if (good_ann)
            fann_destroy(good_ann);

        good_ann=fann_copy(ann);
        unlink(histfile);
        for (u=0;u<1000;u++)
        {
            fflush(NULL);
            train_mse=fann_train_epoch(ann, train_data);

            if (jitter_train)
                apply_jjit(train_data,cln_train_data);


            if (time(NULL)-last_ftest_secs>=1)
            {
                //printf("\r\n%5u %9.6f %5.2f ",epochs,train_mse,test_perc);
                //printf(" %4.2f",test_perc);
                printf(".");


                last_ftest_secs=time(NULL);
            }
            ftest_data();
            plot(epochs,train_mse,test_mse);

            /*         if (epochs>10&&((int)test_perc==43||(int)test_perc==57))
                    {
                        printf(" [excluded %.2f] ",test_perc);
                        break;
                    }            else            {

                    } */
            //printf("excluded %f ",test_perc);

            double prev_test_perc;
            //   if (prev_epoch_mse==best_perc)
            //  printf("o");
            if ((int)test_perc>(int)train_perc&&epochs-last_stat_epoch>10)
            {
                fann_destroy(good_ann);
                good_ann=fann_copy(ann);

                if (test_perc!=prev_test_perc)
                    printf("%.2f [%f]",test_perc,train_mse);

                //printf(" sync[%4.2f]",test_perc);
                last_stat_epoch=epochs;
            }
            else 	if (epochs-last_sync_epoch>111500)
            {
                last_sync_epoch=epochs;
            }
            if (epochs>210&&test_perc>best_perc)
            {
                //	u--;
                //  fann_destroy(good_ann);
                //   good_ann=fann_copy(ann);
                printf(" [saved best %.0f] ",test_perc);
                last_stat_epoch=epochs;
                //		printf("%f",test_perc);
                //	fann_destroy(ann);
                //	ann=fann_copy(good_ann);
                fann_save(ann,"mutate-best.net");
                best_perc=test_perc;
                printf(" %6.2f [%f]",test_perc,train_mse);
                last_best_perc_epoch=epochs;

            }
            else     if (epochs>11100&&((int)test_perc<=63||(int)test_perc==(int)prev_test_perc))
            {
                //best_perc=test_perc;
                //		printf("x");
                //  printf(".");
                //printf("\r%6.8f",train_mse);
                //			printf("done\r\n");
                break;


            }
            static unsigned last_restore_epoch=0;
            if (epochs>100&&test_mse-train_mse>=0.25f&&epochs-last_restore_epoch>=120)
            {
                /* 	fann_set_learning_rate ( ann,0.31f+(rand()%90)*0.01f);
                	fann_set_learning_momentum(ann,(rand()%90)*0.01f);
                	printf(" [restored @ %u lr %.2f mm %.2f]",epochs,fann_get_learning_rate(ann),
                	fann_get_learning_momentum(ann));
                	fann_destroy(ann);
                	ann=fann_copy(good_ann);
                	last_stat_epoch=epochs;
                	last_restore_epoch=epochs; */





                double rdec,rinc;
                rdec=0.0101f+((rand()%100)*0.00001f);
                if (!rdec)
                    rdec=0.01f;
                rinc=1.0001f+((rand()%90)*0.00001f);
                if (!rinc)
                    rinc=1.1f;
                static double prev_test_epoch_mse;

                //		rinc+=diff_mse*0.000001f;
                //			fann_set_rprop_increase_factor(ann,rinc );
                //	fann_set_rprop_decrease_factor(ann, rdec);
            }
            else if (test_mse-train_mse<=0.1f)
            {
                fann_destroy(good_ann);
                good_ann=fann_copy(ann);
                //	printf("s");
            }
            else
            {
                fann_set_sarprop_temperature(ann,fann_get_sarprop_temperature(ann)-0.0001f);
            }
            static unsigned last_train_change_epoch=0;
            if (test_mse>=train_mse&&epochs-last_train_change_epoch>=100)
            {
                last_train_change_epoch=epochs;
                //fann_set_training_algorithm(ann,FANN_TRAIN_SARPROP);
                jitter_train=0;
            }
            else
            {
                //fann_set_training_algorithm(ann,FANN_TRAIN_RPROP);
                jitter_train=0;
            }

            got_inc=test_perc-prev_epoch_mse;
            prev_epoch_mse=test_perc;
            prev_test_perc=test_perc;
            epochs++;
            if (epochs-last_best_perc_epoch>511500)
            {
                printf(" failed");
                break;
            }
            if (epochs>2200&&(int)train_perc<40)
            {
                printf("skip 1\r\n");
                break;
            }

            if ((int)test_perc>=80)
            {
                printf("\r\ngot it %f\r\n",test_perc);
                fann_save(ann,"good.net");
                exit(0);
            }
            // printf("\n%6u ",epochs);
        }
        printf(" %6.2f inc: %.2f",test_perc,got_inc);
//            printf("%6.2f %6.2f",train_perc,test_perc);

        fann_destroy ( ann );

    }

    fann_destroy_train ( train_data );
    fann_destroy_train ( test_data );
    fann_destroy ( ann );

    return 0;
}
Esempio n. 26
0
int main(int argc, char *argv[])
{
	struct fann_train_data *dadosTreino, *dadosTeste;
	struct fann *ANN;
	fann_type *ANN_Answers;

	int *layers, i, j, aux;
	chromosome chromo;

	float erro = 0.0;

	checkArgs(argc, argv);
	buildChromosome(argv, &chromo);

	checkDatasetFiles();

	dadosTreino = fann_read_train_from_file(nomeArqTreino);

	layers = (int *) calloc(2+chromo.qntCamadasOcultas, sizeof(int));
	layers[0] = qntNeuroniosEntrada;
	layers[2+chromo.qntCamadasOcultas-1] = qntNeuroniosSaida;
	aux = chromo.neurOcultos;
	for (i=1; i < 2+chromo.qntCamadasOcultas-1 ; i++)
	{
		layers[i] = aux;
		aux = aux/2;
	}

	// CRIANDO A RNA:
	ANN = fann_create_standard_array(2+chromo.qntCamadasOcultas, layers);

	// TREINO
	fann_set_learning_rate(ANN, chromo.learnRate);
	fann_set_learning_momentum(ANN, chromo.moment);

	fann_set_activation_function_hidden( ANN, chromo.fcOculta );
	fann_set_activation_function_output( ANN, chromo.fcSaida  );
	fann_set_training_algorithm(ANN, chromo.algAprend );

	if (fann_get_training_algorithm(ANN) == FANN_TRAIN_QUICKPROP)
		fann_set_quickprop_decay(ANN, chromo.decay);

	// Em python, o treino ficava entre um try.
	// Se desse erro, escrevia "Resultado: 999.0" e exit
	fann_train_on_data(ANN, dadosTreino, chromo.epocasTreino, 50, desiredError);

	fann_destroy_train(dadosTreino);

	// TESTES:
	dadosTeste  = fann_read_train_from_file( nomeArqValidacao);

	// Em python, o teste também ficava entre um try.
	// Se desse erro, escrevia "Resultado: 999.0" e exit
	for(i = 0; i < fann_length_train_data(dadosTeste); i++)
	{
		ANN_Answers = fann_run(ANN, dadosTeste->input[i]);
		if (ANN_Answers == NULL)
		{
			printf("Resultado: 999.0\n");
			exit(2);
		}

		for (j=0; j < qntNeuroniosSaida; j++)
			erro += (float) powf(fann_abs(ANN_Answers[j] - dadosTeste->output[i][j]), 2);
	}
	printf("Resultado: %f\n", erro/(fann_length_train_data(dadosTeste)-1));

	fann_destroy_train(dadosTeste);

	saveANN(argc, argv, ANN);

	fann_destroy(ANN);
}