Debian Codegraph @

src/algorithms/myfann_cpp.h

raw symbols SCIP
1 #ifndef FANN_CPP_H_INCLUDED
2 #define FANN_CPP_H_INCLUDED
3
4 /*
5 *
6 * Fast Artificial Neural Network (fann) C++ Wrapper
7 * Copyright (C) 2004-2006 created by freegoldbar (at) yahoo dot com
8 *
9 * This wrapper is free software; you can redistribute it and/or
10 * modify it under the terms of the GNU Lesser General Public
11 * License as published by the Free Software Foundation; either
12 * version 2.1 of the License, or (at your option) any later version.
13 *
14 * This wrapper is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
17 * Lesser General Public License for more details.
18 *
19 * You should have received a copy of the GNU Lesser General Public
20 * License along with this library; if not, write to the Free Software
21 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
22 *
23 */
24
25 /*
26 * Title: FANN Wrapper for C++
27 *
28 * Overview:
29 *
30 * The Fann Wrapper for C++ provides two classes: <neural_net>
31 * and <training_data>. To use the wrapper include
32 * doublefann.h, floatfann.h or fixedfann.h before the
33 * fann_cpp.h header file. To get started see xor_sample.cpp
34 * in the examples directory. The license is LGPL. Copyright (C)
35 * 2004-2006 created by <[email protected]>.
36 *
37 * Note: Notes and differences from C API
38 *
39 * - The Fann Wrapper for C++ is a minimal wrapper without use of
40 * templates or exception handling for efficient use in any environment.
41 * Benefits include stricter type checking, simpler memory
42 * management and possibly code completion in program editor.
43 * - Method names are the same as the function names in the C
44 * API except the fann_ prefix has been removed. Enums in the
45 * namespace are similarly defined without the FANN_ prefix.
46 * - The arguments to the methods are the same as the C API
47 * except that the struct fann *ann/struct fann_train_data *data
48 * arguments are encapsulated so they are not present in the
49 * method signatures or are translated into class references.
50 * - The various create methods return a boolean set to true to
51 * indicate that the neural network was created, false otherwise.
52 * The same goes for the read_train_from_file method.
53 * - The neural network and training data is automatically cleaned
54 * up in the destructors and create/read methods.
55 * - To make the destructors virtual define USE_VIRTUAL_DESTRUCTOR
56 * before including the header file.
57 * - Additional methods are available on the training_data class to
58 * give access to the underlying training data. They are get_input,
59 * get_output and set_train_data. Finally fann_duplicate_train_data
60 * has been replaced by a copy constructor.
61 *
62 * Note: Changes
63 *
64 * Version myfann_cpp.h: [email protected]
65 * - support of stl::vector data type
66 * - custom serialization of SVM model create_from_file and save
67 * Version 2.1.0:
68 * - General update to fann C library 2.1.0 with support for new functionality
69 * - Due to changes in the C API the C++ API is not fully backward compatible:
70 * The create methods have changed names and parameters.
71 * The training callback function has different parameters and a set_callback.
72 * Some <training_data> methods have updated names.
73 * Get activation function and steepness is available for neurons, not layers.
74 * - Extensions are now part of fann so there is no fann_extensions.h
75 *
76 * Version 1.2.0:
77 * - Changed char pointers to const std::string references
78 * - Added const_casts where the C API required it
79 * - Initialized enums from the C enums instead of numeric constants
80 * - Added a method set_train_data that copies and allocates training
81 * - data in a way that is compatible with the way the C API deallocates
82 * - the data thus making it possible to change training data.
83 * - The get_rprop_increase_factor method did not return its value
84 *
85 * Version 1.0.0:
86 * - Initial version
87 *
88 */
89
90 #include <iostream>
91 #include <stdarg.h>
92 #include <string>
93 #include <iostream>
94 #include <fstream>
95 #include <vector>
96 #include <map>
97 #include <cassert>
98 #include "base/Vector2d.h"
99 #include "config_jiplib.h"
100
101 /* Namespace: FANN
102 The FANN namespace groups the C++ wrapper definitions */
103 namespace FANN
104 {
105 /* Enum: error_function_enum
106 Error function used during training.
107
108 ERRORFUNC_LINEAR - Standard linear error function.
109 ERRORFUNC_TANH - Tanh error function, usually better
110 but can require a lower learning rate. This error function agressively targets outputs that
111 differ much from the desired, while not targetting outputs that only differ a little that much.
112 This activation function is not recommended for cascade training and incremental training.
113
114 See also:
115 <neural_net::set_train_error_function>, <neural_net::get_train_error_function>
116 */
117 enum error_function_enum {
118 ERRORFUNC_LINEAR = FANN_ERRORFUNC_LINEAR,
119 ERRORFUNC_TANH
120 };
121
122 /* Enum: stop_function_enum
123 Stop criteria used during training.
124
125 STOPFUNC_MSE - Stop criteria is Mean Square Error (MSE) value.
126 STOPFUNC_BIT - Stop criteria is number of bits that fail. The number of bits; means the
127 number of output neurons which differ more than the bit fail limit
128 (see <neural_net::get_bit_fail_limit>, <neural_net::set_bit_fail_limit>).
129 The bits are counted in all of the training data, so this number can be higher than
130 the number of training data.
131
132 See also:
133 <neural_net::set_train_stop_function>, <neural_net::get_train_stop_function>
134 */
135 enum stop_function_enum
136 {
137 STOPFUNC_MSE = FANN_STOPFUNC_MSE,
138 STOPFUNC_BIT
139 };
140
141 /* Enum: training_algorithm_enum
142 The Training algorithms used when training on <training_data> with functions like
143 <neural_net::train_on_data> or <neural_net::train_on_file>. The incremental training
144 looks alters the weights after each time it is presented an input pattern, while batch
145 only alters the weights once after it has been presented to all the patterns.
146
147 TRAIN_INCREMENTAL - Standard backpropagation algorithm, where the weights are
148 updated after each training pattern. This means that the weights are updated many
149 times during a single epoch. For this reason some problems, will train very fast with
150 this algorithm, while other more advanced problems will not train very well.
151 TRAIN_BATCH - Standard backpropagation algorithm, where the weights are updated after
152 calculating the mean square error for the whole training set. This means that the weights
153 are only updated once during a epoch. For this reason some problems, will train slower with
154 this algorithm. But since the mean square error is calculated more correctly than in
155 incremental training, some problems will reach a better solutions with this algorithm.
156 TRAIN_RPROP - A more advanced batch training algorithm which achieves good results
157 for many problems. The RPROP training algorithm is adaptive, and does therefore not
158 use the learning_rate. Some other parameters can however be set to change the way the
159 RPROP algorithm works, but it is only recommended for users with insight in how the RPROP
160 training algorithm works. The RPROP training algorithm is described by
161 [Riedmiller and Braun, 1993], but the actual learning algorithm used here is the
162 iRPROP- training algorithm which is described by [Igel and Husken, 2000] which
163 is an variety of the standard RPROP training algorithm.
164 TRAIN_QUICKPROP - A more advanced batch training algorithm which achieves good results
165 for many problems. The quickprop training algorithm uses the learning_rate parameter
166 along with other more advanced parameters, but it is only recommended to change these
167 advanced parameters, for users with insight in how the quickprop training algorithm works.
168 The quickprop training algorithm is described by [Fahlman, 1988].
169
170 See also:
171 <neural_net::set_training_algorithm>, <neural_net::get_training_algorithm>
172 */
173 enum training_algorithm_enum {
174 TRAIN_INCREMENTAL = FANN_TRAIN_INCREMENTAL,
175 TRAIN_BATCH,
176 TRAIN_RPROP,
177 TRAIN_QUICKPROP
178 };
179
180 /* Enum: activation_function_enum
181
182 The activation functions used for the neurons during training. The activation functions
183 can either be defined for a group of neurons by <neural_net::set_activation_function_hidden>
184 and <neural_net::set_activation_function_output> or it can be defined for a single neuron by
185 <neural_net::set_activation_function>.
186
187 The steepness of an activation function is defined in the same way by
188 <neural_net::set_activation_steepness_hidden>, <neural_net::set_activation_steepness_output>
189 and <neural_net::set_activation_steepness>.
190
191 The functions are described with functions where:
192 * x is the input to the activation function,
193 * y is the output,
194 * s is the steepness and
195 * d is the derivation.
196
197 FANN_LINEAR - Linear activation function.
198 * span: -inf < y < inf
199 * y = x*s, d = 1*s
200 * Can NOT be used in fixed point.
201
202 FANN_THRESHOLD - Threshold activation function.
203 * x < 0 -> y = 0, x >= 0 -> y = 1
204 * Can NOT be used during training.
205
206 FANN_THRESHOLD_SYMMETRIC - Threshold activation function.
207 * x < 0 -> y = 0, x >= 0 -> y = 1
208 * Can NOT be used during training.
209
210 FANN_SIGMOID - Sigmoid activation function.
211 * One of the most used activation functions.
212 * span: 0 < y < 1
213 * y = 1/(1 + exp(-2*s*x))
214 * d = 2*s*y*(1 - y)
215
216 FANN_SIGMOID_STEPWISE - Stepwise linear approximation to sigmoid.
217 * Faster than sigmoid but a bit less precise.
218
219 FANN_SIGMOID_SYMMETRIC - Symmetric sigmoid activation function, aka. tanh.
220 * One of the most used activation functions.
221 * span: -1 < y < 1
222 * y = tanh(s*x) = 2/(1 + exp(-2*s*x)) - 1
223 * d = s*(1-(y*y))
224
225 FANN_SIGMOID_SYMMETRIC - Stepwise linear approximation to symmetric sigmoid.
226 * Faster than symmetric sigmoid but a bit less precise.
227
228 FANN_GAUSSIAN - Gaussian activation function.
229 * 0 when x = -inf, 1 when x = 0 and 0 when x = inf
230 * span: 0 < y < 1
231 * y = exp(-x*s*x*s)
232 * d = -2*x*s*y*s
233
234 FANN_GAUSSIAN_SYMMETRIC - Symmetric gaussian activation function.
235 * -1 when x = -inf, 1 when x = 0 and 0 when x = inf
236 * span: -1 < y < 1
237 * y = exp(-x*s*x*s)*2-1
238 * d = -2*x*s*(y+1)*s
239
240 FANN_ELLIOT - Fast (sigmoid like) activation function defined by David Elliott
241 * span: 0 < y < 1
242 * y = ((x*s) / 2) / (1 + |x*s|) + 0.5
243 * d = s*1/(2*(1+|x*s|)*(1+|x*s|))
244
245 FANN_ELLIOT_SYMMETRIC - Fast (symmetric sigmoid like) activation function defined by David Elliott
246 * span: -1 < y < 1
247 * y = (x*s) / (1 + |x*s|)
248 * d = s*1/((1+|x*s|)*(1+|x*s|))
249
250 FANN_LINEAR_PIECE - Bounded linear activation function.
251 * span: 0 < y < 1
252 * y = x*s, d = 1*s
253
254 FANN_LINEAR_PIECE_SYMMETRIC - Bounded Linear activation function.
255 * span: -1 < y < 1
256 * y = x*s, d = 1*s
257
258 FANN_SIN_SYMMETRIC - Periodical sinus activation function.
259 * span: -1 <= y <= 1
260 * y = sin(x*s)
261 * d = s*cos(x*s)
262
263 FANN_COS_SYMMETRIC - Periodical cosinus activation function.
264 * span: -1 <= y <= 1
265 * y = cos(x*s)
266 * d = s*-sin(x*s)
267
268 See also:
269 <neural_net::set_activation_function_hidden>,
270 <neural_net::set_activation_function_output>
271 */
272 enum activation_function_enum {
273 LINEAR = FANN_LINEAR,
274 THRESHOLD,
275 THRESHOLD_SYMMETRIC,
276 SIGMOID,
277 SIGMOID_STEPWISE,
278 SIGMOID_SYMMETRIC,
279 SIGMOID_SYMMETRIC_STEPWISE,
280 GAUSSIAN,
281 GAUSSIAN_SYMMETRIC,
282 GAUSSIAN_STEPWISE,
283 ELLIOT,
284 ELLIOT_SYMMETRIC,
285 LINEAR_PIECE,
286 LINEAR_PIECE_SYMMETRIC,
287 SIN_SYMMETRIC,
288 COS_SYMMETRIC
289 };
290
291 /* Enum: network_type_enum
292
293 Definition of network types used by <neural_net::get_network_type>
294
295 LAYER - Each layer only has connections to the next layer
296 SHORTCUT - Each layer has connections to all following layers
297
298 See Also:
299 <neural_net::get_network_type>, <fann_get_network_type>
300
301 This enumeration appears in FANN >= 2.1.0
302 */
303 enum network_type_enum
304 {
305 LAYER = FANN_NETTYPE_LAYER,
306 SHORTCUT
307 };
308
309 /* Type: connection
310
311 Describes a connection between two neurons and its weight
312
313 from_neuron - Unique number used to identify source neuron
314 to_neuron - Unique number used to identify destination neuron
315 weight - The numerical value of the weight
316
317 See Also:
318 <neural_net::get_connection_array>, <neural_net::set_weight_array>
319
320 This structure appears in FANN >= 2.1.0
321 */
322 typedef struct fann_connection connection;
323
324 /* Forward declaration of class neural_net and training_data */
325 class neural_net;
326 class training_data;
327
328 /* Type: callback_type
329 This callback function can be called during training when using <neural_net::train_on_data>,
330 <neural_net::train_on_file> or <neural_net::cascadetrain_on_data>.
331
332 >typedef int (*callback_type) (neural_net &net, training_data &train,
333 > unsigned int max_epochs, unsigned int epochs_between_reports,
334 > float desired_error, unsigned int epochs, void *user_data);
335
336 The callback can be set by using <neural_net::set_callback> and is very usefull for doing custom
337 things during training. It is recommended to use this function when implementing custom
338 training procedures, or when visualizing the training in a GUI etc. The parameters which the
339 callback function takes is the parameters given to the <neural_net::train_on_data>, plus an epochs
340 parameter which tells how many epochs the training have taken so far.
341
342 The callback function should return an integer, if the callback function returns -1, the training
343 will terminate.
344
345 Example of a callback function that prints information to cout:
346 >int print_callback(FANN::neural_net &net, FANN::training_data &train,
347 > unsigned int max_epochs, unsigned int epochs_between_reports,
348 > float desired_error, unsigned int epochs, void *user_data)
349 >{
350 > cout << "Epochs " << setw(8) << epochs << ". "
351 > << "Current Error: " << left << net.get_MSE() << right << endl;
352 > return 0;
353 >}
354
355 See also:
356 <neural_net::set_callback>, <fann_callback_type>
357 */
358 typedef int (*callback_type) (neural_net &net, training_data &train,
359 unsigned int max_epochs, unsigned int epochs_between_reports,
360 float desired_error, unsigned int epochs, void *user_data);
361
362 /*************************************************************************/
363
364 /* Class: training_data
365
366 Encapsulation of a training data set <struct fann_train_data> and
367 associated C API functions.
368 */
369 class training_data
370 {
371 public:
372 /* Constructor: training_data
373
374 Default constructor creates an empty neural net.
375 Use <read_train_from_file>, <set_train_data> or <create_train_from_callback> to initialize.
376 */
377 training_data() : train_data(NULL)
378 {
379 }
380
381 /* Constructor: training_data
382
383 Copy constructor constructs a copy of the training data.
384 Corresponds to the C API <fann_duplicate_train_data> function.
385 */
386 training_data(const training_data &data)
387 {
388 destroy_train();
389 if (data.train_data != NULL)
390 {
391 train_data = fann_duplicate_train_data(data.train_data);
392 }
393 }
394
395 /* Destructor: ~training_data
396
397 Provides automatic cleanup of data.
398 Define USE_VIRTUAL_DESTRUCTOR if you need the destructor to be virtual.
399
400 See also:
401 <destroy>
402 */
403 #ifdef USE_VIRTUAL_DESTRUCTOR
404 virtual
405 #endif
406 ~training_data()
407 {
408 destroy_train();
409 }
410
411 /* Method: destroy
412
413 Destructs the training data. Called automatically by the destructor.
414
415 See also:
416 <~training_data>
417 */
418 void destroy_train()
419 {
420 if (train_data != NULL)
421 {
422 fann_destroy_train(train_data);
423 train_data = NULL;
424 }
425 }
426
427 /* Method: read_train_from_file
428 Reads a file that stores training data.
429
430 The file must be formatted like:
431 >num_train_data num_input num_output
432 >inputdata seperated by space
433 >outputdata seperated by space
434 >
435 >.
436 >.
437 >.
438 >
439 >inputdata seperated by space
440 >outputdata seperated by space
441
442 See also:
443 <neural_net::train_on_data>, <save_train>, <fann_read_train_from_file>
444
445 This function appears in FANN >= 1.0.0
446 */
447 bool read_train_from_file(const std::string &filename)
448 {
449 destroy_train();
450 train_data = fann_read_train_from_file(filename.c_str());
451 return (train_data != NULL);
452 }
453
454 /* Method: save_train
455
456 Save the training structure to a file, with the format as specified in <read_train_from_file>
457
458 Return:
459 The function returns true on success and false on failure.
460
461 See also:
462 <read_train_from_file>, <save_train_to_fixed>, <fann_save_train>
463
464 This function appears in FANN >= 1.0.0.
465 */
466 bool save_train(const std::string &filename)
467 {
468 if (train_data == NULL)
469 {
470 return false;
471 }
472 if (fann_save_train(train_data, filename.c_str()) == -1)
473 {
474 return false;
475 }
476 return true;
477 }
478
479 /* Method: save_train_to_fixed
480
481 Saves the training structure to a fixed point data file.
482
483 This function is very usefull for testing the quality of a fixed point network.
484
485 Return:
486 The function returns true on success and false on failure.
487
488 See also:
489 <save_train>, <fann_save_train_to_fixed>
490
491 This function appears in FANN >= 1.0.0.
492 */
493 bool save_train_to_fixed(const std::string &filename, unsigned int decimal_point)
494 {
495 if (train_data == NULL)
496 {
497 return false;
498 }
499 if (fann_save_train_to_fixed(train_data, filename.c_str(), decimal_point) == -1)
500 {
501 return false;
502 }
503 return true;
504 }
505
506 /* Method: shuffle_train_data
507
508 Shuffles training data, randomizing the order.
509 This is recommended for incremental training, while it have no influence during batch training.
510
511 This function appears in FANN >= 1.1.0.
512 */
513 void shuffle_train_data()
514 {
515 if (train_data != NULL)
516 {
517 fann_shuffle_train_data(train_data);
518 }
519 }
520
521 /* Method: merge_train_data
522
523 Merges the data into the data contained in the <training_data>.
524
525 This function appears in FANN >= 1.1.0.
526 */
527 void merge_train_data(const training_data &data)
528 {
529 fann_train_data *new_data = fann_merge_train_data(train_data, data.train_data);
530 if (new_data != NULL)
531 {
532 destroy_train();
533 train_data = new_data;
534 }
535 }
536
537 /* Method: length_train_data
538
539 Returns the number of training patterns in the <training_data>.
540
541 See also:
542 <num_input_train_data>, <num_output_train_data>, <fann_length_train_data>
543
544 This function appears in FANN >= 2.0.0.
545 */
546 unsigned int length_train_data()
547 {
548 if (train_data == NULL)
549 {
550 return 0;
551 }
552 else
553 {
554 return fann_length_train_data(train_data);
555 }
556 }
557
558 /* Method: num_input_train_data
559
560 Returns the number of inputs in each of the training patterns in the <training_data>.
561
562 See also:
563 <num_output_train_data>, <length_train_data>, <fann_num_input_train_data>
564
565 This function appears in FANN >= 2.0.0.
566 */
567 unsigned int num_input_train_data()
568 {
569 if (train_data == NULL)
570 {
571 return 0;
572 }
573 else
574 {
575 return fann_num_input_train_data(train_data);
576 }
577 }
578
579 /* Method: num_output_train_data
580
581 Returns the number of outputs in each of the training patterns in the <struct fann_train_data>.
582
583 See also:
584 <num_input_train_data>, <length_train_data>, <fann_num_output_train_data>
585
586 This function appears in FANN >= 2.0.0.
587 */
588 unsigned int num_output_train_data()
589 {
590 if (train_data == NULL)
591 {
592 return 0;
593 }
594 else
595 {
596 return fann_num_output_train_data(train_data);
597 }
598 }
599
600 /* Grant access to the encapsulated data since many situations
601 and applications creates the data from sources other than files
602 or uses the training data for testing and related functions */
603
604 /* Method: get_input
605
606 Returns:
607 A pointer to the array of input training data
608
609 See also:
610 <get_output>, <set_train_data>
611 */
612 fann_type **get_input()
613 {
614 if (train_data == NULL)
615 {
616 return NULL;
617 }
618 else
619 {
620 return train_data->input;
621 }
622 }
623
624 /* Method: get_output
625
626 Returns:
627 A pointer to the array of output training data
628
629 See also:
630 <get_input>, <set_train_data>
631 */
632 fann_type **get_output()
633 {
634 if (train_data == NULL)
635 {
636 return NULL;
637 }
638 else
639 {
640 return train_data->output;
641 }
642 }
643
644 /* Method: set_train_data
645
646 Set the training data to the input and output data provided.
647
648 A copy of the data is made so there are no restrictions on the
649 allocation of the input/output data and the caller is responsible
650 for the deallocation of the data pointed to by input and output.
651
652 Parameters:
653 num_data - The number of training data
654 num_input - The number of inputs per training data
655 num_output - The number of outputs per training data
656 input - The set of inputs (a pointer to an array of pointers to arrays of floating point data)
657 output - The set of desired outputs (a pointer to an array of pointers to arrays of floating point data)
658
659 See also:
660 <get_input>, <get_output>
661 */
662 void set_train_data(unsigned int num_data,
663 unsigned int num_input, fann_type **input,
664 unsigned int num_output, fann_type **output)
665 {
666 // Uses the allocation method used in fann
667 struct fann_train_data *data =
668 (struct fann_train_data *)malloc(sizeof(struct fann_train_data));
669 data->input = (fann_type **)calloc(num_data, sizeof(fann_type *));
670 data->output = (fann_type **)calloc(num_data, sizeof(fann_type *));
671
672 data->num_data = num_data;
673 data->num_input = num_input;
674 data->num_output = num_output;
675
676 fann_type *data_input = (fann_type *)calloc(num_input*num_data, sizeof(fann_type));
677 fann_type *data_output = (fann_type *)calloc(num_output*num_data, sizeof(fann_type));
678
679 for (unsigned int i = 0; i < num_data; ++i)
680 {
681 data->input[i] = data_input;
682 data_input += num_input;
683 for (unsigned int j = 0; j < num_input; ++j)
684 {
685 data->input[i][j] = input[i][j];
686 }
687 data->output[i] = data_output;
688 data_output += num_output;
689 for (unsigned int j = 0; j < num_output; ++j)
690 {
691 data->output[i][j] = output[i][j];
692 }
693 }
694 set_train_data(data);
695 }
696
697
698
699 void set_train_data(const std::vector< std::vector<fann_type> >& input,
700 const std::vector< std::vector<fann_type> >& output)
701 {
702 unsigned int num_data=input.size();
703 assert(num_data);
704 assert(input.size()==output.size());
705 unsigned int num_input=input[0].size();
706 unsigned int num_output=output[0].size();
707
708 // Uses the allocation method used in fann
709 struct fann_train_data *data =
710 (struct fann_train_data *)malloc(sizeof(struct fann_train_data));
711 data->input = (fann_type **)calloc(num_data, sizeof(fann_type *));
712 data->output = (fann_type **)calloc(num_data, sizeof(fann_type *));
713
714 data->num_data = num_data;
715 data->num_input = num_input;
716 data->num_output = num_output;
717
718 fann_type *data_input = (fann_type *)calloc(num_input*num_data, sizeof(fann_type));
719 fann_type *data_output = (fann_type *)calloc(num_output*num_data, sizeof(fann_type));
720
721 for (unsigned int i = 0; i < num_data; ++i)
722 {
723 data->input[i] = data_input;
724 data_input += num_input;
725 for (unsigned int j = 0; j < num_input; ++j)
726 {
727 data->input[i][j] = input[i][j];
728 }
729 data->output[i] = data_output;
730 data_output += num_output;
731 for (unsigned int j = 0; j < num_output; ++j)
732 {
733 data->output[i][j] = output[i][j];
734 }
735 }
736 set_train_data(data);
737 }
738
739 void set_train_data(const std::vector< std::vector< std::vector<fann_type> > >& input, unsigned int num_data)
740 {
741 assert(num_data);
742 assert(input.size());
743 unsigned int num_class=input.size();
744 assert(input[0].size());
745 unsigned int num_input=input[0][0].size();
746 unsigned int num_output=num_class;
747 //test
748 // unsigned int num_output=1;
749
750 // Uses the allocation method used in fann
751 struct fann_train_data *data =
752 (struct fann_train_data *)malloc(sizeof(struct fann_train_data));
753 data->input = (fann_type **)calloc(num_data, sizeof(fann_type *));
754 data->output = (fann_type **)calloc(num_data, sizeof(fann_type *));
755
756 data->num_data = num_data;
757 data->num_input = num_input;
758 data->num_output = num_output;
759
760 fann_type *data_input = (fann_type *)calloc(num_input*num_data, sizeof(fann_type));
761 fann_type *data_output = (fann_type *)calloc(num_output*num_data, sizeof(fann_type));
762
763 unsigned int isample=0;
764 for(int iclass=0;iclass<num_class;++iclass){
765 for(int csample=0;csample<input[iclass].size();++csample){
766 data->input[isample] = data_input;
767 data_input += num_input;
768 for(int iband=0;iband<input[iclass][csample].size();++iband){
769 assert(input[iclass][csample].size()==num_input);
770 data->input[isample][iband] = input[iclass][csample][iband];
771 }
772 data->output[isample] = data_output;
773 data_output += num_output;
774 for(int ic=0;ic<num_output;++ic){
775 //for single neuron output:
776 // data->output[isample][ic]=2.0/(num_class-1)*(iclass-(num_class-1)/2.0);
777 if(ic==iclass)
778 data->output[isample][ic] = 1;
779 else
780 data->output[isample][ic] = -1;
781 }
782 ++isample;
783 }
784 }
785 set_train_data(data);
786 }
787
788 void set_train_data(const std::vector< Vector2d<fann_type> >& input, unsigned int num_data)
789 {
790 assert(num_data);
791 assert(input.size());
792 unsigned int num_class=input.size();
793 assert(input[0].size());
794 unsigned int num_input=input[0][0].size();
795 unsigned int num_output=num_class;
796 //test
797 // unsigned int num_output=1;
798
799 // Uses the allocation method used in fann
800 struct fann_train_data *data =
801 (struct fann_train_data *)malloc(sizeof(struct fann_train_data));
802 data->input = (fann_type **)calloc(num_data, sizeof(fann_type *));
803 data->output = (fann_type **)calloc(num_data, sizeof(fann_type *));
804
805 data->num_data = num_data;
806 data->num_input = num_input;
807 data->num_output = num_output;
808
809 fann_type *data_input = (fann_type *)calloc(num_input*num_data, sizeof(fann_type));
810 fann_type *data_output = (fann_type *)calloc(num_output*num_data, sizeof(fann_type));
811
812 unsigned int isample=0;
813 for(int iclass=0;iclass<num_class;++iclass){
814 for(int csample=0;csample<input[iclass].size();++csample){
815 data->input[isample] = data_input;
816 data_input += num_input;
817 for(int iband=0;iband<input[iclass][csample].size();++iband){
818 assert(input[iclass][csample].size()==num_input);
819 data->input[isample][iband] = input[iclass][csample][iband];
820 }
821 data->output[isample] = data_output;
822 data_output += num_output;
823 for(int ic=0;ic<num_output;++ic){
824 //for single neuron output:
825 // data->output[isample][ic]=2.0/(num_class-1)*(iclass-(num_class-1)/2.0);
826 if(ic==iclass)
827 data->output[isample][ic] = 1;
828 else
829 data->output[isample][ic] = -1;
830 }
831 ++isample;
832 }
833 }
834 set_train_data(data);
835 }
836
837
838 private:
839 /* Set the training data to the struct fann_training_data pointer.
840 The struct has to be allocated with malloc to be compatible
841 with fann_destroy. */
842 void set_train_data(struct fann_train_data *data)
843 {
844 destroy_train();
845 train_data = data;
846 }
847
848 public:
849 /*********************************************************************/
850
851 /* Method: create_train_from_callback
852 Creates the training data struct from a user supplied function.
853 As the training data are numerable (data 1, data 2...), the user must write
854 a function that receives the number of the training data set (input,output)
855 and returns the set.
856
857 Parameters:
858 num_data - The number of training data
859 num_input - The number of inputs per training data
860 num_output - The number of outputs per training data
861 user_function - The user suplied function
862
863 Parameters for the user function:
864 num - The number of the training data set
865 num_input - The number of inputs per training data
866 num_output - The number of outputs per training data
867 input - The set of inputs
868 output - The set of desired outputs
869
870 See also:
871 <training_data::read_train_from_file>, <neural_net::train_on_data>,
872 <fann_create_train_from_callback>
873
874 This function appears in FANN >= 2.1.0
875 */
876 void create_train_from_callback(unsigned int num_data,
877 unsigned int num_input,
878 unsigned int num_output,
879 void (FANN_API *user_function)( unsigned int,
880 unsigned int,
881 unsigned int,
882 fann_type * ,
883 fann_type * ))
884 {
885 destroy_train();
886 train_data = fann_create_train_from_callback(num_data, num_input, num_output, user_function);
887 }
888
889 /* Method: scale_input_train_data
890
891 Scales the inputs in the training data to the specified range.
892
893 See also:
894 <scale_output_train_data>, <scale_train_data>, <fann_scale_input_train_data>
895
896 This function appears in FANN >= 2.0.0.
897 */
898 void scale_input_train_data(fann_type new_min, fann_type new_max)
899 {
900 if (train_data != NULL)
901 {
902 fann_scale_input_train_data(train_data, new_min, new_max);
903 }
904 }
905
906 /* Method: scale_output_train_data
907
908 Scales the outputs in the training data to the specified range.
909
910 See also:
911 <scale_input_train_data>, <scale_train_data>, <fann_scale_output_train_data>
912
913 This function appears in FANN >= 2.0.0.
914 */
915 void scale_output_train_data(fann_type new_min, fann_type new_max)
916 {
917 if (train_data != NULL)
918 {
919 fann_scale_output_train_data(train_data, new_min, new_max);
920 }
921 }
922
923 /* Method: scale_train_data
924
925 Scales the inputs and outputs in the training data to the specified range.
926
927 See also:
928 <scale_output_train_data>, <scale_input_train_data>, <fann_scale_train_data>
929
930 This function appears in FANN >= 2.0.0.
931 */
932 void scale_train_data(fann_type new_min, fann_type new_max)
933 {
934 if (train_data != NULL)
935 {
936 fann_scale_train_data(train_data, new_min, new_max);
937 }
938 }
939
940 /* Method: subset_train_data
941
942 Changes the training data to a subset, starting at position *pos*
943 and *length* elements forward. Use the copy constructor to work
944 on a new copy of the training data.
945
946 >FANN::training_data full_data_set;
947 >full_data_set.read_train_from_file("somefile.train");
948 >FANN::training_data *small_data_set = new FANN::training_data(full_data_set);
949 >small_data_set->subset_train_data(0, 2); // Only use first two
950 >// Use small_data_set ...
951 >delete small_data_set;
952
953 See also:
954 <fann_subset_train_data>
955
956 This function appears in FANN >= 2.0.0.
957 */
958 void subset_train_data(unsigned int pos, unsigned int length)
959 {
960 if (train_data != NULL)
961 {
962 struct fann_train_data *temp = fann_subset_train_data(train_data, pos, length);
963 destroy_train();
964 train_data = temp;
965 }
966 }
967
968 /*********************************************************************/
969
970 protected:
971 /* The neural_net class has direct access to the training data */
972 friend class neural_net;
973
974 /* Pointer to the encapsulated training data */
975 struct fann_train_data* train_data;
976 };
977
978 /*************************************************************************/
979
980 /* Class: neural_net
981
982 Encapsulation of a neural network <struct fann> and
983 associated C API functions.
984 */
985 class neural_net
986 {
987 public:
988 /* Constructor: neural_net
989
990 Default constructor creates an empty neural net.
991 Use one of the create functions to create the neural network.
992
993 See also:
994 <create_standard>, <create_sparse>, <create_shortcut>,
995 <create_standard_array>, <create_sparse_array>, <create_shortcut_array>
996 */
997 neural_net() : ann(NULL)
998 {
999 }
1000
1001 /* Destructor: ~neural_net
1002
1003 Provides automatic cleanup of data.
1004 Define USE_VIRTUAL_DESTRUCTOR if you need the destructor to be virtual.
1005
1006 See also:
1007 <destroy>
1008 */
1009 #ifdef USE_VIRTUAL_DESTRUCTOR
1010 virtual
1011 #endif
1012 ~neural_net()
1013 {
1014 destroy();
1015 }
1016
1017 /* Method: destroy
1018
1019 Destructs the entire network. Called automatically by the destructor.
1020
1021 See also:
1022 <~neural_net>
1023 */
1024 void destroy()
1025 {
1026 if (ann != NULL)
1027 {
1028 user_context *user_data = static_cast<user_context *>(fann_get_user_data(ann));
1029 if (user_data != NULL)
1030 delete user_data;
1031
1032 fann_destroy(ann);
1033 ann = NULL;
1034 }
1035 }
1036
1037 /* Method: create_standard
1038
1039 Creates a standard fully connected backpropagation neural network.
1040
1041 There will be a bias neuron in each layer (except the output layer),
1042 and this bias neuron will be connected to all neurons in the next layer.
1043 When running the network, the bias nodes always emits 1.
1044
1045 Parameters:
1046 num_layers - The total number of layers including the input and the output layer.
1047 ... - Integer values determining the number of neurons in each layer starting with the
1048 input layer and ending with the output layer.
1049
1050 Returns:
1051 Boolean true if the network was created, false otherwise.
1052
1053 Example:
1054 >const unsigned int num_layers = 3;
1055 >const unsigned int num_input = 2;
1056 >const unsigned int num_hidden = 3;
1057 >const unsigned int num_output = 1;
1058 >
1059 >FANN::neural_net net;
1060 >net.create_standard(num_layers, num_input, num_hidden, num_output);
1061
1062 See also:
1063 <create_standard_array>, <create_sparse>, <create_shortcut>,
1064 <fann_create_standard_array>
1065
1066 This function appears in FANN >= 2.0.0.
1067 */
1068 bool create_standard(unsigned int num_layers, ...)
1069 {
1070 va_list layers;
1071 std::vector<unsigned int> arr(num_layers);//pk
1072 //unsigned int arr[num_layers];
1073
1074 va_start(layers, num_layers);
1075 /* bool status = create_standard_array(num_layers, */
1076 /* reinterpret_cast<const unsigned int *>(layers)); */
1077 for (unsigned int ii = 0; ii < num_layers; ii++)
1078 arr[ii] = va_arg(layers, unsigned int);
1079 bool status = create_standard_array(num_layers, &(arr[0]));//pk
1080 //bool status = create_standard_array(num_layers, arr);
1081 va_end(layers);
1082 return status;
1083 }
1084
1085 /* Method: create_standard_array
1086
1087 Just like <create_standard>, but with an array of layer sizes
1088 instead of individual parameters.
1089
1090 See also:
1091 <create_standard>, <create_sparse>, <create_shortcut>,
1092 <fann_create_standard>
1093
1094 This function appears in FANN >= 2.0.0.
1095 */
1096 bool create_standard_array(unsigned int num_layers, const unsigned int * layers)
1097 {
1098 destroy();
1099 ann = fann_create_standard_array(num_layers, layers);
1100 return (ann != NULL);
1101 }
1102
1103 /* Method: create_sparse
1104
1105 Creates a standard backpropagation neural network, which is not fully connected.
1106
1107 Parameters:
1108 connection_rate - The connection rate controls how many connections there will be in the
1109 network. If the connection rate is set to 1, the network will be fully
1110 connected, but if it is set to 0.5 only half of the connections will be set.
1111 A connection rate of 1 will yield the same result as <fann_create_standard>
1112 num_layers - The total number of layers including the input and the output layer.
1113 ... - Integer values determining the number of neurons in each layer starting with the
1114 input layer and ending with the output layer.
1115
1116 Returns:
1117 Boolean true if the network was created, false otherwise.
1118
1119 See also:
1120 <create_standard>, <create_sparse_array>, <create_shortcut>,
1121 <fann_create_sparse>
1122
1123 This function appears in FANN >= 2.0.0.
1124 */
1125 bool create_sparse(float connection_rate, unsigned int num_layers, ...)
1126 {
1127 va_list layers;
1128 std::vector<unsigned int> arr(num_layers);//pk
1129 //unsigned int arr[num_layers];
1130
1131 va_start(layers, num_layers);
1132 /* bool status = create_sparse_array(connection_rate, num_layers, */
1133 /* reinterpret_cast<const unsigned int *>(layers)); */
1134
1135 for (unsigned int ii = 0; ii < num_layers; ii++)
1136 arr[ii] = va_arg(layers, unsigned int);
1137 bool status = create_sparse_array(connection_rate, num_layers, &(arr[0]));//pk
1138 //bool status = create_sparse_array(connection_rate, num_layers, arr);
1139
1140 va_end(layers);
1141 return status;
1142 }
1143
1144 /* Method: create_sparse_array
1145 Just like <create_sparse>, but with an array of layer sizes
1146 instead of individual parameters.
1147
1148 See <create_sparse> for a description of the parameters.
1149
1150 See also:
1151 <create_standard>, <create_sparse>, <create_shortcut>,
1152 <fann_create_sparse_array>
1153
1154 This function appears in FANN >= 2.0.0.
1155 */
1156 bool create_sparse_array(float connection_rate,
1157 unsigned int num_layers, const unsigned int * layers)
1158 {
1159 destroy();
1160 ann = fann_create_sparse_array(connection_rate, num_layers, layers);
1161 return (ann != NULL);
1162 }
1163
1164 /* Method: create_shortcut
1165
1166 Creates a standard backpropagation neural network, which is not fully connected and which
1167 also has shortcut connections.
1168
1169 Shortcut connections are connections that skip layers. A fully connected network with shortcut
1170 connections, is a network where all neurons are connected to all neurons in later layers.
1171 Including direct connections from the input layer to the output layer.
1172
1173 See <create_standard> for a description of the parameters.
1174
1175 See also:
1176 <create_standard>, <create_sparse>, <create_shortcut_array>,
1177 <fann_create_shortcut>
1178
1179 This function appears in FANN >= 2.0.0.
1180 */
1181 bool create_shortcut(unsigned int num_layers, ...)
1182 {
1183 va_list layers;
1184 std::vector<unsigned int> arr(num_layers);//pk
1185 //unsigned int arr[num_layers];
1186
1187 va_start(layers, num_layers);
1188 /* bool status = create_shortcut_array(num_layers, */
1189 /* reinterpret_cast<const unsigned int *>(layers)); */
1190 for (unsigned int ii = 0; ii < num_layers; ii++)
1191 arr[ii] = va_arg(layers, unsigned int);
1192 bool status = create_shortcut_array(num_layers, &(arr[0]));//
1193 //bool status = create_shortcut_array(num_layers, arr);
1194
1195 va_end(layers);
1196 return status;
1197 }
1198
1199 /* Method: create_shortcut_array
1200
1201 Just like <create_shortcut>, but with an array of layer sizes
1202 instead of individual parameters.
1203
1204 See <create_standard_array> for a description of the parameters.
1205
1206 See also:
1207 <create_standard>, <create_sparse>, <create_shortcut>,
1208 <fann_create_shortcut_array>
1209
1210 This function appears in FANN >= 2.0.0.
1211 */
1212 bool create_shortcut_array(unsigned int num_layers,
1213 const unsigned int * layers)
1214 {
1215 destroy();
1216 ann = fann_create_shortcut_array(num_layers, layers);
1217 return (ann != NULL);
1218 }
1219
1220 /* Method: run
1221
1222 Will run input through the neural network, returning an array of outputs, the number of which being
1223 equal to the number of neurons in the output layer.
1224
1225 See also:
1226 <test>, <fann_run>
1227
1228 This function appears in FANN >= 1.0.0.
1229 */
1230 fann_type* run(fann_type *input)
1231 {
1232 if (ann == NULL)
1233 {
1234 return NULL;
1235 }
1236 // for(int iband=0;iband<get_num_input();++iband)
1237 // std::cout << (input)[iband] << " ";
1238 // std::cout << std::endl;
1239 return fann_run(ann, input);
1240 }
1241
1242 std::vector<fann_type> run(std::vector<fann_type> input)
1243 {
1244 std::vector<fann_type> vresult;
1245 if (ann == NULL)
1246 {
1247 return vresult;
1248 }
1249 vresult.resize(get_num_output());
1250 fann_type* result;
1251 result=fann_run(ann,&(input[0]));
1252 for(int iout=0;iout<get_num_output();++iout)
1253 vresult[iout]=*(result++);
1254 return vresult;
1255 }
1256
1257 /* Method: randomize_weights
1258
1259 Give each connection a random weight between *min_weight* and *max_weight*
1260
1261 From the beginning the weights are random between -0.1 and 0.1.
1262
1263 See also:
1264 <init_weights>, <fann_randomize_weights>
1265
1266 This function appears in FANN >= 1.0.0.
1267 */
1268 void randomize_weights(fann_type min_weight, fann_type max_weight)
1269 {
1270 if (ann != NULL)
1271 {
1272 fann_randomize_weights(ann, min_weight, max_weight);
1273 }
1274 }
1275
1276 /* Method: init_weights
1277
1278 Initialize the weights using Widrow + Nguyen's algorithm.
1279
1280 This function behaves similarly to fann_randomize_weights. It will use the algorithm developed
1281 by Derrick Nguyen and Bernard Widrow to set the weights in such a way
1282 as to speed up training. This technique is not always successful, and in some cases can be less
1283 efficient than a purely random initialization.
1284
1285 The algorithm requires access to the range of the input data (ie, largest and smallest input),
1286 and therefore accepts a second argument, data, which is the training data that will be used to
1287 train the network.
1288
1289 See also:
1290 <randomize_weights>, <training_data::read_train_from_file>,
1291 <fann_init_weights>
1292
1293 This function appears in FANN >= 1.1.0.
1294 */
1295 void init_weights(const training_data &data)
1296 {
1297 if ((ann != NULL) && (data.train_data != NULL))
1298 {
1299 fann_init_weights(ann, data.train_data);
1300 }
1301 }
1302
1303 /* Method: print_connections
1304
1305 Will print the connections of the ann in a compact matrix, for easy viewing of the internals
1306 of the ann.
1307
1308 The output from fann_print_connections on a small (2 2 1) network trained on the xor problem
1309 >Layer / Neuron 012345
1310 >L 1 / N 3 BBa...
1311 >L 1 / N 4 BBA...
1312 >L 1 / N 5 ......
1313 >L 2 / N 6 ...BBA
1314 >L 2 / N 7 ......
1315
1316 This network have five real neurons and two bias neurons. This gives a total of seven neurons
1317 named from 0 to 6. The connections between these neurons can be seen in the matrix. "." is a
1318 place where there is no connection, while a character tells how strong the connection is on a
1319 scale from a-z. The two real neurons in the hidden layer (neuron 3 and 4 in layer 1) has
1320 connection from the three neurons in the previous layer as is visible in the first two lines.
1321 The output neuron (6) has connections form the three neurons in the hidden layer 3 - 5 as is
1322 visible in the fourth line.
1323
1324 To simplify the matrix output neurons is not visible as neurons that connections can come from,
1325 and input and bias neurons are not visible as neurons that connections can go to.
1326
1327 This function appears in FANN >= 1.2.0.
1328 */
1329 void print_connections()
1330 {
1331 if (ann != NULL)
1332 {
1333 fann_print_connections(ann);
1334 }
1335 }
1336
1337 /* Method: create_from_file
1338
1339 Constructs a backpropagation neural network from a configuration file,
1340 which have been saved by <save>.
1341
1342 See also:
1343 <save>, <save_to_fixed>, <fann_create_from_file>
1344
1345 This function appears in FANN >= 1.0.0.
1346 */
1347 bool create_from_file(const std::string &configuration_file)
1348 {
1349 destroy();
1350 ann = fann_create_from_file(configuration_file.c_str());
1351 return (ann != NULL);
1352 }
1353
1354 bool create_from_file(const std::string &configuration_file, std::vector<double> &offset, std::vector<double> &scale, std::map<std::string,short> &classValueMap, std::vector<std::string> &nameVector, std::vector<std::string> &bandNames){
1355 offset.clear();
1356 scale.clear();
1357 classValueMap.clear();
1358 nameVector.clear();
1359 bandNames.clear();
1360 create_from_file(configuration_file.c_str());
1361 short verbose=0;
1362 std::ifstream m_ifstream;
1363 m_ifstream.open(configuration_file.c_str(),std::ios_base::in);
1364 if(!(m_ifstream)){
1365 std::ostringstream errorStream;
1366 errorStream << "Error: could not open file" << configuration_file;
1367 throw(errorStream.str());
1368 }
1369 std::istringstream lineStream;
1370 std::istringstream csvstream;
1371 int ncol=0;
1372 char m_comment='#';
1373 char m_equal='=';
1374 char m_fs=',';//commma seperated
1375 bool isComment=false;
1376 bool isEqual=false;
1377 std::string csvRecord;
1378 std::string item;
1379 size_t pos=std::string::npos;
1380 size_t posEqual=std::string::npos;
1381 size_t posComment=std::string::npos;
1382
1383 bool offsetDone=false;
1384 bool scaleDone=false;
1385 bool classValueMapDone=false;
1386 bool nameVectorDone=false;
1387 bool bandNamesDone=false;
1388 while(getline(m_ifstream,csvRecord)){//read a line
1389 if(!offsetDone){
1390 //reading offset
1391 if(csvRecord.find("offset")==std::string::npos)
1392 continue;
1393 if(verbose>1)
1394 std::cout << csvRecord << std::endl;
1395 lineStream.clear();
1396 lineStream.str(csvRecord);
1397 isEqual=false;
1398 csvstream.clear();
1399 csvstream.str(csvRecord);
1400 ncol=0;
1401 while(getline(csvstream,item,m_fs)){//read a column
1402 if(verbose)
1403 std::cout << item << " ";
1404 pos=item.find(m_comment);
1405 if(pos!=std::string::npos){
1406 isComment=true;
1407 if(pos>0)
1408 item=item.substr(0,pos-1);
1409 else
1410 break;
1411 if(verbose)
1412 std::cout << "comment found, string is " << item << std::endl;
1413 }
1414 ++ncol;
1415 if(isComment)
1416 break;
1417 }
1418 //number of columns is ncol
1419 lineStream.clear();
1420 lineStream.str(csvRecord);
1421 isComment=false;
1422 csvstream.clear();
1423 csvstream.str(csvRecord);
1424 while(getline(csvstream,item,m_fs)){//read a column
1425 if(verbose)
1426 std::cout << item << " ";
1427 posEqual=item.find(m_equal);
1428 posComment=item.find(m_comment);
1429 if(!isEqual){
1430 if(posEqual!=std::string::npos){
1431 isEqual=true;
1432 if(posEqual>0)
1433 item=item.substr(posEqual+1);
1434 else
1435 break;
1436 if(verbose)
1437 std::cout << "equal found, string is " << item << std::endl;
1438 }
1439 else
1440 continue;//until we found equal character
1441 }
1442 if(posComment!=std::string::npos){
1443 isComment=true;
1444 if(posComment>0)
1445 item=item.substr(0,posComment-1);
1446 else
1447 break;
1448 if(verbose)
1449 std::cout << "comment found, string is " << item << std::endl;
1450 }
1451 //rstrip comma from item
1452 pos=item.find(',');
1453 if(pos!=std::string::npos)
1454 item=item.substr(0,pos-1);
1455 float value=string2type<float>(item);
1456
1457 offset.push_back(value);
1458 }
1459 if(offset.size()!=ncol){
1460 std::string errorString="Error: reading offset";
1461 throw(errorString);
1462 }
1463 if(verbose){
1464 std::cout << "offset:" << std::endl;
1465 for(int index=0;index<offset.size();++index){
1466 if(index<offset.size()-1)
1467 std::cout << offset[index] << ", ";
1468 else
1469 std::cout << offset[index] << std::endl;
1470 }
1471 }
1472 offsetDone=true;
1473 continue;
1474 }
1475 if(!scaleDone){
1476 //reading scale
1477
1478 //if(csvRecord.find("scale")==std::string::npos)
1479 // continue;
1480 if(verbose>1)
1481 std::cout << csvRecord << std::endl;
1482 lineStream.clear();
1483 lineStream.str(csvRecord);
1484 isEqual=false;
1485 csvstream.clear();
1486 csvstream.str(csvRecord);
1487 ncol=0;
1488 while(getline(csvstream,item,m_fs)){//read a column
1489 if(verbose)
1490 std::cout << item << " ";
1491 pos=item.find(m_comment);
1492 if(pos!=std::string::npos){
1493 isComment=true;
1494 if(pos>0)
1495 item=item.substr(0,pos-1);
1496 else
1497 break;
1498 if(verbose)
1499 std::cout << "comment found, string is " << item << std::endl;
1500 }
1501 ++ncol;
1502 if(isComment)
1503 break;
1504 }
1505 //number of columns is ncol
1506 lineStream.clear();
1507 lineStream.str(csvRecord);
1508 isComment=false;
1509 while(getline(lineStream,item,m_fs)){//read a column
1510 if(verbose)
1511 std::cout << item << " ";
1512 posEqual=item.find(m_equal);
1513 posComment=item.find(m_comment);
1514 if(!isEqual){
1515 if(posEqual!=std::string::npos){
1516 isEqual=true;
1517 if(posEqual>0)
1518 item=item.substr(posEqual+1);
1519 else
1520 break;
1521 if(verbose)
1522 std::cout << "equal found, string is " << item << std::endl;
1523 }
1524 else
1525 continue;//until we found equal character
1526 }
1527 if(posComment!=std::string::npos){
1528 isComment=true;
1529 if(posComment>0)
1530 item=item.substr(0,posComment-1);
1531 else
1532 break;
1533 if(verbose)
1534 std::cout << "comment found, string is " << item << std::endl;
1535 }
1536 //rstrip comma from item
1537 pos=item.find(',');
1538 if(pos!=std::string::npos)
1539 item=item.substr(0,pos-1);
1540 float value=string2type<float>(item);
1541 scale.push_back(value);
1542 }
1543 if(scale.size()!=ncol){
1544 std::string errorString="Error: reading scale";
1545 throw(errorString);
1546 }
1547 if(verbose){
1548 std::cout << "scale:" << std::endl;
1549 for(int index=0;index<scale.size();++index){
1550 if(index<scale.size()-1)
1551 std::cout << scale[index] << ", ";
1552 else
1553 std::cout << scale[index] << std::endl;
1554 }
1555 }
1556 scaleDone=true;
1557 continue;
1558 }
1559 if(!classValueMapDone){
1560 //reading classValueMap
1561 //if(csvRecord.find("classValueMap")==std::string::npos)
1562 // continue;
1563 if(verbose>1)
1564 std::cout << csvRecord << std::endl;
1565 lineStream.clear();
1566 lineStream.str(csvRecord);
1567 isEqual=false;
1568 csvstream.clear();
1569 csvstream.str(csvRecord);
1570 ncol=0;
1571 while(getline(csvstream,item,m_fs)){//read a column
1572 if(verbose)
1573 std::cout << item << " ";
1574 pos=item.find(m_comment);
1575 if(pos!=std::string::npos){
1576 isComment=true;
1577 if(pos>0)
1578 item=item.substr(0,pos-1);
1579 else
1580 break;
1581 if(verbose)
1582 std::cout << "comment found, string is " << item << std::endl;
1583 }
1584 ++ncol;
1585 if(isComment)
1586 break;
1587 }
1588 //number of columns is ncol
1589 lineStream.clear();
1590 lineStream.str(csvRecord);
1591 isComment=false;
1592 while(getline(lineStream,item,m_fs)){//read a column
1593 if(verbose)
1594 std::cout << item << " ";
1595 posEqual=item.find(m_equal);
1596 posComment=item.find(m_comment);
1597 if(!isEqual){
1598 if(posEqual!=std::string::npos){
1599 isEqual=true;
1600 if(posEqual>0)
1601 item=item.substr(posEqual+1);
1602 else
1603 break;
1604 if(verbose)
1605 std::cout << "equal found, string is " << item << std::endl;
1606 }
1607 else
1608 continue;//until we found equal character
1609 }
1610 if(posComment!=std::string::npos){
1611 isComment=true;
1612 if(posComment>0)
1613 item=item.substr(0,posComment-1);
1614 else
1615 break;
1616 if(verbose)
1617 std::cout << "comment found, string is " << item << std::endl;
1618 }
1619 //rstrip comma from item
1620 pos=item.find(',');
1621 if(pos!=std::string::npos)
1622 item=item.substr(0,pos-1);
1623 //split item in item1 before ':' and item2 after ':'
1624 pos=item.find(':');
1625 std::string key;
1626 if(pos!=std::string::npos){
1627 key=item.substr(0,pos);
1628 float value=string2type<float>(item.substr(pos+1));
1629 classValueMap[key]=value;
1630 }
1631 else{
1632 std::string errorString="Error: reading classValueMap (no : found)";
1633 throw(errorString);
1634 }
1635 }
1636 if(verbose){
1637 std::cout << "classValueMap=";
1638 std::map<std::string,short>::const_iterator mapit=classValueMap.begin();
1639 while(mapit!=classValueMap.end()){
1640 if(mapit!=--classValueMap.end())
1641 std::cout << mapit->first << ":" << mapit->second << ", ";
1642 else
1643 std::cout << mapit->first << ":" << mapit->second << std::endl;
1644 ++mapit;
1645 }
1646 }
1647 if(classValueMap.size()!=ncol){
1648 std::ostringstream errorStream;
1649 errorStream << "Error: reading classValueMap (ncol: " << classValueMap.size() << ")";
1650 throw(errorStream.str());
1651 }
1652 classValueMapDone=true;
1653 continue;
1654 }
1655 if(!nameVectorDone){
1656 bool nameVectorFound=false;
1657 //reading nameVector
1658 if(csvRecord.find("nameVector")!=std::string::npos)
1659 nameVectorFound=true;
1660 if(verbose>1)
1661 std::cout << csvRecord << std::endl;
1662 lineStream.clear();
1663 lineStream.str(csvRecord);
1664 isEqual=false;
1665 csvstream.clear();
1666 csvstream.str(csvRecord);
1667 ncol=0;
1668 while(getline(csvstream,item,m_fs)){//read a column
1669 if(verbose)
1670 std::cout << item << " ";
1671 pos=item.find(m_comment);
1672 if(pos!=std::string::npos){
1673 isComment=true;
1674 if(pos>0)
1675 item=item.substr(0,pos-1);
1676 else
1677 break;
1678 if(verbose)
1679 std::cout << "comment found, string is " << item << std::endl;
1680 }
1681 ++ncol;
1682 if(isComment)
1683 break;
1684 }
1685 //number of columns is ncol
1686 lineStream.clear();
1687 lineStream.str(csvRecord);
1688 isComment=false;
1689 while(getline(lineStream,item,m_fs)){//read a column
1690 if(verbose)
1691 std::cout << item << " ";
1692 posEqual=item.find(m_equal);
1693 posComment=item.find(m_comment);
1694 if(!isEqual){
1695 if(posEqual!=std::string::npos){
1696 isEqual=true;
1697 if(posEqual>0)
1698 item=item.substr(posEqual+1);
1699 else
1700 break;
1701 if(verbose)
1702 std::cout << "equal found, string is " << item << std::endl;
1703 }
1704 else
1705 continue;//until we found equal character
1706 }
1707 if(posComment!=std::string::npos){
1708 isComment=true;
1709 if(posComment>0)
1710 item=item.substr(0,posComment-1);
1711 else
1712 break;
1713 if(verbose)
1714 std::cout << "comment found, string is " << item << std::endl;
1715 }
1716 //rstrip comma from item
1717 pos=item.find(',');
1718 if(pos!=std::string::npos)
1719 item=item.substr(0,pos-1);
1720 nameVector.push_back(item);
1721 }
1722 if(nameVector.size()!=ncol){
1723 std::string errorString="Error: reading nameVector";
1724 throw(errorString);
1725 }
1726 if(verbose){
1727 std::cout << "nameVector:" << std::endl;
1728 for(int index=0;index<nameVector.size();++index){
1729 if(index<nameVector.size()-1)
1730 std::cout << nameVector[index] << ", ";
1731 else
1732 std::cout << nameVector[index] << std::endl;
1733 }
1734 }
1735 if(!nameVectorFound)
1736 nameVector.clear();
1737 nameVectorDone=true;
1738 }
1739 if(!bandNamesDone){
1740 bool bandNamesFound=false;
1741 //reading bandNames
1742 if(csvRecord.find("bandNames")!=std::string::npos)
1743 bandNamesFound=true;
1744 if(verbose>1)
1745 std::cout << csvRecord << std::endl;
1746 lineStream.clear();
1747 lineStream.str(csvRecord);
1748 isEqual=false;
1749 csvstream.clear();
1750 csvstream.str(csvRecord);
1751 ncol=0;
1752 while(getline(csvstream,item,m_fs)){//read a column
1753 if(verbose)
1754 std::cout << item << " ";
1755 pos=item.find(m_comment);
1756 if(pos!=std::string::npos){
1757 isComment=true;
1758 if(pos>0)
1759 item=item.substr(0,pos-1);
1760 else
1761 break;
1762 if(verbose)
1763 std::cout << "comment found, string is " << item << std::endl;
1764 }
1765 ++ncol;
1766 if(isComment)
1767 break;
1768 }
1769 //number of columns is ncol
1770 lineStream.clear();
1771 lineStream.str(csvRecord);
1772 isComment=false;
1773 while(getline(lineStream,item,m_fs)){//read a column
1774 if(verbose)
1775 std::cout << item << " ";
1776 posEqual=item.find(m_equal);
1777 posComment=item.find(m_comment);
1778 if(!isEqual){
1779 if(posEqual!=std::string::npos){
1780 isEqual=true;
1781 if(posEqual>0)
1782 item=item.substr(posEqual+1);
1783 else
1784 break;
1785 if(verbose)
1786 std::cout << "equal found, string is " << item << std::endl;
1787 }
1788 else
1789 continue;//until we found equal character
1790 }
1791 if(posComment!=std::string::npos){
1792 isComment=true;
1793 if(posComment>0)
1794 item=item.substr(0,posComment-1);
1795 else
1796 break;
1797 if(verbose)
1798 std::cout << "comment found, string is " << item << std::endl;
1799 }
1800 //rstrip comma from item
1801 pos=item.find(',');
1802 if(pos!=std::string::npos)
1803 item=item.substr(0,pos-1);
1804 bandNames.push_back(item);
1805 }
1806 if(bandNames.size()!=ncol){
1807 std::string errorString="Error: reading bandNames";
1808 throw(errorString);
1809 }
1810 if(verbose){
1811 std::cout << "bandNames:" << std::endl;
1812 for(int index=0;index<bandNames.size();++index){
1813 if(index<bandNames.size()-1)
1814 std::cout << bandNames[index] << ", ";
1815 else
1816 std::cout << bandNames[index] << std::endl;
1817 }
1818 }
1819 if(!bandNamesFound)
1820 bandNames.clear();
1821 bandNamesDone=true;
1822 }
1823 }
1824 m_ifstream.close();
1825 return (ann != NULL);
1826 }
1827
1828 /* Method: save
1829
1830 Save the entire network to a configuration file.
1831
1832 The configuration file contains all information about the neural network and enables
1833 <create_from_file> to create an exact copy of the neural network and all of the
1834 parameters associated with the neural network.
1835
1836 These two parameters (<set_callback>, <set_error_log>) are *NOT* saved
1837 to the file because they cannot safely be ported to a different location. Also temporary
1838 parameters generated during training like <get_MSE> is not saved.
1839
1840 Return:
1841 The function returns 0 on success and -1 on failure.
1842
1843 See also:
1844 <create_from_file>, <save_to_fixed>, <fann_save>
1845
1846 This function appears in FANN >= 1.0.0.
1847 */
1848 bool save(const std::string &configuration_file)
1849 {
1850 if (ann == NULL)
1851 {
1852 return false;
1853 }
1854 if (fann_save(ann, configuration_file.c_str()) == -1)
1855 {
1856 return false;
1857 }
1858 return true;
1859 }
1860
1861 int fann_save_internal_fd(std::ostream &outputStream, struct fann *ann, unsigned int save_as_fixed)
1862 {
1863 struct fann_layer *layer_it;
1864 int calculated_decimal_point = 0;
1865 struct fann_neuron *neuron_it, *first_neuron;
1866 fann_type *weights;
1867 struct fann_neuron **connected_neurons;
1868 unsigned int i = 0;
1869
1870 #ifndef FIXEDFANN
1871 /* variabels for use when saving floats as fixed point variabels */
1872 unsigned int decimal_point = 0;
1873 unsigned int fixed_multiplier = 0;
1874 fann_type max_possible_value = 0;
1875 unsigned int bits_used_for_max = 0;
1876 fann_type current_max_value = 0;
1877 #endif
1878
1879 #ifndef FIXEDFANN
1880 if(save_as_fixed)
1881 {
1882 /* save the version information */
1883 /* fprintf(conf, FANN_FIX_VERSION "\n"); */
1884 outputStream << FANN_FIX_VERSION << std::endl;
1885 }
1886 else
1887 {
1888 /* save the version information */
1889 /* fprintf(conf, FANN_FLO_VERSION "\n"); */
1890 outputStream << FANN_FLO_VERSION << std::endl;
1891 }
1892 #else
1893 /* save the version information */
1894 /* fprintf(conf, FANN_FIX_VERSION "\n"); */
1895 outputStream << FANN_FIX_VERSION << std::endl;
1896 #endif
1897
1898 #ifndef FIXEDFANN
1899 if(save_as_fixed)
1900 {
1901 /* calculate the maximal possible shift value */
1902
1903 for(layer_it = ann->first_layer + 1; layer_it != ann->last_layer; layer_it++)
1904 {
1905 for(neuron_it = layer_it->first_neuron; neuron_it != layer_it->last_neuron; neuron_it++)
1906 {
1907 /* look at all connections to each neurons, and see how high a value we can get */
1908 current_max_value = 0;
1909 for(i = neuron_it->first_con; i != neuron_it->last_con; i++)
1910 {
1911 current_max_value += fann_abs(ann->weights[i]);
1912 }
1913
1914 if(current_max_value > max_possible_value)
1915 {
1916 max_possible_value = current_max_value;
1917 }
1918 }
1919 }
1920
1921 for(bits_used_for_max = 0; max_possible_value >= 1; bits_used_for_max++)
1922 {
1923 max_possible_value /= 2.0;
1924 }
1925
1926 /* The maximum number of bits we shift the fix point, is the number
1927 * of bits in a integer, minus one for the sign, one for the minus
1928 * in stepwise, and minus the bits used for the maximum.
1929 * This is devided by two, to allow multiplication of two fixed
1930 * point numbers.
1931 */
1932 calculated_decimal_point = (sizeof(int) * 8 - 2 - bits_used_for_max) / 2;
1933
1934 if(calculated_decimal_point < 0)
1935 {
1936 decimal_point = 0;
1937 }
1938 else
1939 {
1940 decimal_point = calculated_decimal_point;
1941 }
1942
1943 fixed_multiplier = 1 << decimal_point;
1944
1945 #ifdef DEBUG
1946 printf("calculated_decimal_point=%d, decimal_point=%u, bits_used_for_max=%u\n",
1947 calculated_decimal_point, decimal_point, bits_used_for_max);
1948 #endif
1949
1950 /* save the decimal_point on a seperate line */
1951 /* fprintf(conf, "decimal_point=%u\n", decimal_point); */
1952 outputStream << "decimal_point=" << decimal_point << std::endl;
1953 }
1954 #else
1955 /* save the decimal_point on a seperate line */
1956 outputStream << "decimal_point=" << ann->decimal_point << std::endl;
1957
1958 #endif
1959
1960 /* Save network parameters */
1961 outputStream << "num_layers=" << (int)(ann->last_layer - ann->first_layer) << std::endl;
1962 outputStream << "learning_rate=" << ann->learning_rate << std::endl;
1963 outputStream << "connection_rate=" << ann->connection_rate << std::endl;
1964 outputStream << "network_type=" << ann->network_type << std::endl;
1965
1966 outputStream << "learning_momentum=" << ann->learning_momentum << std::endl;
1967 outputStream << "training_algorithm=" << ann->training_algorithm << std::endl;
1968 outputStream << "train_error_function=" << ann->train_error_function << std::endl;
1969 outputStream << "train_stop_function=" << ann->train_stop_function << std::endl;
1970 outputStream << "cascade_output_change_fraction=" << ann->cascade_output_change_fraction << std::endl;
1971 outputStream << "quickprop_decay=" << ann->quickprop_decay << std::endl;
1972 outputStream << "quickprop_mu=" << ann->quickprop_mu << std::endl;
1973 outputStream << "rprop_increase_factor=" << ann->rprop_increase_factor << std::endl;
1974 outputStream << "rprop_decrease_factor=" << ann->rprop_decrease_factor << std::endl;
1975 outputStream << "rprop_delta_min=" << ann->rprop_delta_min << std::endl;
1976 outputStream << "rprop_delta_max=" << ann->rprop_delta_max << std::endl;
1977 outputStream << "rprop_delta_zero=" << ann->rprop_delta_zero << std::endl;
1978 outputStream << "cascade_output_stagnation_epochs=" << ann->cascade_output_stagnation_epochs << std::endl;
1979 outputStream << "cascade_candidate_change_fraction=" << ann->cascade_candidate_change_fraction << std::endl;
1980 outputStream << "cascade_candidate_stagnation_epochs=" << ann->cascade_candidate_stagnation_epochs << std::endl;
1981 outputStream << "cascade_max_out_epochs=" << ann->cascade_max_out_epochs << std::endl;
1982 /* #if FANN_VERSION_MINOR > 1 */
1983 outputStream << "cascade_min_out_epochs=" << ann->cascade_min_out_epochs << std::endl;
1984 /* #endif */
1985 outputStream << "cascade_max_cand_epochs=" << ann->cascade_max_cand_epochs << std::endl;
1986 /* #if FANN_VERSION_MINOR > 1 */
1987 outputStream << "cascade_min_cand_epochs=" << ann->cascade_min_cand_epochs << std::endl;
1988 /* #endif */
1989 outputStream << "cascade_num_candidate_groups=" << ann->cascade_num_candidate_groups << std::endl;
1990
1991 #ifndef FIXEDFANN
1992 if(save_as_fixed)
1993 {
1994 outputStream << "bit_fail_limit=" << (int) floor((ann->bit_fail_limit * fixed_multiplier) + 0.5) << std::endl;
1995 outputStream << "cascade_candidate_limit=" << (int) floor((ann->cascade_candidate_limit * fixed_multiplier) + 0.5) << std::endl;
1996 outputStream << "cascade_weight_multiplier=" << (int) floor((ann->cascade_weight_multiplier * fixed_multiplier) + 0.5) << std::endl;
1997 }
1998 else
1999 #endif
2000 {
2001 outputStream << "bit_fail_limit=" << ann->bit_fail_limit << std::endl;
2002 outputStream << "cascade_candidate_limit=" << ann->cascade_candidate_limit << std::endl;
2003 outputStream << "cascade_weight_multiplier=" << ann->cascade_weight_multiplier * fixed_multiplier << std::endl;
2004 }
2005
2006 outputStream << "cascade_activation_functions_count=" << ann->cascade_activation_functions_count << std::endl;
2007 outputStream << "cascade_activation_functions=";
2008 for(i = 0; i < ann->cascade_activation_functions_count; i++)
2009 outputStream << ann->cascade_activation_functions[i] << " ";
2010 outputStream << std::endl;
2011
2012 outputStream << "cascade_activation_steepnesses_count=" << ann->cascade_activation_steepnesses_count << std::endl;
2013 outputStream << "cascade_activation_steepnesses=";
2014 for(i = 0; i < ann->cascade_activation_steepnesses_count; i++)
2015 {
2016 #ifndef FIXEDFANN
2017 if(save_as_fixed)
2018 outputStream << (int) floor((ann->cascade_activation_steepnesses[i] * fixed_multiplier) + 0.5) << " ";
2019 else
2020 #endif
2021 //for floatfann #define FANNPRINTF "%.20e"
2022 //for fixedfann #define FANNPRINTF "%d"
2023 //for doublefann #define FANNPRINTF "%.20e"
2024 //fprintf(conf, FANNPRINTF" ", ann->cascade_activation_steepnesses[i]);
2025 outputStream << ann->cascade_activation_steepnesses[i] << " ";
2026 }
2027 outputStream << std::endl;
2028
2029 outputStream << "layer_sizes=";
2030 for(layer_it = ann->first_layer; layer_it != ann->last_layer; layer_it++)
2031 {
2032 /* the number of neurons in the layers (in the last layer, there is always one too many neurons, because of an unused bias) */
2033 outputStream << (int)(layer_it->last_neuron - layer_it->first_neuron) << " ";
2034 }
2035 outputStream << std::endl;
2036
2037 #ifndef FIXEDFANN
2038 /* 2.1 */
2039 #define SCALE_SAVE( what, where ) \
2040 outputStream << #what << "_" << #where << "="; \
2041 for( i = 0; i < ann->num_##where##put; i++ ) \
2042 outputStream << ann->what##_##where[ i ] << " "; \
2043 outputStream << std::endl;
2044
2045 if(!save_as_fixed){
2046 if(ann->scale_mean_in != NULL){
2047 outputStream << "scale_included=1" << std::endl;
2048 SCALE_SAVE( scale_mean, in )
2049 SCALE_SAVE( scale_deviation, in )
2050 SCALE_SAVE( scale_new_min, in )
2051 SCALE_SAVE( scale_factor, in )
2052
2053 SCALE_SAVE( scale_mean, out )
2054 SCALE_SAVE( scale_deviation, out )
2055 SCALE_SAVE( scale_new_min, out )
2056 SCALE_SAVE( scale_factor, out )
2057 }
2058 else
2059 outputStream << "scale_included=0" << std::endl;
2060 }
2061 #undef SCALE_SAVE
2062 #endif
2063
2064 /* 2.0 */
2065 outputStream << "neurons (num_inputs, activation_function, activation_steepness)=";
2066 for(layer_it = ann->first_layer; layer_it != ann->last_layer; layer_it++)
2067 {
2068 /* the neurons */
2069 for(neuron_it = layer_it->first_neuron; neuron_it != layer_it->last_neuron; neuron_it++)
2070 {
2071 #ifndef FIXEDFANN
2072 if(save_as_fixed)
2073 {
2074 outputStream << "(" << neuron_it->last_con - neuron_it->first_con << ", " << neuron_it->activation_function << ", " << (int) floor((neuron_it->activation_steepness * fixed_multiplier) + 0.5) << ") ";
2075 }
2076 else
2077 {
2078 outputStream << "(" << neuron_it->last_con - neuron_it->first_con << ", " << neuron_it->activation_function << ", " << neuron_it->activation_steepness << ") ";
2079 }
2080 #else
2081 outputStream << "(" << neuron_it->last_con - neuron_it->first_con << ", " << neuron_it->activation_function << ", " << neuron_it->activation_steepness << ") ";
2082 #endif
2083 }
2084 }
2085 outputStream << std::endl;
2086
2087 connected_neurons = ann->connections;
2088 weights = ann->weights;
2089 first_neuron = ann->first_layer->first_neuron;
2090
2091 /* Now save all the connections.
2092 * We only need to save the source and the weight,
2093 * since the destination is given by the order.
2094 *
2095 * The weight is not saved binary due to differences
2096 * in binary definition of floating point numbers.
2097 * Especially an iPAQ does not use the same binary
2098 * representation as an i386 machine.
2099 */
2100 outputStream << "connections (connected_to_neuron, weight)=";
2101 for(i = 0; i < ann->total_connections; i++)
2102 {
2103 #ifndef FIXEDFANN
2104 if(save_as_fixed)
2105 {
2106 /* save the connection "(source weight) " */
2107 outputStream << "(" << (int)(connected_neurons[i] - first_neuron) << ", " << (int) floor((weights[i] * fixed_multiplier) + 0.5) << ") ";
2108 }
2109 else
2110 {
2111 /* save the connection "(source weight) " */
2112 outputStream << "(" << (int)(connected_neurons[i] - first_neuron) << ", " << weights[i] << ") ";
2113 }
2114 #else
2115 /* save the connection "(source weight) " */
2116 outputStream << "(" << (int)(connected_neurons[i] - first_neuron) << ", " << weights[i] << ") ";
2117 #endif
2118 }
2119 outputStream << std::endl;
2120
2121 return calculated_decimal_point;
2122 }
2123
2124 bool save(const std::string &configuration_file, const std::vector<double> &offset, const std::vector<double> &scale, std::map<std::string,short> &classValueMap, const std::vector<std::string> &nameVector, const std::vector<std::string> &bandNames){
2125 bool result=false;
2126 std::ofstream fileStream(configuration_file);
2127 if(fileStream)
2128 result=ann_serialize_model(fileStream, offset, scale, classValueMap, nameVector, bandNames);
2129 fileStream.close();
2130 return result;
2131 }
2132
2133 bool ann_serialize_model(std::ostream &outputStream, const std::vector<double> &offset, const std::vector<double> &scale, std::map<std::string,short> &classValueMap, const std::vector<std::string> &nameVector, const std::vector<std::string> &bandNames)
2134 {
2135 short verbose=0;
2136 if (ann == NULL)
2137 {
2138 return false;
2139 }
2140 /* FILE *conf = fopen(configuration_file.c_str(), "w+"); */
2141
2142 /* if(!conf) */
2143 /* { */
2144 /* fann_error((struct fann_error *) ann, FANN_E_CANT_OPEN_CONFIG_W, configuration_file.c_str()); */
2145 /* return false; */
2146 /* } */
2147 /* if(fann_save_internal_fd(ann, conf, configuration_file.c_str(), 0)==-1) */
2148 if(fann_save_internal_fd(outputStream, ann, 0)==-1)
2149 return(false);
2150 if(verbose)
2151 std::cout << "writing offset: " << offset[0] << " ..." << std::endl;
2152 outputStream << "offset=";
2153 for(int index=0;index<offset.size();++index){
2154 if(index<offset.size()-1)
2155 outputStream << offset[index] << ", ";
2156 else
2157 outputStream << offset[index] << std::endl;
2158 }
2159 if(verbose)
2160 std::cout << "writing scale: " << scale[0] << " ..." << std::endl;
2161 outputStream << "scale=";
2162 for(int index=0;index<scale.size();++index){
2163 if(index<scale.size()-1)
2164 outputStream << scale[index] << ", ";
2165 else
2166 outputStream << scale[index] << std::endl;
2167 }
2168 //classValueMap
2169 if(verbose)
2170 std::cout << "writing classValueMap: " << classValueMap.begin()->first << " ..." << std::endl;
2171 outputStream << "classValueMap=";
2172 std::map<std::string,short>::const_iterator mapit=classValueMap.begin();
2173 while(mapit!=classValueMap.end()){
2174 if(mapit!=--classValueMap.end())
2175 outputStream << mapit->first << ":" << mapit->second << ", ";
2176 else
2177 outputStream << (mapit->first) << ":" << mapit->second << std::endl;
2178 ++mapit;
2179 }
2180 //nameVector
2181 if(verbose)
2182 std::cout << "writing nameVector: " << nameVector[0] << " ..." << std::endl;
2183 outputStream << "nameVector=";
2184 for(int index=0;index<nameVector.size();++index){
2185 if(index<nameVector.size()-1)
2186 outputStream << nameVector[index] << ", ";
2187 else
2188 outputStream << nameVector[index] << std::endl;
2189 }
2190 //bandNames
2191 if(bandNames.size()){
2192 if(verbose)
2193 std::cout << "writing bandNames: " << bandNames[0] << " ..." << std::endl;
2194 outputStream << "bandNames=";
2195 for(int index=0;index<bandNames.size();++index){
2196 if(index<bandNames.size()-1)
2197 outputStream << bandNames[index] << ", ";
2198 else
2199 outputStream << bandNames[index] << std::endl;
2200 }
2201 }
2202 return true;
2203 }
2204
2205 /* Method: save_to_fixed
2206
2207 Saves the entire network to a configuration file.
2208 But it is saved in fixed point format no matter which
2209 format it is currently in.
2210
2211 This is usefull for training a network in floating points,
2212 and then later executing it in fixed point.
2213
2214 The function returns the bit position of the fix point, which
2215 can be used to find out how accurate the fixed point network will be.
2216 A high value indicates high precision, and a low value indicates low
2217 precision.
2218
2219 A negative value indicates very low precision, and a very
2220 strong possibility for overflow.
2221 (the actual fix point will be set to 0, since a negative
2222 fix point does not make sence).
2223
2224 Generally, a fix point lower than 6 is bad, and should be avoided.
2225 The best way to avoid this, is to have less connections to each neuron,
2226 or just less neurons in each layer.
2227
2228 The fixed point use of this network is only intended for use on machines that
2229 have no floating point processor, like an iPAQ. On normal computers the floating
2230 point version is actually faster.
2231
2232 See also:
2233 <create_from_file>, <save>, <fann_save_to_fixed>
2234
2235 This function appears in FANN >= 1.0.0.
2236 */
2237 int save_to_fixed(const std::string &configuration_file)
2238 {
2239 int fixpoint = 0;
2240 if (ann != NULL)
2241 {
2242 fixpoint = fann_save_to_fixed(ann, configuration_file.c_str());
2243 }
2244 return fixpoint;
2245 }
2246
2247 #ifndef FIXEDFANN
2248 /* Method: train
2249
2250 Train one iteration with a set of inputs, and a set of desired outputs.
2251 This training is always incremental training (see <FANN::training_algorithm_enum>),
2252 since only one pattern is presented.
2253
2254 Parameters:
2255 ann - The neural network structure
2256 input - an array of inputs. This array must be exactly <fann_get_num_input> long.
2257 desired_output - an array of desired outputs. This array must be exactly <fann_get_num_output> long.
2258
2259 See also:
2260 <train_on_data>, <train_epoch>, <fann_train>
2261
2262 This function appears in FANN >= 1.0.0.
2263 */
2264 void train(fann_type *input, fann_type *desired_output)
2265 {
2266 if (ann != NULL)
2267 {
2268 fann_train(ann, input, desired_output);
2269 }
2270 }
2271
2272 /* Method: train_epoch
2273 Train one epoch with a set of training data.
2274
2275 Train one epoch with the training data stored in data. One epoch is where all of
2276 the training data is considered exactly once.
2277
2278 This function returns the MSE error as it is calculated either before or during
2279 the actual training. This is not the actual MSE after the training epoch, but since
2280 calculating this will require to go through the entire training set once more, it is
2281 more than adequate to use this value during training.
2282
2283 The training algorithm used by this function is chosen by the <fann_set_training_algorithm>
2284 function.
2285
2286 See also:
2287 <train_on_data>, <test_data>, <fann_train_epoch>
2288
2289 This function appears in FANN >= 1.2.0.
2290 */
2291 float train_epoch(const training_data &data)
2292 {
2293 float mse = 0.0f;
2294 if ((ann != NULL) && (data.train_data != NULL))
2295 {
2296 mse = fann_train_epoch(ann, data.train_data);
2297 }
2298 return mse;
2299 }
2300
2301 /* Method: train_on_data
2302
2303 Trains on an entire dataset, for a period of time.
2304
2305 This training uses the training algorithm chosen by <set_training_algorithm>,
2306 and the parameters set for these training algorithms.
2307
2308 Parameters:
2309 ann - The neural network
2310 data - The data, which should be used during training
2311 max_epochs - The maximum number of epochs the training should continue
2312 epochs_between_reports - The number of epochs between printing a status report to stdout.
2313 A value of zero means no reports should be printed.
2314 desired_error - The desired <get_MSE> or <get_bit_fail>, depending on which stop function
2315 is chosen by <set_train_stop_function>.
2316
2317 Instead of printing out reports every epochs_between_reports, a callback function can be called
2318 (see <set_callback>).
2319
2320 See also:
2321 <train_on_file>, <train_epoch>, <fann_train_on_data>
2322
2323 This function appears in FANN >= 1.0.0.
2324 */
2325 void train_on_data(const training_data &data, unsigned int max_epochs,
2326 unsigned int epochs_between_reports, float desired_error)
2327 {
2328 if ((ann != NULL) && (data.train_data != NULL))
2329 {
2330 fann_train_on_data(ann, data.train_data, max_epochs,
2331 epochs_between_reports, desired_error);
2332 }
2333 }
2334
2335
2336
2337 void train_on_data(const std::vector< std::vector<fann_type> >& input,
2338 const std::vector< std::vector<fann_type> >& output,
2339 bool initWeights,
2340 unsigned int max_epochs,
2341 unsigned int epochs_between_reports,
2342 float desired_error)
2343 {
2344 if ((ann != NULL))
2345 {
2346 training_data data;
2347 data.set_train_data(input,output);
2348 if(data.train_data != NULL){
2349 if(initWeights)
2350 init_weights(data);
2351 fann_train_on_data(ann, data.train_data, max_epochs,
2352 epochs_between_reports, desired_error);
2353 }
2354 }
2355 }
2356
2357 void train_on_data(const std::vector< Vector2d<fann_type> >& input,
2358 unsigned int num_data,
2359 bool initWeights,
2360 unsigned int max_epochs,
2361 unsigned int epochs_between_reports,
2362 float desired_error)
2363 {
2364 if ((ann != NULL))
2365 {
2366 training_data data;
2367 data.set_train_data(input,num_data);
2368 if(data.train_data != NULL){
2369 if(initWeights)
2370 init_weights(data);
2371 fann_train_on_data(ann, data.train_data, max_epochs,
2372 epochs_between_reports, desired_error);
2373 }
2374 }
2375 }
2376
2377 //cross validation for classification
2378 float cross_validation(std::vector< Vector2d<fann_type> >& trainingFeatures,
2379 unsigned int ntraining,
2380 unsigned short cv,
2381 unsigned int max_epochs,
2382 float desired_error,
2383 std::vector<unsigned short>& referenceVector,
2384 std::vector<unsigned short>& outputVector,
2385 short verbose=0)
2386 {
2387 referenceVector.clear();
2388 outputVector.clear();
2389 assert(cv<ntraining);
2390 int nclass=trainingFeatures.size();
2391 std::vector< Vector2d<float> > testFeatures(nclass);
2392 int testclass=0;//class to leave out
2393 // int testsample=0;//sample to leave out
2394 int nrun=(cv>1)? cv : ntraining;
2395 if(nrun>ntraining)
2396 nrun=ntraining;
2397 for(int irun=0;irun<nrun;++irun){
2398 if(verbose>1)
2399 std::cout << "run " << irun << std::endl;
2400 //reset training sample from last run
2401 if(verbose>1)
2402 std::cout << "reset training sample from last run" << std::endl;
2403 for(int iclass=0;iclass<nclass;++iclass){
2404 while(testFeatures[iclass].size()){
2405 trainingFeatures[iclass].push_back(testFeatures[iclass].back());
2406 testFeatures[iclass].pop_back();
2407 }
2408 if(verbose>1){
2409 std::cout << "training size " << iclass << ": " << trainingFeatures[iclass].size() << std::endl;
2410 std::cout << "test size " << iclass << ": " << testFeatures[iclass].size() << std::endl;
2411 }
2412 assert(trainingFeatures[iclass].size());
2413 }
2414 //create test sample
2415 if(verbose>1)
2416 std::cout << "create test sample" << std::endl;
2417 unsigned int nsample=0;
2418 int ntest=(cv>1)? ntraining/cv : 1; //n-fold cross validation or leave-one-out
2419 while(nsample<ntest){
2420 // if(index>=trainingFeatures[testclass].size()){
2421 // index=0;
2422 // }
2423 testFeatures[testclass].push_back(trainingFeatures[testclass][0]);
2424 trainingFeatures[testclass].erase(trainingFeatures[testclass].begin());
2425 if(!trainingFeatures[testclass].size())
2426 std::cout << "Error: testclass " << testclass << " has no training" << std::endl;
2427 assert(trainingFeatures[testclass].size());
2428 ++nsample;
2429 if(static_cast<float>(trainingFeatures[testclass].size())/static_cast<float>(testFeatures[testclass].size())<=(cv-1)){
2430 if(verbose>1){
2431 std::cout << "training size " << testclass << ": " << trainingFeatures[testclass].size() << std::endl;
2432 std::cout << "test size " << testclass << ": " << testFeatures[testclass].size() << std::endl;
2433 }
2434 testclass=(testclass+1)%nclass;
2435 }
2436 }
2437 assert(nsample==ntest);
2438 //training with left out training set
2439 if(verbose>1)
2440 std::cout << std::endl << "Set training data" << std::endl;
2441 bool initWeights=true;
2442 unsigned int epochs_between_reports=0;
2443 train_on_data(trainingFeatures,ntraining-ntest,initWeights, max_epochs,
2444 epochs_between_reports, desired_error);
2445 //cross validation with testFeatures
2446 if(verbose>1)
2447 std::cout << std::endl << "Cross validation" << std::endl;
2448
2449 std::vector<float> result(nclass);
2450 int maxClass=-1;
2451 for(int iclass=0;iclass<testFeatures.size();++iclass){
2452 assert(trainingFeatures[iclass].size());
2453 for(int isample=0;isample<testFeatures[iclass].size();++isample){
2454 result=run(testFeatures[iclass][isample]);
2455 //search class with maximum posterior probability
2456 float maxP=-1;
2457 for(int ic=0;ic<nclass;++ic){
2458 float pv=(result[ic]+1.0)/2.0;//bring back to scale [0,1]
2459 if(pv>maxP){
2460 maxP=pv;
2461 maxClass=ic;
2462 }
2463 }
2464 assert(maxP>=0);
2465 referenceVector.push_back(iclass);
2466 outputVector.push_back(maxClass);
2467 }
2468 }
2469
2470 // rmse+=test_data(testFeatures,ntest);
2471 // if(verbose>1)
2472 // std::cout << std::endl << "rmse: " << rmse << std::endl;
2473 }
2474 // rmse/=nrun;
2475 //reset from very last run
2476 for(int iclass=0;iclass<nclass;++iclass){
2477 while(testFeatures[iclass].size()){
2478 trainingFeatures[iclass].push_back(testFeatures[iclass].back());
2479 testFeatures[iclass].pop_back();
2480 }
2481 }
2482 // return(rmse);
2483 return 0;
2484 }
2485
2486 //cross validation for regresssion
2487 float cross_validation(std::vector< std::vector<fann_type> >& input,
2488 std::vector< std::vector<fann_type> >& output,
2489 unsigned short cv,
2490 unsigned int max_epochs,
2491 float desired_error,
2492 std::vector< std::vector<fann_type> >& referenceVector,
2493 std::vector< std::vector<fann_type> >& outputVector,
2494 short verbose=0)
2495 {
2496 assert(input.size());
2497 assert(output.size()==input.size());
2498 unsigned int ntraining=input.size();
2499 unsigned int noutput=output[0].size();
2500 referenceVector.clear();
2501 outputVector.clear();
2502 assert(cv<ntraining);
2503 std::vector< std::vector<fann_type> > testInput;
2504 std::vector< std::vector<fann_type> > testOutput;
2505 // int testsample=0;//sample to leave out
2506 int nrun=(cv>1)? cv : ntraining;
2507 if(nrun>ntraining)
2508 nrun=ntraining;
2509 for(int irun=0;irun<nrun;++irun){
2510 if(verbose>1)
2511 std::cout << "run " << irun << std::endl;
2512 //reset training sample from last run
2513 if(verbose>1)
2514 std::cout << "reset training sample from last run" << std::endl;
2515 while(testInput.size()){
2516 input.push_back(testInput.back());
2517 testInput.pop_back();
2518 }
2519 while(testOutput.size()){
2520 output.push_back(testOutput.back());
2521 testOutput.pop_back();
2522 }
2523 assert(testInput.size()==testOutput.size());
2524 if(verbose>1){
2525 std::cout << "training size: " << input.size() << std::endl;
2526 std::cout << "test size: " << testInput.size() << std::endl;
2527 }
2528 assert(input.size());
2529 //create test sample
2530 if(verbose>1)
2531 std::cout << "create test sample" << std::endl;
2532 unsigned int nsample=0;
2533 int ntest=(cv>1)? ntraining/cv : 1; //n-fold cross validation or leave-one-out
2534 while(nsample<ntest){
2535 testInput.push_back(input[0]);
2536 testOutput.push_back(output[0]);
2537 input.erase(input.begin());
2538 output.erase(output.begin());
2539 assert(input.size());
2540 assert(output.size());
2541 assert(input.size()==output.size());
2542 ++nsample;
2543 }
2544 assert(nsample==ntest);
2545 assert(testInput.size()==testOutput.size());
2546 //training with left out training set
2547 if(verbose>1)
2548 std::cout << std::endl << "Set training data" << std::endl;
2549 bool initWeights=true;
2550 unsigned int epochs_between_reports=0;
2551
2552 train_on_data(input,output,initWeights, max_epochs,
2553 epochs_between_reports, desired_error);
2554 //cross validation with testFeatures
2555 if(verbose>1)
2556 std::cout << std::endl << "Cross validation" << std::endl;
2557
2558 std::vector<fann_type> result(noutput);
2559 for(int isample=0;isample<testInput.size();++isample){
2560 result=run(testInput[isample]);
2561 referenceVector.push_back(testOutput[isample]);
2562 outputVector.push_back(result);
2563 }
2564 }
2565 //reset from very last run
2566 while(testInput.size()){
2567 input.push_back(testInput.back());
2568 testInput.pop_back();
2569 }
2570 while(testOutput.size()){
2571 output.push_back(testOutput.back());
2572 testOutput.pop_back();
2573 }
2574 return 0;
2575 }
2576
2577 /* Method: train_on_file
2578
2579 Does the same as <train_on_data>, but reads the training data directly from a file.
2580
2581 See also:
2582 <train_on_data>, <fann_train_on_file>
2583
2584 This function appears in FANN >= 1.0.0.
2585 */
2586 void train_on_file(const std::string &filename, unsigned int max_epochs,
2587 unsigned int epochs_between_reports, float desired_error)
2588 {
2589 if (ann != NULL)
2590 {
2591 fann_train_on_file(ann, filename.c_str(),
2592 max_epochs, epochs_between_reports, desired_error);
2593 }
2594 }
2595 #endif /* NOT FIXEDFANN */
2596
2597 /* Method: test
2598
2599 Test with a set of inputs, and a set of desired outputs.
2600 This operation updates the mean square error, but does not
2601 change the network in any way.
2602
2603 See also:
2604 <test_data>, <train>, <fann_test>
2605
2606 This function appears in FANN >= 1.0.0.
2607 */
2608 fann_type * test(fann_type *input, fann_type *desired_output)
2609 {
2610 fann_type * output = NULL;
2611 if (ann != NULL)
2612 {
2613 output = fann_test(ann, input, desired_output);
2614 }
2615 return output;
2616 }
2617
2618 /* Method: test_data
2619
2620 Test a set of training data and calculates the MSE for the training data.
2621
2622 This function updates the MSE and the bit fail values.
2623
2624 See also:
2625 <test>, <get_MSE>, <get_bit_fail>, <fann_test_data>
2626
2627 This function appears in FANN >= 1.2.0.
2628 */
2629 float test_data(const training_data &data)
2630 {
2631 float mse = 0.0f;
2632 if ((ann != NULL) && (data.train_data != NULL))
2633 {
2634 mse = fann_test_data(ann, data.train_data);
2635 }
2636 return mse;
2637 }
2638
2639 float test_data(const std::vector< Vector2d<fann_type> >& input, unsigned int num_data)
2640 {
2641 assert(num_data);
2642 assert(input.size());
2643 unsigned int num_class=input.size();
2644 assert(input[0].size());
2645 unsigned int num_input=input[0][0].size();
2646 unsigned int num_output=num_class;
2647 struct fann_train_data *data =
2648 (struct fann_train_data *)malloc(sizeof(struct fann_train_data));
2649 data->input = (fann_type **)calloc(num_data, sizeof(fann_type *));
2650 data->output = (fann_type **)calloc(num_data, sizeof(fann_type *));
2651
2652 data->num_data = num_data;
2653 data->num_input = num_input;
2654 data->num_output = num_output;
2655
2656 fann_type *data_input = (fann_type *)calloc(num_input*num_data, sizeof(fann_type));
2657 fann_type *data_output = (fann_type *)calloc(num_output*num_data, sizeof(fann_type));
2658
2659 unsigned int isample=0;
2660 for(int iclass=0;iclass<num_class;++iclass){
2661 for(int csample=0;csample<input[iclass].size();++csample){
2662 data->input[isample] = data_input;
2663 data_input += num_input;
2664 for(int iband=0;iband<input[iclass][csample].size();++iband){
2665 assert(input[iclass][csample].size()==num_input);
2666 data->input[isample][iband] = input[iclass][csample][iband];
2667 }
2668 data->output[isample] = data_output;
2669 data_output += num_output;
2670 for(int ic=0;ic<num_output;++ic){
2671 //for single neuron output:
2672 // data->output[isample][ic]=2.0/(num_class-1)*(iclass-(num_class-1)/2.0);
2673 if(ic==iclass)
2674 data->output[isample][ic] = 1;
2675 else
2676 data->output[isample][ic] = -1;
2677 }
2678 ++isample;
2679 }
2680 }
2681 FANN::training_data trainingData;
2682 trainingData.train_data = data;
2683 return test_data(trainingData);
2684 }
2685
2686
2687 /* Method: get_MSE
2688 Reads the mean square error from the network.
2689
2690 Reads the mean square error from the network. This value is calculated during
2691 training or testing, and can therefore sometimes be a bit off if the weights
2692 have been changed since the last calculation of the value.
2693
2694 See also:
2695 <test_data>, <fann_get_MSE>
2696
2697 This function appears in FANN >= 1.1.0.
2698 */
2699 float get_MSE()
2700 {
2701 float mse = 0.0f;
2702 if (ann != NULL)
2703 {
2704 mse = fann_get_MSE(ann);
2705 }
2706 return mse;
2707 }
2708
2709 /* Method: reset_MSE
2710
2711 Resets the mean square error from the network.
2712
2713 This function also resets the number of bits that fail.
2714
2715 See also:
2716 <get_MSE>, <get_bit_fail_limit>, <fann_reset_MSE>
2717
2718 This function appears in FANN >= 1.1.0
2719 */
2720 void reset_MSE()
2721 {
2722 if (ann != NULL)
2723 {
2724 fann_reset_MSE(ann);
2725 }
2726 }
2727
2728 /* Method: set_callback
2729
2730 Sets the callback function for use during training. The user_data is passed to
2731 the callback. It can point to arbitrary data that the callback might require and
2732 can be NULL if it is not used.
2733
2734 See <FANN::callback_type> for more information about the callback function.
2735
2736 The default callback function simply prints out some status information.
2737
2738 This function appears in FANN >= 2.0.0.
2739 */
2740 void set_callback(callback_type callback, void *user_data)
2741 {
2742 if (ann != NULL)
2743 {
2744 // Allocated data is also deleted in the destroy method called by the destructor
2745 user_context *user_instance = static_cast<user_context *>(fann_get_user_data(ann));
2746 if (user_instance != NULL)
2747 delete user_instance;
2748
2749 user_instance = new user_context();
2750 user_instance->user_callback = callback;
2751 user_instance->user_data = user_data;
2752 user_instance->net = this;
2753 fann_set_user_data(ann, user_instance);
2754
2755 if (callback != NULL)
2756 fann_set_callback(ann, &FANN::neural_net::internal_callback);
2757 else
2758 fann_set_callback(ann, NULL);
2759 }
2760 }
2761
2762 /* Method: print_parameters
2763
2764 Prints all of the parameters and options of the neural network
2765
2766 See also:
2767 <fann_print_parameters>
2768
2769 This function appears in FANN >= 1.2.0.
2770 */
2771 void print_parameters()
2772 {
2773 if (ann != NULL)
2774 {
2775 fann_print_parameters(ann);
2776 }
2777 }
2778
2779 /* Method: get_training_algorithm
2780
2781 Return the training algorithm as described by <FANN::training_algorithm_enum>.
2782 This training algorithm is used by <train_on_data> and associated functions.
2783
2784 Note that this algorithm is also used during <cascadetrain_on_data>, although only
2785 FANN::TRAIN_RPROP and FANN::TRAIN_QUICKPROP is allowed during cascade training.
2786
2787 The default training algorithm is FANN::TRAIN_RPROP.
2788
2789 See also:
2790 <set_training_algorithm>, <FANN::training_algorithm_enum>,
2791 <fann_get_training_algorithm>
2792
2793 This function appears in FANN >= 1.0.0.
2794 */
2795 training_algorithm_enum get_training_algorithm()
2796 {
2797 fann_train_enum training_algorithm = FANN_TRAIN_INCREMENTAL;
2798 if (ann != NULL)
2799 {
2800 training_algorithm = fann_get_training_algorithm(ann);
2801 }
2802 return static_cast<training_algorithm_enum>(training_algorithm);
2803 }
2804
2805 /* Method: set_training_algorithm
2806
2807 Set the training algorithm.
2808
2809 More info available in <get_training_algorithm>
2810
2811 This function appears in FANN >= 1.0.0.
2812 */
2813 void set_training_algorithm(training_algorithm_enum training_algorithm)
2814 {
2815 if (ann != NULL)
2816 {
2817 fann_set_training_algorithm(ann,
2818 static_cast<fann_train_enum>(training_algorithm));
2819 }
2820 }
2821
2822 /* Method: get_learning_rate
2823
2824 Return the learning rate.
2825
2826 The learning rate is used to determine how aggressive training should be for some of the
2827 training algorithms (FANN::TRAIN_INCREMENTAL, FANN::TRAIN_BATCH, FANN::TRAIN_QUICKPROP).
2828 Do however note that it is not used in FANN::TRAIN_RPROP.
2829
2830 The default learning rate is 0.7.
2831
2832 See also:
2833 <set_learning_rate>, <set_training_algorithm>,
2834 <fann_get_learning_rate>
2835
2836 This function appears in FANN >= 1.0.0.
2837 */
2838 float get_learning_rate()
2839 {
2840 float learning_rate = 0.0f;
2841 if (ann != NULL)
2842 {
2843 learning_rate = fann_get_learning_rate(ann);
2844 }
2845 return learning_rate;
2846 }
2847
2848 /* Method: set_learning_rate
2849
2850 Set the learning rate.
2851
2852 More info available in <get_learning_rate>
2853
2854 This function appears in FANN >= 1.0.0.
2855 */
2856 void set_learning_rate(float learning_rate)
2857 {
2858 if (ann != NULL)
2859 {
2860 fann_set_learning_rate(ann, learning_rate);
2861 }
2862 }
2863
2864 /*************************************************************************************************************/
2865
2866 /* Method: get_activation_function
2867
2868 Get the activation function for neuron number *neuron* in layer number *layer*,
2869 counting the input layer as layer 0.
2870
2871 It is not possible to get activation functions for the neurons in the input layer.
2872
2873 Information about the individual activation functions is available at <FANN::activation_function_enum>.
2874
2875 Returns:
2876 The activation function for the neuron or -1 if the neuron is not defined in the neural network.
2877
2878 See also:
2879 <set_activation_function_layer>, <set_activation_function_hidden>,
2880 <set_activation_function_output>, <set_activation_steepness>,
2881 <set_activation_function>, <fann_get_activation_function>
2882
2883 This function appears in FANN >= 2.1.0
2884 */
2885 activation_function_enum get_activation_function(int layer, int neuron)
2886 {
2887 unsigned int activation_function = 0;
2888 if (ann != NULL)
2889 {
2890 activation_function = fann_get_activation_function(ann, layer, neuron);
2891 }
2892 return static_cast<activation_function_enum>(activation_function);
2893 }
2894
2895 /* Method: set_activation_function
2896
2897 Set the activation function for neuron number *neuron* in layer number *layer*,
2898 counting the input layer as layer 0.
2899
2900 It is not possible to set activation functions for the neurons in the input layer.
2901
2902 When choosing an activation function it is important to note that the activation
2903 functions have different range. FANN::SIGMOID is e.g. in the 0 - 1 range while
2904 FANN::SIGMOID_SYMMETRIC is in the -1 - 1 range and FANN::LINEAR is unbound.
2905
2906 Information about the individual activation functions is available at <FANN::activation_function_enum>.
2907
2908 The default activation function is FANN::SIGMOID_STEPWISE.
2909
2910 See also:
2911 <set_activation_function_layer>, <set_activation_function_hidden>,
2912 <set_activation_function_output>, <set_activation_steepness>,
2913 <get_activation_function>, <fann_set_activation_function>
2914
2915 This function appears in FANN >= 2.0.0.
2916 */
2917 void set_activation_function(activation_function_enum activation_function, int layer, int neuron)
2918 {
2919 if (ann != NULL)
2920 {
2921 fann_set_activation_function(ann,
2922 static_cast<fann_activationfunc_enum>(activation_function), layer, neuron);
2923 }
2924 }
2925
2926 /* Method: set_activation_function_layer
2927
2928 Set the activation function for all the neurons in the layer number *layer*,
2929 counting the input layer as layer 0.
2930
2931 It is not possible to set activation functions for the neurons in the input layer.
2932
2933 See also:
2934 <set_activation_function>, <set_activation_function_hidden>,
2935 <set_activation_function_output>, <set_activation_steepness_layer>,
2936 <fann_set_activation_function_layer>
2937
2938 This function appears in FANN >= 2.0.0.
2939 */
2940 void set_activation_function_layer(activation_function_enum activation_function, int layer)
2941 {
2942 if (ann != NULL)
2943 {
2944 fann_set_activation_function_layer(ann,
2945 static_cast<fann_activationfunc_enum>(activation_function), layer);
2946 }
2947 }
2948
2949 /* Method: set_activation_function_hidden
2950
2951 Set the activation function for all of the hidden layers.
2952
2953 See also:
2954 <set_activation_function>, <set_activation_function_layer>,
2955 <set_activation_function_output>, <set_activation_steepness_hidden>,
2956 <fann_set_activation_function_hidden>
2957
2958 This function appears in FANN >= 1.0.0.
2959 */
2960 void set_activation_function_hidden(activation_function_enum activation_function)
2961 {
2962 if (ann != NULL)
2963 {
2964 fann_set_activation_function_hidden(ann,
2965 static_cast<fann_activationfunc_enum>(activation_function));
2966 }
2967 }
2968
2969 /* Method: set_activation_function_output
2970
2971 Set the activation function for the output layer.
2972
2973 See also:
2974 <set_activation_function>, <set_activation_function_layer>,
2975 <set_activation_function_hidden>, <set_activation_steepness_output>,
2976 <fann_set_activation_function_output>
2977
2978 This function appears in FANN >= 1.0.0.
2979 */
2980 void set_activation_function_output(activation_function_enum activation_function)
2981 {
2982 if (ann != NULL)
2983 {
2984 fann_set_activation_function_output(ann,
2985 static_cast<fann_activationfunc_enum>(activation_function));
2986 }
2987 }
2988
2989 /* Method: get_activation_steepness
2990
2991 Get the activation steepness for neuron number *neuron* in layer number *layer*,
2992 counting the input layer as layer 0.
2993
2994 It is not possible to get activation steepness for the neurons in the input layer.
2995
2996 The steepness of an activation function says something about how fast the activation function
2997 goes from the minimum to the maximum. A high value for the activation function will also
2998 give a more agressive training.
2999
3000 When training neural networks where the output values should be at the extremes (usually 0 and 1,
3001 depending on the activation function), a steep activation function can be used (e.g. 1.0).
3002
3003 The default activation steepness is 0.5.
3004
3005 Returns:
3006 The activation steepness for the neuron or -1 if the neuron is not defined in the neural network.
3007
3008 See also:
3009 <set_activation_steepness_layer>, <set_activation_steepness_hidden>,
3010 <set_activation_steepness_output>, <set_activation_function>,
3011 <set_activation_steepness>, <fann_get_activation_steepness>
3012
3013 This function appears in FANN >= 2.1.0
3014 */
3015 fann_type get_activation_steepness(int layer, int neuron)
3016 {
3017 fann_type activation_steepness = 0;
3018 if (ann != NULL)
3019 {
3020 activation_steepness = fann_get_activation_steepness(ann, layer, neuron);
3021 }
3022 return activation_steepness;
3023 }
3024
3025 /* Method: set_activation_steepness
3026
3027 Set the activation steepness for neuron number *neuron* in layer number *layer*,
3028 counting the input layer as layer 0.
3029
3030 It is not possible to set activation steepness for the neurons in the input layer.
3031
3032 The steepness of an activation function says something about how fast the activation function
3033 goes from the minimum to the maximum. A high value for the activation function will also
3034 give a more agressive training.
3035
3036 When training neural networks where the output values should be at the extremes (usually 0 and 1,
3037 depending on the activation function), a steep activation function can be used (e.g. 1.0).
3038
3039 The default activation steepness is 0.5.
3040
3041 See also:
3042 <set_activation_steepness_layer>, <set_activation_steepness_hidden>,
3043 <set_activation_steepness_output>, <set_activation_function>,
3044 <get_activation_steepness>, <fann_set_activation_steepness>
3045
3046 This function appears in FANN >= 2.0.0.
3047 */
3048 void set_activation_steepness(fann_type steepness, int layer, int neuron)
3049 {
3050 if (ann != NULL)
3051 {
3052 fann_set_activation_steepness(ann, steepness, layer, neuron);
3053 }
3054 }
3055
3056 /* Method: set_activation_steepness_layer
3057
3058 Set the activation steepness all of the neurons in layer number *layer*,
3059 counting the input layer as layer 0.
3060
3061 It is not possible to set activation steepness for the neurons in the input layer.
3062
3063 See also:
3064 <set_activation_steepness>, <set_activation_steepness_hidden>,
3065 <set_activation_steepness_output>, <set_activation_function_layer>,
3066 <fann_set_activation_steepness_layer>
3067
3068 This function appears in FANN >= 2.0.0.
3069 */
3070 void set_activation_steepness_layer(fann_type steepness, int layer)
3071 {
3072 if (ann != NULL)
3073 {
3074 fann_set_activation_steepness_layer(ann, steepness, layer);
3075 }
3076 }
3077
3078 /* Method: set_activation_steepness_hidden
3079
3080 Set the steepness of the activation steepness in all of the hidden layers.
3081
3082 See also:
3083 <set_activation_steepness>, <set_activation_steepness_layer>,
3084 <set_activation_steepness_output>, <set_activation_function_hidden>,
3085 <fann_set_activation_steepness_hidden>
3086
3087 This function appears in FANN >= 1.2.0.
3088 */
3089 void set_activation_steepness_hidden(fann_type steepness)
3090 {
3091 if (ann != NULL)
3092 {
3093 fann_set_activation_steepness_hidden(ann, steepness);
3094 }
3095 }
3096
3097 /* Method: set_activation_steepness_output
3098
3099 Set the steepness of the activation steepness in the output layer.
3100
3101 See also:
3102 <set_activation_steepness>, <set_activation_steepness_layer>,
3103 <set_activation_steepness_hidden>, <set_activation_function_output>,
3104 <fann_set_activation_steepness_output>
3105
3106 This function appears in FANN >= 1.2.0.
3107 */
3108 void set_activation_steepness_output(fann_type steepness)
3109 {
3110 if (ann != NULL)
3111 {
3112 fann_set_activation_steepness_output(ann, steepness);
3113 }
3114 }
3115
3116 /*************************************************************************************************************/
3117
3118 /* Method: get_train_error_function
3119
3120 Returns the error function used during training.
3121
3122 The error functions is described further in <FANN::error_function_enum>
3123
3124 The default error function is FANN::ERRORFUNC_TANH
3125
3126 See also:
3127 <set_train_error_function>, <fann_get_train_error_function>
3128
3129 This function appears in FANN >= 1.2.0.
3130 */
3131 error_function_enum get_train_error_function()
3132 {
3133 fann_errorfunc_enum train_error_function = FANN_ERRORFUNC_LINEAR;
3134 if (ann != NULL)
3135 {
3136 train_error_function = fann_get_train_error_function(ann);
3137 }
3138 return static_cast<error_function_enum>(train_error_function);
3139 }
3140
3141 /* Method: set_train_error_function
3142
3143 Set the error function used during training.
3144
3145 The error functions is described further in <FANN::error_function_enum>
3146
3147 See also:
3148 <get_train_error_function>, <fann_set_train_error_function>
3149
3150 This function appears in FANN >= 1.2.0.
3151 */
3152 void set_train_error_function(error_function_enum train_error_function)
3153 {
3154 if (ann != NULL)
3155 {
3156 fann_set_train_error_function(ann,
3157 static_cast<fann_errorfunc_enum>(train_error_function));
3158 }
3159 }
3160
3161 /* Method: get_quickprop_decay
3162
3163 The decay is a small negative valued number which is the factor that the weights
3164 should become smaller in each iteration during quickprop training. This is used
3165 to make sure that the weights do not become too high during training.
3166
3167 The default decay is -0.0001.
3168
3169 See also:
3170 <set_quickprop_decay>, <fann_get_quickprop_decay>
3171
3172 This function appears in FANN >= 1.2.0.
3173 */
3174 float get_quickprop_decay()
3175 {
3176 float quickprop_decay = 0.0f;
3177 if (ann != NULL)
3178 {
3179 quickprop_decay = fann_get_quickprop_decay(ann);
3180 }
3181 return quickprop_decay;
3182 }
3183
3184 /* Method: set_quickprop_decay
3185
3186 Sets the quickprop decay factor.
3187
3188 See also:
3189 <get_quickprop_decay>, <fann_set_quickprop_decay>
3190
3191 This function appears in FANN >= 1.2.0.
3192 */
3193 void set_quickprop_decay(float quickprop_decay)
3194 {
3195 if (ann != NULL)
3196 {
3197 fann_set_quickprop_decay(ann, quickprop_decay);
3198 }
3199 }
3200
3201 /* Method: get_quickprop_mu
3202
3203 The mu factor is used to increase and decrease the step-size during quickprop training.
3204 The mu factor should always be above 1, since it would otherwise decrease the step-size
3205 when it was suppose to increase it.
3206
3207 The default mu factor is 1.75.
3208
3209 See also:
3210 <set_quickprop_mu>, <fann_get_quickprop_mu>
3211
3212 This function appears in FANN >= 1.2.0.
3213 */
3214 float get_quickprop_mu()
3215 {
3216 float quickprop_mu = 0.0f;
3217 if (ann != NULL)
3218 {
3219 quickprop_mu = fann_get_quickprop_mu(ann);
3220 }
3221 return quickprop_mu;
3222 }
3223
3224 /* Method: set_quickprop_mu
3225
3226 Sets the quickprop mu factor.
3227
3228 See also:
3229 <get_quickprop_mu>, <fann_set_quickprop_mu>
3230
3231 This function appears in FANN >= 1.2.0.
3232 */
3233 void set_quickprop_mu(float quickprop_mu)
3234 {
3235 if (ann != NULL)
3236 {
3237 fann_set_quickprop_mu(ann, quickprop_mu);
3238 }
3239 }
3240
3241 /* Method: get_rprop_increase_factor
3242
3243 The increase factor is a value larger than 1, which is used to
3244 increase the step-size during RPROP training.
3245
3246 The default increase factor is 1.2.
3247
3248 See also:
3249 <set_rprop_increase_factor>, <fann_get_rprop_increase_factor>
3250
3251 This function appears in FANN >= 1.2.0.
3252 */
3253 float get_rprop_increase_factor()
3254 {
3255 float factor = 0.0f;
3256 if (ann != NULL)
3257 {
3258 factor = fann_get_rprop_increase_factor(ann);
3259 }
3260 return factor;
3261 }
3262
3263 /* Method: set_rprop_increase_factor
3264
3265 The increase factor used during RPROP training.
3266
3267 See also:
3268 <get_rprop_increase_factor>, <fann_set_rprop_increase_factor>
3269
3270 This function appears in FANN >= 1.2.0.
3271 */
3272 void set_rprop_increase_factor(float rprop_increase_factor)
3273 {
3274 if (ann != NULL)
3275 {
3276 fann_set_rprop_increase_factor(ann, rprop_increase_factor);
3277 }
3278 }
3279
3280 /* Method: get_rprop_decrease_factor
3281
3282 The decrease factor is a value smaller than 1, which is used to decrease the step-size during RPROP training.
3283
3284 The default decrease factor is 0.5.
3285
3286 See also:
3287 <set_rprop_decrease_factor>, <fann_get_rprop_decrease_factor>
3288
3289 This function appears in FANN >= 1.2.0.
3290 */
3291 float get_rprop_decrease_factor()
3292 {
3293 float factor = 0.0f;
3294 if (ann != NULL)
3295 {
3296 factor = fann_get_rprop_decrease_factor(ann);
3297 }
3298 return factor;
3299 }
3300
3301 /* Method: set_rprop_decrease_factor
3302
3303 The decrease factor is a value smaller than 1, which is used to decrease the step-size during RPROP training.
3304
3305 See also:
3306 <get_rprop_decrease_factor>, <fann_set_rprop_decrease_factor>
3307
3308 This function appears in FANN >= 1.2.0.
3309 */
3310 void set_rprop_decrease_factor(float rprop_decrease_factor)
3311 {
3312 if (ann != NULL)
3313 {
3314 fann_set_rprop_decrease_factor(ann, rprop_decrease_factor);
3315 }
3316 }
3317
3318 /* Method: get_rprop_delta_min
3319
3320 The minimum step-size is a small positive number determining how small the minimum step-size may be.
3321
3322 The default value delta min is 0.0.
3323
3324 See also:
3325 <set_rprop_delta_min>, <fann_get_rprop_delta_min>
3326
3327 This function appears in FANN >= 1.2.0.
3328 */
3329 float get_rprop_delta_min()
3330 {
3331 float delta = 0.0f;
3332 if (ann != NULL)
3333 {
3334 delta = fann_get_rprop_delta_min(ann);
3335 }
3336 return delta;
3337 }
3338
3339 /* Method: set_rprop_delta_min
3340
3341 The minimum step-size is a small positive number determining how small the minimum step-size may be.
3342
3343 See also:
3344 <get_rprop_delta_min>, <fann_set_rprop_delta_min>
3345
3346 This function appears in FANN >= 1.2.0.
3347 */
3348 void set_rprop_delta_min(float rprop_delta_min)
3349 {
3350 if (ann != NULL)
3351 {
3352 fann_set_rprop_delta_min(ann, rprop_delta_min);
3353 }
3354 }
3355
3356 /* Method: get_rprop_delta_max
3357
3358 The maximum step-size is a positive number determining how large the maximum step-size may be.
3359
3360 The default delta max is 50.0.
3361
3362 See also:
3363 <set_rprop_delta_max>, <get_rprop_delta_min>, <fann_get_rprop_delta_max>
3364
3365 This function appears in FANN >= 1.2.0.
3366 */
3367 float get_rprop_delta_max()
3368 {
3369 float delta = 0.0f;
3370 if (ann != NULL)
3371 {
3372 delta = fann_get_rprop_delta_max(ann);
3373 }
3374 return delta;
3375 }
3376
3377 /* Method: set_rprop_delta_max
3378
3379 The maximum step-size is a positive number determining how large the maximum step-size may be.
3380
3381 See also:
3382 <get_rprop_delta_max>, <get_rprop_delta_min>, <fann_set_rprop_delta_max>
3383
3384 This function appears in FANN >= 1.2.0.
3385 */
3386 void set_rprop_delta_max(float rprop_delta_max)
3387 {
3388 if (ann != NULL)
3389 {
3390 fann_set_rprop_delta_max(ann, rprop_delta_max);
3391 }
3392 }
3393
3394 /* Method: get_num_input
3395
3396 Get the number of input neurons.
3397
3398 This function appears in FANN >= 1.0.0.
3399 */
3400 unsigned int get_num_input()
3401 {
3402 unsigned int num_input = 0;
3403 if (ann != NULL)
3404 {
3405 num_input = fann_get_num_input(ann);
3406 }
3407 return num_input;
3408 }
3409
3410 /* Method: get_num_output
3411
3412 Get the number of output neurons.
3413
3414 This function appears in FANN >= 1.0.0.
3415 */
3416 unsigned int get_num_output()
3417 {
3418 unsigned int num_output = 0;
3419 if (ann != NULL)
3420 {
3421 num_output = fann_get_num_output(ann);
3422 }
3423 return num_output;
3424 }
3425
3426 /* Method: get_total_neurons
3427
3428 Get the total number of neurons in the entire network. This number does also include the
3429 bias neurons, so a 2-4-2 network has 2+4+2 +2(bias) = 10 neurons.
3430
3431 This function appears in FANN >= 1.0.0.
3432 */
3433 unsigned int get_total_neurons()
3434 {
3435 if (ann == NULL)
3436 {
3437 return 0;
3438 }
3439 return fann_get_total_neurons(ann);
3440 }
3441
3442 /* Method: get_total_connections
3443
3444 Get the total number of connections in the entire network.
3445
3446 This function appears in FANN >= 1.0.0.
3447 */
3448 unsigned int get_total_connections()
3449 {
3450 if (ann == NULL)
3451 {
3452 return 0;
3453 }
3454 return fann_get_total_connections(ann);
3455 }
3456
3457 #ifdef FIXEDFANN
3458 /* Method: get_decimal_point
3459
3460 Returns the position of the decimal point in the ann.
3461
3462 This function is only available when the ANN is in fixed point mode.
3463
3464 The decimal point is described in greater detail in the tutorial <Fixed Point Usage>.
3465
3466 See also:
3467 <Fixed Point Usage>, <get_multiplier>, <save_to_fixed>,
3468 <training_data::save_train_to_fixed>, <fann_get_decimal_point>
3469
3470 This function appears in FANN >= 1.0.0.
3471 */
3472 unsigned int get_decimal_point()
3473 {
3474 if (ann == NULL)
3475 {
3476 return 0;
3477 }
3478 return fann_get_decimal_point(ann);
3479 }
3480
3481 /* Method: get_multiplier
3482
3483 Returns the multiplier that fix point data is multiplied with.
3484
3485 This function is only available when the ANN is in fixed point mode.
3486
3487 The multiplier is the used to convert between floating point and fixed point notation.
3488 A floating point number is multiplied with the multiplier in order to get the fixed point
3489 number and visa versa.
3490
3491 The multiplier is described in greater detail in the tutorial <Fixed Point Usage>.
3492
3493 See also:
3494 <Fixed Point Usage>, <get_decimal_point>, <save_to_fixed>,
3495 <training_data::save_train_to_fixed>, <fann_get_multiplier>
3496
3497 This function appears in FANN >= 1.0.0.
3498 */
3499 unsigned int get_multiplier()
3500 {
3501 if (ann == NULL)
3502 {
3503 return 0;
3504 }
3505 return fann_get_multiplier(ann);
3506 }
3507 #endif /* FIXEDFANN */
3508
3509 /*********************************************************************/
3510
3511 /* Method: get_network_type
3512
3513 Get the type of neural network it was created as.
3514
3515 Returns:
3516 The neural network type from enum <FANN::network_type_enum>
3517
3518 See Also:
3519 <fann_get_network_type>
3520
3521 This function appears in FANN >= 2.1.0
3522 */
3523 network_type_enum get_network_type()
3524 {
3525 fann_nettype_enum network_type = FANN_NETTYPE_LAYER;
3526 if (ann != NULL)
3527 {
3528 network_type = fann_get_network_type(ann);
3529 }
3530 return static_cast<network_type_enum>(network_type);
3531 }
3532
3533 /* Method: get_connection_rate
3534
3535 Get the connection rate used when the network was created
3536
3537 Returns:
3538 The connection rate
3539
3540 See also:
3541 <fann_get_connection_rate>
3542
3543 This function appears in FANN >= 2.1.0
3544 */
3545 float get_connection_rate()
3546 {
3547 if (ann == NULL)
3548 {
3549 return 0;
3550 }
3551 return fann_get_connection_rate(ann);
3552 }
3553
3554 /* Method: get_num_layers
3555
3556 Get the number of layers in the network
3557
3558 Returns:
3559 The number of layers in the neural network
3560
3561 See also:
3562 <fann_get_num_layers>
3563
3564 This function appears in FANN >= 2.1.0
3565 */
3566 unsigned int get_num_layers()
3567 {
3568 if (ann == NULL)
3569 {
3570 return 0;
3571 }
3572 return fann_get_num_layers(ann);
3573 }
3574
3575 /* Method: get_layer_array
3576
3577 Get the number of neurons in each layer in the network.
3578
3579 Bias is not included so the layers match the create methods.
3580
3581 The layers array must be preallocated to at least
3582 sizeof(unsigned int) * get_num_layers() long.
3583
3584 See also:
3585 <fann_get_layer_array>
3586
3587 This function appears in FANN >= 2.1.0
3588 */
3589 void get_layer_array(unsigned int *layers)
3590 {
3591 if (ann != NULL)
3592 {
3593 fann_get_layer_array(ann, layers);
3594 }
3595 }
3596
3597 void get_layer_array(std::vector<unsigned int> vlayers)
3598 {
3599 vlayers.clear();
3600 if (ann != NULL){
3601 vlayers.resize(get_num_layers());
3602 unsigned int* layers=(unsigned int *)calloc(get_num_layers(),sizeof(unsigned int));
3603 fann_get_layer_array(ann, layers);
3604 for(int ilayer=0;ilayer<get_num_layers();++ilayer)
3605 vlayers[ilayer]=*(layers++);
3606 }
3607 }
3608
3609 /* Method: get_bias_array
3610
3611 Get the number of bias in each layer in the network.
3612
3613 The bias array must be preallocated to at least
3614 sizeof(unsigned int) * get_num_layers() long.
3615
3616 See also:
3617 <fann_get_bias_array>
3618
3619 This function appears in FANN >= 2.1.0
3620 */
3621 void get_bias_array(unsigned int *bias)
3622 {
3623 if (ann != NULL)
3624 {
3625 fann_get_bias_array(ann, bias);
3626 }
3627 }
3628
3629 /* Method: get_connection_array
3630
3631 Get the connections in the network.
3632
3633 The connections array must be preallocated to at least
3634 sizeof(struct fann_connection) * get_total_connections() long.
3635
3636 See also:
3637 <fann_get_connection_array>
3638
3639 This function appears in FANN >= 2.1.0
3640 */
3641 void get_connection_array(connection *connections)
3642 {
3643 if (ann != NULL)
3644 {
3645 fann_get_connection_array(ann, connections);
3646 }
3647 }
3648
3649 void get_connection_array(std::vector<connection>& convector)
3650 {
3651 convector.clear();
3652 if (ann != NULL)
3653 {
3654 convector.resize(get_total_connections());
3655 connection* connections=(connection*)calloc(get_total_connections(),sizeof(connection));
3656 fann_get_connection_array(ann, connections);
3657 for(int icon=0;icon<get_total_connections();++icon)
3658 convector[icon]=*(connections++);
3659 }
3660 }
3661
3662 /* Method: set_weight_array
3663
3664 Set connections in the network.
3665
3666 Only the weights can be changed, connections and weights are ignored
3667 if they do not already exist in the network.
3668
3669 The array must have sizeof(struct fann_connection) * num_connections size.
3670
3671 See also:
3672 <fann_set_weight_array>
3673
3674 This function appears in FANN >= 2.1.0
3675 */
3676 void set_weight_array(connection *connections, unsigned int num_connections)
3677 {
3678 if (ann != NULL)
3679 {
3680 fann_set_weight_array(ann, connections, num_connections);
3681 }
3682 }
3683
3684 void set_weight_array(std::vector<connection> convector)
3685 {
3686 if (ann != NULL)
3687 {
3688 unsigned int num_connections=convector.size();
3689 connection* connections=(connection*)calloc(num_connections,sizeof(connection));
3690 connections=&(convector[0]);
3691 fann_set_weight_array(ann, connections, num_connections);
3692 }
3693 }
3694
3695 /* Method: set_weight
3696
3697 Set a connection in the network.
3698
3699 Only the weights can be changed. The connection/weight is
3700 ignored if it does not already exist in the network.
3701
3702 See also:
3703 <fann_set_weight>
3704
3705 This function appears in FANN >= 2.1.0
3706 */
3707 void set_weight(unsigned int from_neuron, unsigned int to_neuron, fann_type weight)
3708 {
3709 if (ann != NULL)
3710 {
3711 fann_set_weight(ann, from_neuron, to_neuron, weight);
3712 }
3713 }
3714
3715 /*********************************************************************/
3716
3717 /* Method: get_learning_momentum
3718
3719 Get the learning momentum.
3720
3721 The learning momentum can be used to speed up FANN::TRAIN_INCREMENTAL training.
3722 A too high momentum will however not benefit training. Setting momentum to 0 will
3723 be the same as not using the momentum parameter. The recommended value of this parameter
3724 is between 0.0 and 1.0.
3725
3726 The default momentum is 0.
3727
3728 See also:
3729 <set_learning_momentum>, <set_training_algorithm>
3730
3731 This function appears in FANN >= 2.0.0.
3732 */
3733 float get_learning_momentum()
3734 {
3735 float learning_momentum = 0.0f;
3736 if (ann != NULL)
3737 {
3738 learning_momentum = fann_get_learning_momentum(ann);
3739 }
3740 return learning_momentum;
3741 }
3742
3743 /* Method: set_learning_momentum
3744
3745 Set the learning momentum.
3746
3747 More info available in <get_learning_momentum>
3748
3749 This function appears in FANN >= 2.0.0.
3750 */
3751 void set_learning_momentum(float learning_momentum)
3752 {
3753 if (ann != NULL)
3754 {
3755 fann_set_learning_momentum(ann, learning_momentum);
3756 }
3757 }
3758
3759 /* Method: get_train_stop_function
3760
3761 Returns the the stop function used during training.
3762
3763 The stop function is described further in <FANN::stop_function_enum>
3764
3765 The default stop function is FANN::STOPFUNC_MSE
3766
3767 See also:
3768 <get_train_stop_function>, <get_bit_fail_limit>
3769
3770 This function appears in FANN >= 2.0.0.
3771 */
3772 stop_function_enum get_train_stop_function()
3773 {
3774 enum fann_stopfunc_enum stopfunc = FANN_STOPFUNC_MSE;
3775 if (ann != NULL)
3776 {
3777 stopfunc = fann_get_train_stop_function(ann);
3778 }
3779 return static_cast<stop_function_enum>(stopfunc);
3780 }
3781
3782 /* Method: set_train_stop_function
3783
3784 Set the stop function used during training.
3785
3786 The stop function is described further in <FANN::stop_function_enum>
3787
3788 See also:
3789 <get_train_stop_function>
3790
3791 This function appears in FANN >= 2.0.0.
3792 */
3793 void set_train_stop_function(stop_function_enum train_stop_function)
3794 {
3795 if (ann != NULL)
3796 {
3797 fann_set_train_stop_function(ann,
3798 static_cast<enum fann_stopfunc_enum>(train_stop_function));
3799 }
3800 }
3801
3802 /* Method: get_bit_fail_limit
3803
3804 Returns the bit fail limit used during training.
3805
3806 The bit fail limit is used during training when the <FANN::stop_function_enum> is set to FANN_STOPFUNC_BIT.
3807
3808 The limit is the maximum accepted difference between the desired output and the actual output during
3809 training. Each output that diverges more than this limit is counted as an error bit.
3810 This difference is divided by two when dealing with symmetric activation functions,
3811 so that symmetric and not symmetric activation functions can use the same limit.
3812
3813 The default bit fail limit is 0.35.
3814
3815 See also:
3816 <set_bit_fail_limit>
3817
3818 This function appears in FANN >= 2.0.0.
3819 */
3820 fann_type get_bit_fail_limit()
3821 {
3822 fann_type bit_fail_limit = 0.0f;
3823
3824 if (ann != NULL)
3825 {
3826 bit_fail_limit = fann_get_bit_fail_limit(ann);
3827 }
3828 return bit_fail_limit;
3829 }
3830
3831 /* Method: set_bit_fail_limit
3832
3833 Set the bit fail limit used during training.
3834
3835 See also:
3836 <get_bit_fail_limit>
3837
3838 This function appears in FANN >= 2.0.0.
3839 */
3840 void set_bit_fail_limit(fann_type bit_fail_limit)
3841 {
3842 if (ann != NULL)
3843 {
3844 fann_set_bit_fail_limit(ann, bit_fail_limit);
3845 }
3846 }
3847
3848 /* Method: get_bit_fail
3849
3850 The number of fail bits; means the number of output neurons which differ more
3851 than the bit fail limit (see <get_bit_fail_limit>, <set_bit_fail_limit>).
3852 The bits are counted in all of the training data, so this number can be higher than
3853 the number of training data.
3854
3855 This value is reset by <reset_MSE> and updated by all the same functions which also
3856 updates the MSE value (e.g. <test_data>, <train_epoch>)
3857
3858 See also:
3859 <FANN::stop_function_enum>, <get_MSE>
3860
3861 This function appears in FANN >= 2.0.0
3862 */
3863 unsigned int get_bit_fail()
3864 {
3865 unsigned int bit_fail = 0;
3866 if (ann != NULL)
3867 {
3868 bit_fail = fann_get_bit_fail(ann);
3869 }
3870 return bit_fail;
3871 }
3872
3873 /*********************************************************************/
3874
3875 /* Method: cascadetrain_on_data
3876
3877 Trains on an entire dataset, for a period of time using the Cascade2 training algorithm.
3878 This algorithm adds neurons to the neural network while training, which means that it
3879 needs to start with an ANN without any hidden layers. The neural network should also use
3880 shortcut connections, so <create_shortcut> should be used to create the ANN like this:
3881 >net.create_shortcut(2, train_data.num_input_train_data(), train_data.num_output_train_data());
3882
3883 This training uses the parameters set using the set_cascade_..., but it also uses another
3884 training algorithm as it's internal training algorithm. This algorithm can be set to either
3885 FANN::TRAIN_RPROP or FANN::TRAIN_QUICKPROP by <set_training_algorithm>, and the parameters
3886 set for these training algorithms will also affect the cascade training.
3887
3888 Parameters:
3889 data - The data, which should be used during training
3890 max_neuron - The maximum number of neurons to be added to neural network
3891 neurons_between_reports - The number of neurons between printing a status report to stdout.
3892 A value of zero means no reports should be printed.
3893 desired_error - The desired <fann_get_MSE> or <fann_get_bit_fail>, depending on which stop function
3894 is chosen by <fann_set_train_stop_function>.
3895
3896 Instead of printing out reports every neurons_between_reports, a callback function can be called
3897 (see <set_callback>).
3898
3899 See also:
3900 <train_on_data>, <cascadetrain_on_file>, <fann_cascadetrain_on_data>
3901
3902 This function appears in FANN >= 2.0.0.
3903 */
3904 void cascadetrain_on_data(const training_data &data, unsigned int max_neurons,
3905 unsigned int neurons_between_reports, float desired_error)
3906 {
3907 if ((ann != NULL) && (data.train_data != NULL))
3908 {
3909 fann_cascadetrain_on_data(ann, data.train_data, max_neurons,
3910 neurons_between_reports, desired_error);
3911 }
3912 }
3913
3914 /* Method: cascadetrain_on_file
3915
3916 Does the same as <cascadetrain_on_data>, but reads the training data directly from a file.
3917
3918 See also:
3919 <fann_cascadetrain_on_data>, <fann_cascadetrain_on_file>
3920
3921 This function appears in FANN >= 2.0.0.
3922 */
3923 void cascadetrain_on_file(const std::string &filename, unsigned int max_neurons,
3924 unsigned int neurons_between_reports, float desired_error)
3925 {
3926 if (ann != NULL)
3927 {
3928 fann_cascadetrain_on_file(ann, filename.c_str(),
3929 max_neurons, neurons_between_reports, desired_error);
3930 }
3931 }
3932
3933 /* Method: get_cascade_output_change_fraction
3934
3935 The cascade output change fraction is a number between 0 and 1 determining how large a fraction
3936 the <get_MSE> value should change within <get_cascade_output_stagnation_epochs> during
3937 training of the output connections, in order for the training not to stagnate. If the training
3938 stagnates, the training of the output connections will be ended and new candidates will be prepared.
3939
3940 This means:
3941 If the MSE does not change by a fraction of <get_cascade_output_change_fraction> during a
3942 period of <get_cascade_output_stagnation_epochs>, the training of the output connections
3943 is stopped because the training has stagnated.
3944
3945 If the cascade output change fraction is low, the output connections will be trained more and if the
3946 fraction is high they will be trained less.
3947
3948 The default cascade output change fraction is 0.01, which is equalent to a 1% change in MSE.
3949
3950 See also:
3951 <set_cascade_output_change_fraction>, <get_MSE>,
3952 <get_cascade_output_stagnation_epochs>, <fann_get_cascade_output_change_fraction>
3953
3954 This function appears in FANN >= 2.0.0.
3955 */
3956 float get_cascade_output_change_fraction()
3957 {
3958 float change_fraction = 0.0f;
3959 if (ann != NULL)
3960 {
3961 change_fraction = fann_get_cascade_output_change_fraction(ann);
3962 }
3963 return change_fraction;
3964 }
3965
3966 /* Method: set_cascade_output_change_fraction
3967
3968 Sets the cascade output change fraction.
3969
3970 See also:
3971 <get_cascade_output_change_fraction>, <fann_set_cascade_output_change_fraction>
3972
3973 This function appears in FANN >= 2.0.0.
3974 */
3975 void set_cascade_output_change_fraction(float cascade_output_change_fraction)
3976 {
3977 if (ann != NULL)
3978 {
3979 fann_set_cascade_output_change_fraction(ann, cascade_output_change_fraction);
3980 }
3981 }
3982
3983 /* Method: get_cascade_output_stagnation_epochs
3984
3985 The number of cascade output stagnation epochs determines the number of epochs training is allowed to
3986 continue without changing the MSE by a fraction of <get_cascade_output_change_fraction>.
3987
3988 See more info about this parameter in <get_cascade_output_change_fraction>.
3989
3990 The default number of cascade output stagnation epochs is 12.
3991
3992 See also:
3993 <set_cascade_output_stagnation_epochs>, <get_cascade_output_change_fraction>,
3994 <fann_get_cascade_output_stagnation_epochs>
3995
3996 This function appears in FANN >= 2.0.0.
3997 */
3998 unsigned int get_cascade_output_stagnation_epochs()
3999 {
4000 unsigned int stagnation_epochs = 0;
4001 if (ann != NULL)
4002 {
4003 stagnation_epochs = fann_get_cascade_output_stagnation_epochs(ann);
4004 }
4005 return stagnation_epochs;
4006 }
4007
4008 /* Method: set_cascade_output_stagnation_epochs
4009
4010 Sets the number of cascade output stagnation epochs.
4011
4012 See also:
4013 <get_cascade_output_stagnation_epochs>, <fann_set_cascade_output_stagnation_epochs>
4014
4015 This function appears in FANN >= 2.0.0.
4016 */
4017 void set_cascade_output_stagnation_epochs(unsigned int cascade_output_stagnation_epochs)
4018 {
4019 if (ann != NULL)
4020 {
4021 fann_set_cascade_output_stagnation_epochs(ann, cascade_output_stagnation_epochs);
4022 }
4023 }
4024
4025 /* Method: get_cascade_candidate_change_fraction
4026
4027 The cascade candidate change fraction is a number between 0 and 1 determining how large a fraction
4028 the <get_MSE> value should change within <get_cascade_candidate_stagnation_epochs> during
4029 training of the candidate neurons, in order for the training not to stagnate. If the training
4030 stagnates, the training of the candidate neurons will be ended and the best candidate will be selected.
4031
4032 This means:
4033 If the MSE does not change by a fraction of <get_cascade_candidate_change_fraction> during a
4034 period of <get_cascade_candidate_stagnation_epochs>, the training of the candidate neurons
4035 is stopped because the training has stagnated.
4036
4037 If the cascade candidate change fraction is low, the candidate neurons will be trained more and if the
4038 fraction is high they will be trained less.
4039
4040 The default cascade candidate change fraction is 0.01, which is equalent to a 1% change in MSE.
4041
4042 See also:
4043 <set_cascade_candidate_change_fraction>, <get_MSE>,
4044 <get_cascade_candidate_stagnation_epochs>, <fann_get_cascade_candidate_change_fraction>
4045
4046 This function appears in FANN >= 2.0.0.
4047 */
4048 float get_cascade_candidate_change_fraction()
4049 {
4050 float change_fraction = 0.0f;
4051 if (ann != NULL)
4052 {
4053 change_fraction = fann_get_cascade_candidate_change_fraction(ann);
4054 }
4055 return change_fraction;
4056 }
4057
4058 /* Method: set_cascade_candidate_change_fraction
4059
4060 Sets the cascade candidate change fraction.
4061
4062 See also:
4063 <get_cascade_candidate_change_fraction>,
4064 <fann_set_cascade_candidate_change_fraction>
4065
4066 This function appears in FANN >= 2.0.0.
4067 */
4068 void set_cascade_candidate_change_fraction(float cascade_candidate_change_fraction)
4069 {
4070 if (ann != NULL)
4071 {
4072 fann_set_cascade_candidate_change_fraction(ann, cascade_candidate_change_fraction);
4073 }
4074 }
4075
4076 /* Method: get_cascade_candidate_stagnation_epochs
4077
4078 The number of cascade candidate stagnation epochs determines the number of epochs training is allowed to
4079 continue without changing the MSE by a fraction of <get_cascade_candidate_change_fraction>.
4080
4081 See more info about this parameter in <get_cascade_candidate_change_fraction>.
4082
4083 The default number of cascade candidate stagnation epochs is 12.
4084
4085 See also:
4086 <set_cascade_candidate_stagnation_epochs>, <get_cascade_candidate_change_fraction>,
4087 <fann_get_cascade_candidate_stagnation_epochs>
4088
4089 This function appears in FANN >= 2.0.0.
4090 */
4091 unsigned int get_cascade_candidate_stagnation_epochs()
4092 {
4093 unsigned int stagnation_epochs = 0;
4094 if (ann != NULL)
4095 {
4096 stagnation_epochs = fann_get_cascade_candidate_stagnation_epochs(ann);
4097 }
4098 return stagnation_epochs;
4099 }
4100
4101 /* Method: set_cascade_candidate_stagnation_epochs
4102
4103 Sets the number of cascade candidate stagnation epochs.
4104
4105 See also:
4106 <get_cascade_candidate_stagnation_epochs>,
4107 <fann_set_cascade_candidate_stagnation_epochs>
4108
4109 This function appears in FANN >= 2.0.0.
4110 */
4111 void set_cascade_candidate_stagnation_epochs(unsigned int cascade_candidate_stagnation_epochs)
4112 {
4113 if (ann != NULL)
4114 {
4115 fann_set_cascade_candidate_stagnation_epochs(ann, cascade_candidate_stagnation_epochs);
4116 }
4117 }
4118
4119 /* Method: get_cascade_weight_multiplier
4120
4121 The weight multiplier is a parameter which is used to multiply the weights from the candidate neuron
4122 before adding the neuron to the neural network. This parameter is usually between 0 and 1, and is used
4123 to make the training a bit less aggressive.
4124
4125 The default weight multiplier is 0.4
4126
4127 See also:
4128 <set_cascade_weight_multiplier>, <fann_get_cascade_weight_multiplier>
4129
4130 This function appears in FANN >= 2.0.0.
4131 */
4132 fann_type get_cascade_weight_multiplier()
4133 {
4134 fann_type weight_multiplier = 0;
4135 if (ann != NULL)
4136 {
4137 weight_multiplier = fann_get_cascade_weight_multiplier(ann);
4138 }
4139 return weight_multiplier;
4140 }
4141
4142 /* Method: set_cascade_weight_multiplier
4143
4144 Sets the weight multiplier.
4145
4146 See also:
4147 <get_cascade_weight_multiplier>, <fann_set_cascade_weight_multiplier>
4148
4149 This function appears in FANN >= 2.0.0.
4150 */
4151 void set_cascade_weight_multiplier(fann_type cascade_weight_multiplier)
4152 {
4153 if (ann != NULL)
4154 {
4155 fann_set_cascade_weight_multiplier(ann, cascade_weight_multiplier);
4156 }
4157 }
4158
4159 /* Method: get_cascade_candidate_limit
4160
4161 The candidate limit is a limit for how much the candidate neuron may be trained.
4162 The limit is a limit on the proportion between the MSE and candidate score.
4163
4164 Set this to a lower value to avoid overfitting and to a higher if overfitting is
4165 not a problem.
4166
4167 The default candidate limit is 1000.0
4168
4169 See also:
4170 <set_cascade_candidate_limit>, <fann_get_cascade_candidate_limit>
4171
4172 This function appears in FANN >= 2.0.0.
4173 */
4174 fann_type get_cascade_candidate_limit()
4175 {
4176 fann_type candidate_limit = 0;
4177 if (ann != NULL)
4178 {
4179 candidate_limit = fann_get_cascade_candidate_limit(ann);
4180 }
4181 return candidate_limit;
4182 }
4183
4184 /* Method: set_cascade_candidate_limit
4185
4186 Sets the candidate limit.
4187
4188 See also:
4189 <get_cascade_candidate_limit>, <fann_set_cascade_candidate_limit>
4190
4191 This function appears in FANN >= 2.0.0.
4192 */
4193 void set_cascade_candidate_limit(fann_type cascade_candidate_limit)
4194 {
4195 if (ann != NULL)
4196 {
4197 fann_set_cascade_candidate_limit(ann, cascade_candidate_limit);
4198 }
4199 }
4200
4201 /* Method: get_cascade_max_out_epochs
4202
4203 The maximum out epochs determines the maximum number of epochs the output connections
4204 may be trained after adding a new candidate neuron.
4205
4206 The default max out epochs is 150
4207
4208 See also:
4209 <set_cascade_max_out_epochs>, <fann_get_cascade_max_out_epochs>
4210
4211 This function appears in FANN >= 2.0.0.
4212 */
4213 unsigned int get_cascade_max_out_epochs()
4214 {
4215 unsigned int max_out_epochs = 0;
4216 if (ann != NULL)
4217 {
4218 max_out_epochs = fann_get_cascade_max_out_epochs(ann);
4219 }
4220 return max_out_epochs;
4221 }
4222
4223 /* Method: set_cascade_max_out_epochs
4224
4225 Sets the maximum out epochs.
4226
4227 See also:
4228 <get_cascade_max_out_epochs>, <fann_set_cascade_max_out_epochs>
4229
4230 This function appears in FANN >= 2.0.0.
4231 */
4232 void set_cascade_max_out_epochs(unsigned int cascade_max_out_epochs)
4233 {
4234 if (ann != NULL)
4235 {
4236 fann_set_cascade_max_out_epochs(ann, cascade_max_out_epochs);
4237 }
4238 }
4239
4240 /* Method: get_cascade_max_cand_epochs
4241
4242 The maximum candidate epochs determines the maximum number of epochs the input
4243 connections to the candidates may be trained before adding a new candidate neuron.
4244
4245 The default max candidate epochs is 150
4246
4247 See also:
4248 <set_cascade_max_cand_epochs>, <fann_get_cascade_max_cand_epochs>
4249
4250 This function appears in FANN >= 2.0.0.
4251 */
4252 unsigned int get_cascade_max_cand_epochs()
4253 {
4254 unsigned int max_cand_epochs = 0;
4255 if (ann != NULL)
4256 {
4257 max_cand_epochs = fann_get_cascade_max_cand_epochs(ann);
4258 }
4259 return max_cand_epochs;
4260 }
4261
4262 /* Method: set_cascade_max_cand_epochs
4263
4264 Sets the max candidate epochs.
4265
4266 See also:
4267 <get_cascade_max_cand_epochs>, <fann_set_cascade_max_cand_epochs>
4268
4269 This function appears in FANN >= 2.0.0.
4270 */
4271 void set_cascade_max_cand_epochs(unsigned int cascade_max_cand_epochs)
4272 {
4273 if (ann != NULL)
4274 {
4275 fann_set_cascade_max_cand_epochs(ann, cascade_max_cand_epochs);
4276 }
4277 }
4278
4279 /* Method: get_cascade_num_candidates
4280
4281 The number of candidates used during training (calculated by multiplying <get_cascade_activation_functions_count>,
4282 <get_cascade_activation_steepnesses_count> and <get_cascade_num_candidate_groups>).
4283
4284 The actual candidates is defined by the <get_cascade_activation_functions> and
4285 <get_cascade_activation_steepnesses> arrays. These arrays define the activation functions
4286 and activation steepnesses used for the candidate neurons. If there are 2 activation functions
4287 in the activation function array and 3 steepnesses in the steepness array, then there will be
4288 2x3=6 different candidates which will be trained. These 6 different candidates can be copied into
4289 several candidate groups, where the only difference between these groups is the initial weights.
4290 If the number of groups is set to 2, then the number of candidate neurons will be 2x3x2=12. The
4291 number of candidate groups is defined by <set_cascade_num_candidate_groups>.
4292
4293 The default number of candidates is 6x4x2 = 48
4294
4295 See also:
4296 <get_cascade_activation_functions>, <get_cascade_activation_functions_count>,
4297 <get_cascade_activation_steepnesses>, <get_cascade_activation_steepnesses_count>,
4298 <get_cascade_num_candidate_groups>, <fann_get_cascade_num_candidates>
4299
4300 This function appears in FANN >= 2.0.0.
4301 */
4302 unsigned int get_cascade_num_candidates()
4303 {
4304 unsigned int num_candidates = 0;
4305 if (ann != NULL)
4306 {
4307 num_candidates = fann_get_cascade_num_candidates(ann);
4308 }
4309 return num_candidates;
4310 }
4311
4312 /* Method: get_cascade_activation_functions_count
4313
4314 The number of activation functions in the <get_cascade_activation_functions> array.
4315
4316 The default number of activation functions is 6.
4317
4318 See also:
4319 <get_cascade_activation_functions>, <set_cascade_activation_functions>,
4320 <fann_get_cascade_activation_functions_count>
4321
4322 This function appears in FANN >= 2.0.0.
4323 */
4324 unsigned int get_cascade_activation_functions_count()
4325 {
4326 unsigned int activation_functions_count = 0;
4327 if (ann != NULL)
4328 {
4329 activation_functions_count = fann_get_cascade_activation_functions_count(ann);
4330 }
4331 return activation_functions_count;
4332 }
4333
4334 /* Method: get_cascade_activation_functions
4335
4336 The cascade activation functions array is an array of the different activation functions used by
4337 the candidates.
4338
4339 See <get_cascade_num_candidates> for a description of which candidate neurons will be
4340 generated by this array.
4341
4342 See also:
4343 <get_cascade_activation_functions_count>, <set_cascade_activation_functions>,
4344 <FANN::activation_function_enum>
4345
4346 This function appears in FANN >= 2.0.0.
4347 */
4348 activation_function_enum * get_cascade_activation_functions()
4349 {
4350 enum fann_activationfunc_enum *activation_functions = NULL;
4351 if (ann != NULL)
4352 {
4353 activation_functions = fann_get_cascade_activation_functions(ann);
4354 }
4355 return reinterpret_cast<activation_function_enum *>(activation_functions);
4356 }
4357
4358 /* Method: set_cascade_activation_functions
4359
4360 Sets the array of cascade candidate activation functions. The array must be just as long
4361 as defined by the count.
4362
4363 See <get_cascade_num_candidates> for a description of which candidate neurons will be
4364 generated by this array.
4365
4366 See also:
4367 <get_cascade_activation_steepnesses_count>, <get_cascade_activation_steepnesses>,
4368 <fann_set_cascade_activation_functions>
4369
4370 This function appears in FANN >= 2.0.0.
4371 */
4372 void set_cascade_activation_functions(activation_function_enum *cascade_activation_functions,
4373 unsigned int cascade_activation_functions_count)
4374 {
4375 if (ann != NULL)
4376 {
4377 fann_set_cascade_activation_functions(ann,
4378 reinterpret_cast<enum fann_activationfunc_enum *>(cascade_activation_functions),
4379 cascade_activation_functions_count);
4380 }
4381 }
4382
4383 /* Method: get_cascade_activation_steepnesses_count
4384
4385 The number of activation steepnesses in the <get_cascade_activation_functions> array.
4386
4387 The default number of activation steepnesses is 4.
4388
4389 See also:
4390 <get_cascade_activation_steepnesses>, <set_cascade_activation_functions>,
4391 <fann_get_cascade_activation_steepnesses_count>
4392
4393 This function appears in FANN >= 2.0.0.
4394 */
4395 unsigned int get_cascade_activation_steepnesses_count()
4396 {
4397 unsigned int activation_steepness_count = 0;
4398 if (ann != NULL)
4399 {
4400 activation_steepness_count = fann_get_cascade_activation_steepnesses_count(ann);
4401 }
4402 return activation_steepness_count;
4403 }
4404
4405 /* Method: get_cascade_activation_steepnesses
4406
4407 The cascade activation steepnesses array is an array of the different activation functions used by
4408 the candidates.
4409
4410 See <get_cascade_num_candidates> for a description of which candidate neurons will be
4411 generated by this array.
4412
4413 The default activation steepnesses is {0.25, 0.50, 0.75, 1.00}
4414
4415 See also:
4416 <set_cascade_activation_steepnesses>, <get_cascade_activation_steepnesses_count>,
4417 <fann_get_cascade_activation_steepnesses>
4418
4419 This function appears in FANN >= 2.0.0.
4420 */
4421 fann_type *get_cascade_activation_steepnesses()
4422 {
4423 fann_type *activation_steepnesses = NULL;
4424 if (ann != NULL)
4425 {
4426 activation_steepnesses = fann_get_cascade_activation_steepnesses(ann);
4427 }
4428 return activation_steepnesses;
4429 }
4430
4431 /* Method: set_cascade_activation_steepnesses
4432
4433 Sets the array of cascade candidate activation steepnesses. The array must be just as long
4434 as defined by the count.
4435
4436 See <get_cascade_num_candidates> for a description of which candidate neurons will be
4437 generated by this array.
4438
4439 See also:
4440 <get_cascade_activation_steepnesses>, <get_cascade_activation_steepnesses_count>,
4441 <fann_set_cascade_activation_steepnesses>
4442
4443 This function appears in FANN >= 2.0.0.
4444 */
4445 void set_cascade_activation_steepnesses(fann_type *cascade_activation_steepnesses,
4446 unsigned int cascade_activation_steepnesses_count)
4447 {
4448 if (ann != NULL)
4449 {
4450 fann_set_cascade_activation_steepnesses(ann,
4451 cascade_activation_steepnesses, cascade_activation_steepnesses_count);
4452 }
4453 }
4454
4455 /* Method: get_cascade_num_candidate_groups
4456
4457 The number of candidate groups is the number of groups of identical candidates which will be used
4458 during training.
4459
4460 This number can be used to have more candidates without having to define new parameters for the candidates.
4461
4462 See <get_cascade_num_candidates> for a description of which candidate neurons will be
4463 generated by this parameter.
4464
4465 The default number of candidate groups is 2
4466
4467 See also:
4468 <set_cascade_num_candidate_groups>, <fann_get_cascade_num_candidate_groups>
4469
4470 This function appears in FANN >= 2.0.0.
4471 */
4472 unsigned int get_cascade_num_candidate_groups()
4473 {
4474 unsigned int num_candidate_groups = 0;
4475 if (ann != NULL)
4476 {
4477 num_candidate_groups = fann_get_cascade_num_candidate_groups(ann);
4478 }
4479 return num_candidate_groups;
4480 }
4481
4482 /* Method: set_cascade_num_candidate_groups
4483
4484 Sets the number of candidate groups.
4485
4486 See also:
4487 <get_cascade_num_candidate_groups>, <fann_set_cascade_num_candidate_groups>
4488
4489 This function appears in FANN >= 2.0.0.
4490 */
4491 void set_cascade_num_candidate_groups(unsigned int cascade_num_candidate_groups)
4492 {
4493 if (ann != NULL)
4494 {
4495 fann_set_cascade_num_candidate_groups(ann, cascade_num_candidate_groups);
4496 }
4497 }
4498
4499 /*********************************************************************/
4500
4501 #ifndef FIXEDFANN
4502 /* Method: scale_train
4503
4504 Scale input and output data based on previously calculated parameters.
4505
4506 See also:
4507 <descale_train>, <fann_scale_train>
4508
4509 This function appears in FANN >= 2.1.0.
4510 */
4511 void scale_train(training_data &data)
4512 {
4513 if (ann != NULL)
4514 {
4515 fann_scale_train(ann, data.train_data);
4516 }
4517 }
4518
4519 /* Method: descale_train
4520
4521 Descale input and output data based on previously calculated parameters.
4522
4523 See also:
4524 <scale_train>, <fann_descale_train>
4525
4526 This function appears in FANN >= 2.1.0.
4527 */
4528 void descale_train(training_data &data)
4529 {
4530 if (ann != NULL)
4531 {
4532 fann_descale_train(ann, data.train_data);
4533 }
4534 }
4535
4536 /* Method: set_input_scaling_params
4537
4538 Calculate scaling parameters for future use based on training data.
4539
4540 See also:
4541 <set_output_scaling_params>, <fann_set_input_scaling_params>
4542
4543 This function appears in FANN >= 2.1.0.
4544 */
4545 bool set_input_scaling_params(const training_data &data, float new_input_min, float new_input_max)
4546 {
4547 bool status = false;
4548 if (ann != NULL)
4549 {
4550 status = (fann_set_input_scaling_params(ann, data.train_data, new_input_min, new_input_max) != -1);
4551 }
4552 return status;
4553 }
4554
4555 /* Method: set_output_scaling_params
4556
4557 Calculate scaling parameters for future use based on training data.
4558
4559 See also:
4560 <set_input_scaling_params>, <fann_set_output_scaling_params>
4561
4562 This function appears in FANN >= 2.1.0.
4563 */
4564 bool set_output_scaling_params(const training_data &data, float new_output_min, float new_output_max)
4565 {
4566 bool status = false;
4567 if (ann != NULL)
4568 {
4569 status = (fann_set_output_scaling_params(ann, data.train_data, new_output_min, new_output_max) != -1);
4570 }
4571 return status;
4572 }
4573
4574 /* Method: set_scaling_params
4575
4576 Calculate scaling parameters for future use based on training data.
4577
4578 See also:
4579 <clear_scaling_params>, <fann_set_scaling_params>
4580
4581 This function appears in FANN >= 2.1.0.
4582 */
4583 bool set_scaling_params(const training_data &data,
4584 float new_input_min, float new_input_max, float new_output_min, float new_output_max)
4585 {
4586 bool status = false;
4587 if (ann != NULL)
4588 {
4589 status = (fann_set_scaling_params(ann, data.train_data,
4590 new_input_min, new_input_max, new_output_min, new_output_max) != -1);
4591 }
4592 return status;
4593 }
4594
4595 /* Method: clear_scaling_params
4596
4597 Clears scaling parameters.
4598
4599 See also:
4600 <set_scaling_params>, <fann_clear_scaling_params>
4601
4602 This function appears in FANN >= 2.1.0.
4603 */
4604 bool clear_scaling_params()
4605 {
4606 bool status = false;
4607 if (ann != NULL)
4608 {
4609 status = (fann_clear_scaling_params(ann) != -1);
4610 }
4611 return status;
4612 }
4613
4614 /* Method: scale_input
4615
4616 Scale data in input vector before feed it to ann based on previously calculated parameters.
4617
4618 See also:
4619 <descale_input>, <scale_output>, <fann_scale_input>
4620
4621 This function appears in FANN >= 2.1.0.
4622 */
4623 void scale_input(fann_type *input_vector)
4624 {
4625 if (ann != NULL)
4626 {
4627 fann_scale_input(ann, input_vector );
4628 }
4629 }
4630
4631 /* Method: scale_output
4632
4633 Scale data in output vector before feed it to ann based on previously calculated parameters.
4634
4635 See also:
4636 <descale_output>, <scale_input>, <fann_scale_output>
4637
4638 This function appears in FANN >= 2.1.0.
4639 */
4640 void scale_output(fann_type *output_vector)
4641 {
4642 if (ann != NULL)
4643 {
4644 fann_scale_output(ann, output_vector );
4645 }
4646 }
4647
4648 /* Method: descale_input
4649
4650 Scale data in input vector after get it from ann based on previously calculated parameters.
4651
4652 See also:
4653 <scale_input>, <descale_output>, <fann_descale_input>
4654
4655 This function appears in FANN >= 2.1.0.
4656 */
4657 void descale_input(fann_type *input_vector)
4658 {
4659 if (ann != NULL)
4660 {
4661 fann_descale_input(ann, input_vector );
4662 }
4663 }
4664
4665 /* Method: descale_output
4666
4667 Scale data in output vector after get it from ann based on previously calculated parameters.
4668
4669 See also:
4670 <scale_output>, <descale_input>, <fann_descale_output>
4671
4672 This function appears in FANN >= 2.1.0.
4673 */
4674 void descale_output(fann_type *output_vector)
4675 {
4676 if (ann != NULL)
4677 {
4678 fann_descale_output(ann, output_vector );
4679 }
4680 }
4681
4682 #endif /* FIXEDFANN */
4683
4684 /*********************************************************************/
4685
4686 /* Method: set_error_log
4687
4688 Change where errors are logged to.
4689
4690 If log_file is NULL, no errors will be printed.
4691
4692 If neural_net is empty i.e. ann is NULL, the default log will be set.
4693 The default log is the log used when creating a neural_net.
4694 This default log will also be the default for all new structs
4695 that are created.
4696
4697 The default behavior is to log them to stderr.
4698
4699 See also:
4700 <struct fann_error>, <fann_set_error_log>
4701
4702 This function appears in FANN >= 1.1.0.
4703 */
4704 void set_error_log(FILE *log_file)
4705 {
4706 fann_set_error_log(reinterpret_cast<struct fann_error *>(ann), log_file);
4707 }
4708
4709 /* Method: get_errno
4710
4711 Returns the last error number.
4712
4713 See also:
4714 <fann_errno_enum>, <fann_reset_errno>, <fann_get_errno>
4715
4716 This function appears in FANN >= 1.1.0.
4717 */
4718 unsigned int get_errno()
4719 {
4720 return fann_get_errno(reinterpret_cast<struct fann_error *>(ann));
4721 }
4722
4723 /* Method: reset_errno
4724
4725 Resets the last error number.
4726
4727 This function appears in FANN >= 1.1.0.
4728 */
4729 void reset_errno()
4730 {
4731 fann_reset_errno(reinterpret_cast<struct fann_error *>(ann));
4732 }
4733
4734 /* Method: reset_errstr
4735
4736 Resets the last error string.
4737
4738 This function appears in FANN >= 1.1.0.
4739 */
4740 void reset_errstr()
4741 {
4742 fann_reset_errstr(reinterpret_cast<struct fann_error *>(ann));
4743 }
4744
4745 /* Method: get_errstr
4746
4747 Returns the last errstr.
4748
4749 This function calls <fann_reset_errno> and <fann_reset_errstr>
4750
4751 This function appears in FANN >= 1.1.0.
4752 */
4753 std::string get_errstr()
4754 {
4755 return std::string(fann_get_errstr(reinterpret_cast<struct fann_error *>(ann)));
4756 }
4757
4758 /* Method: print_error
4759
4760 Prints the last error to stderr.
4761
4762 This function appears in FANN >= 1.1.0.
4763 */
4764 void print_error()
4765 {
4766 fann_print_error(reinterpret_cast<struct fann_error *>(ann));
4767 }
4768
4769 /*********************************************************************/
4770
4771 private:
4772 // Structure used by set_callback to hold information about a user callback
4773 typedef struct user_context_type
4774 {
4775 callback_type user_callback; // Pointer to user callback function
4776 void *user_data; // Arbitrary data pointer passed to the callback
4777 neural_net *net; // This pointer for the neural network
4778 } user_context;
4779
4780 // Internal callback used to convert from pointers to class references
4781 static int FANN_API internal_callback(struct fann *ann, struct fann_train_data *train,
4782 unsigned int max_epochs, unsigned int epochs_between_reports, float desired_error, unsigned int epochs)
4783 {
4784 user_context *user_data = static_cast<user_context *>(fann_get_user_data(ann));
4785 if (user_data != NULL)
4786 {
4787 FANN::training_data data;
4788 data.train_data = train;
4789
4790 int result = (*user_data->user_callback)(*user_data->net,
4791 data, max_epochs, epochs_between_reports, desired_error, epochs, user_data);
4792
4793 data.train_data = NULL; // Prevent automatic cleanup
4794 return result;
4795 }
4796 else
4797 {
4798 return -1; // This should not occur except if out of memory
4799 }
4800 }
4801 protected:
4802 // Pointer the encapsulated fann neural net structure
4803 struct fann *ann;
4804 };
4805
4806 /*************************************************************************/
4807 };
4808
4809 #endif /* FANN_CPP_H_INCLUDED */