Simple.xs

filter: Statementstmt 87.4% 363 / 415 Branchbran 70.9% 132 / 186 Conditioncond n/a MC/DCmcdc n/a Subroutinesub n/a Podpod n/a totaltotal 82.3% 495 / 601 CC 0 SCAR 0
CC
0
Cov
0%
CRAP 0
« blib/lib/AI/NeuralNet/Simple.pm ↑ Summary
1 #include "EXTERN.h"
2 #include "perl.h"
3 #include "XSUB.h"
4  
5 /*
6 * Macros and symbolic constants
7 */
8  
9 #define RAND_WEIGHT ( ((float)rand() / (float)RAND_MAX) - 0.5 )
10  
11 #define sqr(x) ((x) * (x))
12  
13 typedef struct {
14 double **input_to_hidden;
15 double **hidden_to_output;
16 } SYNAPSE;
17  
18 SYNAPSE weight;
19  
20 typedef struct {
21 double *hidden;
22 double *output;
23 } ERROR;
24  
25 ERROR error;
26  
27 typedef struct {
28 double *input;
29 double *hidden;
30 double *output;
31 double *target;
32 } LAYER;
33  
34 LAYER neuron;
35  
36 typedef struct {
37 int input;
38 int hidden;
39 int output;
40 } NEURON_COUNT;
41  
42 typedef struct {
43 float learn_rate;
44 double delta;
45 int use_bipolar;
46 SYNAPSE weight;
47 ERROR error;
48 LAYER neuron;
49 NEURON_COUNT size;
50 double *tmp;
51 } NEURAL_NETWORK;
52  
53 int networks = 0;
54 NEURAL_NETWORK **network = NULL;
55  
56 AV* get_array_from_aoa(SV* scalar, int index);
57 AV* get_array(SV* aref);
58 SV* get_element(AV* array, int index);
59  
60 double sigmoid(NEURAL_NETWORK *n, double val);
61 double sigmoid_derivative(NEURAL_NETWORK *n, double val);
62 float get_float_element(AV* array, int index);
63 int is_array_ref(SV* ref);
64 void c_assign_random_weights(NEURAL_NETWORK *);
65 void c_back_propagate(NEURAL_NETWORK *);
66 void c_destroy_network(int);
67 void c_feed(NEURAL_NETWORK *, double *input, double *output, int learn);
68 void c_feed_forward(NEURAL_NETWORK *);
69 float c_get_learn_rate(int);
70 void c_set_learn_rate(int, float);
71 SV* c_export_network(int handle);
72 int c_import_network(SV *);
73  
74 #define ABS(x) ((x) > 0.0 ? (x) : -(x))
75  
76 320057 int is_array_ref(SV* ref)
77 {
78 320057 ▶ if (SvROK(ref) && SvTYPE(SvRV(ref)) == SVt_PVAV)
Branch: 2 branches
BranchTrueFalseTotal
if (SvROK(ref) && SvTYPE(SvRV(ref)) == SVt_PVAV) 320057 0 320057
if (SvROK(ref) && SvTYPE(SvRV(ref)) == SVt_PVAV) 320057 0 320057
79 320057 return 1;
80 else
81 0 return 0;
82 }
83  
84 120015 double sigmoid(NEURAL_NETWORK *n, double val)
85 {
86 120015 return 1.0 / (1.0 + exp(-n->delta * val));
87 }
88  
89 120003 double sigmoid_derivative(NEURAL_NETWORK *n, double val)
90 {
91 /*
92 * It's always called with val=sigmoid(x) and we want sigmoid'(x).
93 *
94 * Since sigmoid'(x) = delta * sigmoid(x) * (1 - sigmoid(x))
95 * the value we return is extremely simple.
96 *
97 * sigmoid_derivative(x) is NOT sigmoid'(x).
98 */
99  
100 120003 return n->delta * val * (1.0 - val);
101 }
102  
103 /* Not using tanh() as this is already defined in math headers */
104 120480 double hyperbolic_tan(NEURAL_NETWORK *n, double val)
105 {
106 120480 double epx = exp(n->delta * val);
107 120480 double emx = exp(-n->delta * val);
108  
109 120480 return (epx - emx) / (epx + emx);
110 }
111  
112 120444 double hyperbolic_tan_derivative(NEURAL_NETWORK *n, double val)
113 {
114 /*
115 * It's always called with val=tanh(delta*x) and we want tanh'(delta*x).
116 *
117 * Since tanh'(delta*x) = delta * (1 - tanh(delta*x)^2)
118 * the value we return is extremely simple.
119 *
120 * hyperbolic_tan_derivative(x) is NOT tanh'(x).
121 */
122  
123 120444 return n->delta * (1.0 - val * val);
124 }
125  
126 160047 AV* get_array(SV* aref)
127 {
128 160047 ▶ if (! is_array_ref(aref))
Branch: 1 branch
BranchTrueFalseTotal
if (! is_array_ref(aref)) 0 160047 160047
129 0 croak("get_array() argument is not an array reference");
130
131 160047 return (AV*) SvRV(aref);
132 }
133  
134 320062 float get_float_element(AV* array, int index)
135 {
136 SV **sva;
137 SV *sv;
138  
139 320062 sva = av_fetch(array, index, 0);
140 320062 ▶ if (!sva)
Branch: 1 branch
BranchTrueFalseTotal
if (!sva) 0 320062 320062
141 0 return 0.0;
142  
143 320062 sv = *sva;
144 320062 return SvNV(sv);
145 }
146  
147 10 SV* get_element(AV* array, int index)
148 {
149 SV **temp;
150 10 temp = av_fetch(array, index, 0);
151  
152 10 ▶ if (!temp)
Branch: 1 branch
BranchTrueFalseTotal
if (!temp) 0 10 10
153 0 croak("Item %d in array is not defined", index);
154  
155 10 return *temp;
156 }
157  
158 10 AV* get_array_from_aoa(SV* aref, int index)
159 {
160 SV *elem;
161 AV *array;
162  
163 /* dereference array and get requested arrayref */
164 10 array = get_array(aref);
165 10 elem = get_element(array, index);
166
167 /* dereference array ref */
168 10 return get_array(elem);
169 }
170  
171 80048 NEURAL_NETWORK *c_get_network(int handle)
172 {
173 NEURAL_NETWORK *n;
174  
175 80048 ▶ if (handle < 0 || handle >= networks)
Branch: 2 branches
BranchTrueFalseTotal
if (handle < 0 || handle >= networks) 80048 0 80048
if (handle < 0 || handle >= networks) 0 80048 80048
176 0 croak("Invalid neural network handle");
177  
178 80048 n = network[handle];
179  
180 80048 ▶ if (n == NULL)
Branch: 1 branch
BranchTrueFalseTotal
if (n == NULL) 0 80048 80048
181 0 croak("Stale neural network handle");
182  
183 80048 return n;
184 }
185  
186 6 int c_new_handle(void)
187 {
188 6 int handle = -1;
189  
190 /*
191 * Allocate the network array if not already done.
192 * Then allocate a new handle for the network.
193 */
194  
195 6 ▶ if (network == NULL) {
Branch: 1 branch
BranchTrueFalseTotal
if (network == NULL) { 3 3 6
196 int i;
197  
198 3 networks = 10;
199 3 network = malloc(networks * sizeof(*network));
200  
201 33 ▶ for (i = 0; i < networks; i++)
Branch: 1 branch
BranchTrueFalseTotal
for (i = 0; i < networks; i++) 30 3 33
202 30 network[i] = NULL;
203  
204 3 handle = 0;
205 } else {
206 int i;
207  
208 5 ▶ for (i = 0; i < networks; i++) {
Branch: 1 branch
BranchTrueFalseTotal
for (i = 0; i < networks; i++) { 5 0 5
209 5 ▶ if (network[i] == NULL) {
Branch: 1 branch
BranchTrueFalseTotal
if (network[i] == NULL) { 3 2 5
210 3 handle = i;
211 3 break;
212 }
213 }
214  
215 3 ▶ if (handle == -1) {
Branch: 1 branch
BranchTrueFalseTotal
if (handle == -1) { 0 3 3
216 0 handle = networks;
217 0 networks += 10;
218 0 network = realloc(network, networks * sizeof(*network));
219  
220 0 ▶ for (i = networks - 10; i < networks; i++)
Branch: 1 branch
BranchTrueFalseTotal
for (i = networks - 10; i < networks; i++) 0 0 0
221 0 network[i] = NULL;
222 }
223 }
224  
225 6 network[handle] = malloc(sizeof(NEURAL_NETWORK));
226  
227 6 return handle;
228 }
229  
230 6 float c_get_learn_rate(int handle)
231 {
232 6 NEURAL_NETWORK *n = c_get_network(handle);
233  
234 6 return n->learn_rate;
235 }
236  
237 5 void c_set_learn_rate(int handle, float rate)
238 {
239 5 NEURAL_NETWORK *n = c_get_network(handle);
240  
241 5 n->learn_rate = rate;
242 5 }
243  
244 1 double c_get_delta(int handle)
245 {
246 1 NEURAL_NETWORK *n = c_get_network(handle);
247  
248 1 return n->delta;
249 }
250  
251  
252 2 void c_set_delta(int handle, double delta)
253 {
254 2 NEURAL_NETWORK *n = c_get_network(handle);
255  
256 2 n->delta = delta;
257 2 }
258  
259 1 int c_get_use_bipolar(int handle)
260 {
261 1 NEURAL_NETWORK *n = c_get_network(handle);
262  
263 1 return n->use_bipolar;
264 }
265  
266 2 void c_set_use_bipolar(int handle, int bipolar)
267 {
268 2 NEURAL_NETWORK *n = c_get_network(handle);
269  
270 2 n->use_bipolar = bipolar;
271 2 }
272  
273 6 int c_create_network(NEURAL_NETWORK *n)
274 {
275 int i;
276 /* each of the next two variables has an extra row for the "bias" */
277 6 int input_layer_with_bias = n->size.input + 1;
278 6 int hidden_layer_with_bias = n->size.hidden + 1;
279  
280 6 n->learn_rate = .2;
281 6 n->delta = 1.0;
282 6 n->use_bipolar = 0;
283  
284 6 n->tmp = malloc(sizeof(double) * n->size.input);
285  
286 6 n->neuron.input = malloc(sizeof(double) * n->size.input);
287 6 n->neuron.hidden = malloc(sizeof(double) * n->size.hidden);
288 6 n->neuron.output = malloc(sizeof(double) * n->size.output);
289 6 n->neuron.target = malloc(sizeof(double) * n->size.output);
290  
291 6 n->error.hidden = malloc(sizeof(double) * n->size.hidden);
292 6 n->error.output = malloc(sizeof(double) * n->size.output);
293
294 /* one extra for sentinel */
295 n->weight.input_to_hidden
296 6 = malloc(sizeof(void *) * (input_layer_with_bias + 1));
297 n->weight.hidden_to_output
298 6 = malloc(sizeof(void *) * (hidden_layer_with_bias + 1));
299  
300 6 ▶ if(!n->weight.input_to_hidden || !n->weight.hidden_to_output) {
Branch: 2 branches
BranchTrueFalseTotal
if(!n->weight.input_to_hidden || !n->weight.hidden_to_output) { 6 0 6
if(!n->weight.input_to_hidden || !n->weight.hidden_to_output) { 0 6 6
301 0 printf("Initial malloc() failed\n");
302 0 return 0;
303 }
304
305 /* now allocate the actual rows */
306 27 ▶ for(i = 0; i < input_layer_with_bias; i++) {
Branch: 1 branch
BranchTrueFalseTotal
for(i = 0; i < input_layer_with_bias; i++) { 21 6 27
307 21 n->weight.input_to_hidden[i]
308 21 = malloc(hidden_layer_with_bias * sizeof(double));
309 21 ▶ if(n->weight.input_to_hidden[i] == 0) {
Branch: 1 branch
BranchTrueFalseTotal
if(n->weight.input_to_hidden[i] == 0) { 0 21 21
310 0 free(*n->weight.input_to_hidden);
311 0 printf("Second malloc() to weight.input_to_hidden failed\n");
312 0 return 0;
313 }
314 }
315  
316 /* now allocate the actual rows */
317 25 ▶ for(i = 0; i < hidden_layer_with_bias; i++) {
Branch: 1 branch
BranchTrueFalseTotal
for(i = 0; i < hidden_layer_with_bias; i++) { 19 6 25
318 19 n->weight.hidden_to_output[i]
319 19 = malloc(n->size.output * sizeof(double));
320 19 ▶ if(n->weight.hidden_to_output[i] == 0) {
Branch: 1 branch
BranchTrueFalseTotal
if(n->weight.hidden_to_output[i] == 0) { 0 19 19
321 0 free(*n->weight.hidden_to_output);
322 0 printf("Second malloc() to weight.hidden_to_output failed\n");
323 0 return 0;
324 }
325 }
326  
327 /* initialize the sentinel value */
328 6 n->weight.input_to_hidden[input_layer_with_bias] = 0;
329 6 n->weight.hidden_to_output[hidden_layer_with_bias] = 0;
330  
331 6 return 1;
332 }
333  
334 6 void c_destroy_network(int handle)
335 {
336 double **row;
337 6 NEURAL_NETWORK *n = c_get_network(handle);
338  
339 27 ▶ for(row = n->weight.input_to_hidden; *row != 0; row++) {
Branch: 1 branch
BranchTrueFalseTotal
for(row = n->weight.input_to_hidden; *row != 0; row++) { 21 6 27
340 21 free(*row);
341 }
342 6 free(n->weight.input_to_hidden);
343  
344 25 ▶ for(row = n->weight.hidden_to_output; *row != 0; row++) {
Branch: 1 branch
BranchTrueFalseTotal
for(row = n->weight.hidden_to_output; *row != 0; row++) { 19 6 25
345 19 free(*row);
346 }
347 6 free(n->weight.hidden_to_output);
348  
349 6 free(n->neuron.input);
350 6 free(n->neuron.hidden);
351 6 free(n->neuron.output);
352 6 free(n->neuron.target);
353  
354 6 free(n->error.hidden);
355 6 free(n->error.output);
356  
357 6 free(n->tmp);
358  
359 6 network[handle] = NULL;
360 6 }
361  
362 /*
363 * Build a Perl reference on array `av'.
364 * This performs something like "$rv = \@av;" in Perl.
365 */
366 8 SV *build_rv(AV *av)
367 {
368 SV *rv;
369  
370 /*
371 * To understand what is going on here, look at retrieve_ref()
372 * in the Storable.xs file. In particular, we don't perform
373 * an SvREFCNT_inc(av) because the av we're supplying is going
374 * to be referenced only by the REF we're building here.
375 * --RAM
376 */
377  
378 8 rv = NEWSV(10002, 0);
379 8 sv_upgrade(rv, SVt_RV);
380 8 SvRV(rv) = (SV *) av;
381 8 SvROK_on(rv);
382  
383 8 return rv;
384 }
385  
386 /*
387 * Build reference to a 2-dimensional array, implemented as an array
388 * or array references. The holding array has `rows' rows and each array
389 * reference has `columns' entries.
390 *
391 * The name "axa" denotes the "product" of 2 arrays.
392 */
393 2 SV *build_axaref(void *arena, int rows, int columns)
394 {
395 AV *av;
396 int i;
397 double **p;
398  
399 2 av = newAV();
400 2 av_extend(av, rows);
401  
402 7 ▶ for (i = 0, p = arena; i < rows; i++, p++) {
Branch: 1 branch
BranchTrueFalseTotal
for (i = 0, p = arena; i < rows; i++, p++) { 5 2 7
403 int j;
404 double *q;
405 AV *av2;
406  
407 5 av2 = newAV();
408 5 av_extend(av2, columns);
409  
410 15 ▶ for (j = 0, q = *p; j < columns; j++, q++)
Branch: 1 branch
BranchTrueFalseTotal
for (j = 0, q = *p; j < columns; j++, q++) 10 5 15
411 10 av_store(av2, j, newSVnv((NV) *q));
412  
413 5 av_store(av, i, build_rv(av2));
414 }
415  
416 2 return build_rv(av);
417 }
418  
419 #define EXPORT_VERSION 1
420 #define EXPORTED_ITEMS 9
421  
422 /*
423 * Exports the C data structures to the Perl world for serialization
424 * by Storable. We don't want to duplicate the logic of Storable here
425 * even though we have to do some low-level Perl object construction.
426 *
427 * The structure we return is an array reference, which contains the
428 * following items:
429 *
430 * 0 the export version number, in case format changes later
431 * 1 the amount of neurons in the input layer
432 * 2 the amount of neurons in the hidden layer
433 * 3 the amount of neurons in the output layer
434 * 4 the learning rate
435 * 5 the sigmoid delta
436 * 6 whether to use a bipolar (tanh) routine instead of the sigmoid
437 * 7 [[weight.input_to_hidden[0]], [weight.input_to_hidden[1]], ...]
438 * 8 [[weight.hidden_to_output[0]], [weight.hidden_to_output[1]], ...]
439 */
440 1 SV *c_export_network(int handle)
441 {
442 1 NEURAL_NETWORK *n = c_get_network(handle);
443 AV *av;
444 1 int i = 0;
445  
446 1 av = newAV();
447 1 av_extend(av, EXPORTED_ITEMS);
448  
449 1 av_store(av, i++, newSViv(EXPORT_VERSION));
450 1 av_store(av, i++, newSViv(n->size.input));
451 1 av_store(av, i++, newSViv(n->size.hidden));
452 1 av_store(av, i++, newSViv(n->size.output));
453 1 av_store(av, i++, newSVnv(n->learn_rate));
454 1 av_store(av, i++, newSVnv(n->delta));
455 1 av_store(av, i++, newSViv(n->use_bipolar));
456 1 av_store(av, i++,
457 build_axaref(n->weight.input_to_hidden,
458 n->size.input + 1, n->size.hidden + 1));
459 1 av_store(av, i++,
460 build_axaref(n->weight.hidden_to_output,
461 n->size.hidden + 1, n->size.output));
462  
463 1 ▶ if (i != EXPORTED_ITEMS)
Branch: 1 branch
BranchTrueFalseTotal
if (i != EXPORTED_ITEMS) 0 1 1
464 0 croak("BUG in c_export_network()");
465  
466 1 return build_rv(av);
467 }
468  
469 /*
470 * Load a Perl array of array (a matrix) with "rows" rows and "columns" columns
471 * into the pre-allocated C array of arrays.
472 *
473 * The "hold" argument is an holding array and the Perl array of array which
474 * we expect is at index "idx" within that holding array.
475 */
476 2 void c_load_axa(AV *hold, int idx, void *arena, int rows, int columns)
477 {
478 SV **sav;
479 SV *rv;
480 AV *av;
481 int i;
482 2 double **array = arena;
483  
484 2 sav = av_fetch(hold, idx, 0);
485 2 ▶ if (sav == NULL)
Branch: 1 branch
BranchTrueFalseTotal
if (sav == NULL) 0 2 2
486 0 croak("serialized item %d is not defined", idx);
487  
488 2 rv = *sav;
489 2 ▶ if (!is_array_ref(rv))
Branch: 1 branch
BranchTrueFalseTotal
if (!is_array_ref(rv)) 0 2 2
490 0 croak("serialized item %d is not an array reference", idx);
491  
492 2 av = get_array(rv); /* This is an array of array refs */
493  
494 7 ▶ for (i = 0; i < rows; i++) {
Branch: 1 branch
BranchTrueFalseTotal
for (i = 0; i < rows; i++) { 5 2 7
495 5 double *row = array[i];
496 int j;
497 AV *subav;
498  
499 5 sav = av_fetch(av, i, 0);
500 5 ▶ if (sav == NULL)
Branch: 1 branch
BranchTrueFalseTotal
if (sav == NULL) 0 5 5
501 0 croak("serialized item %d has undefined row %d", idx, i);
502 5 rv = *sav;
503 5 ▶ if (!is_array_ref(rv))
Branch: 1 branch
BranchTrueFalseTotal
if (!is_array_ref(rv)) 0 5 5
504 0 croak("row %d of serialized item %d is not an array ref", i, idx);
505  
506 5 subav = get_array(rv);
507  
508 15 ▶ for (j = 0; j < columns; j++)
Branch: 1 branch
BranchTrueFalseTotal
for (j = 0; j < columns; j++) 10 5 15
509 10 row[j] = get_float_element(subav, j);
510 }
511 2 }
512  
513 /*
514 * Create new network from a retrieved data structure, such as the one
515 * produced by c_export_network().
516 */
517 1 int c_import_network(SV *rv)
518 {
519 NEURAL_NETWORK *n;
520 int handle;
521 SV **sav;
522 AV *av;
523 1 int i = 0;
524  
525 /*
526 * Unfortunately, since those data come from the outside, we need
527 * to validate most of the structural information to make sure
528 * we're not fed garbage or something we cannot process, like a
529 * newer version of the serialized data. This makes the code heavy.
530 * --RAM
531 */
532  
533 1 ▶ if (!is_array_ref(rv))
Branch: 1 branch
BranchTrueFalseTotal
if (!is_array_ref(rv)) 0 1 1
534 0 croak("c_import_network() not given an array reference");
535  
536 1 av = get_array(rv);
537  
538 /* Check version number */
539 1 sav = av_fetch(av, i++, 0);
540 1 ▶ if (sav == NULL || SvIVx(*sav) != EXPORT_VERSION)
Branch: 2 branches
BranchTrueFalseTotal
if (sav == NULL || SvIVx(*sav) != EXPORT_VERSION) 1 0 1
if (sav == NULL || SvIVx(*sav) != EXPORT_VERSION) 0 1 1
541 0 ▶ croak("c_import_network() given unknown version %d",
Branch: 1 branch
BranchTrueFalseTotal
croak("c_import_network() given unknown version %d", 0 0 0
542 sav == NULL ? 0 : SvIVx(*sav));
543  
544 /* Check length -- at version 1, length is fixed to 13 */
545 1 ▶ if (av_len(av) + 1 != EXPORTED_ITEMS)
Branch: 1 branch
BranchTrueFalseTotal
if (av_len(av) + 1 != EXPORTED_ITEMS) 0 1 1
546 0 croak("c_import_network() not given a %d-item array reference",
547 EXPORTED_ITEMS);
548  
549 1 handle = c_new_handle();
550 1 n = c_get_network(handle);
551  
552 1 sav = av_fetch(av, i++, 0);
553 1 ▶ if (sav == NULL)
Branch: 1 branch
BranchTrueFalseTotal
if (sav == NULL) 0 1 1
554 0 croak("undefined input size (item %d)", i - 1);
555 1 n->size.input = SvIVx(*sav);
556  
557 1 sav = av_fetch(av, i++, 0);
558 1 ▶ if (sav == NULL)
Branch: 1 branch
BranchTrueFalseTotal
if (sav == NULL) 0 1 1
559 0 croak("undefined hidden size (item %d), i - 1");
560 1 n->size.hidden = SvIVx(*sav);
561  
562 1 sav = av_fetch(av, i++, 0);
563 1 ▶ if (sav == NULL)
Branch: 1 branch
BranchTrueFalseTotal
if (sav == NULL) 0 1 1
564 0 croak("undefined output size (item %d)", i - 1);
565 1 n->size.output = SvIVx(*sav);
566  
567 1 ▶ if (!c_create_network(n))
Branch: 1 branch
BranchTrueFalseTotal
if (!c_create_network(n)) 0 1 1
568 0 return -1;
569  
570 1 sav = av_fetch(av, i++, 0);
571 1 ▶ if (sav == NULL)
Branch: 1 branch
BranchTrueFalseTotal
if (sav == NULL) 0 1 1
572 0 croak("undefined learn_rate (item %d)", i - 1);
573 1 n->learn_rate = SvNVx(*sav);
574  
575 1 sav = av_fetch(av, i++, 0);
576 1 ▶ if (sav == NULL)
Branch: 1 branch
BranchTrueFalseTotal
if (sav == NULL) 0 1 1
577 0 croak("undefined delta (item %d)", i - 1);
578 1 n->delta = SvNVx(*sav);
579  
580 1 sav = av_fetch(av, i++, 0);
581 1 ▶ if (sav == NULL)
Branch: 1 branch
BranchTrueFalseTotal
if (sav == NULL) 0 1 1
582 0 croak("undefined use_bipolar (item %d)", i - 1);
583 1 n->use_bipolar = SvIVx(*sav);
584  
585 1 c_load_axa(av, i++, n->weight.input_to_hidden,
586 1 n->size.input + 1, n->size.hidden + 1);
587 1 c_load_axa(av, i++, n->weight.hidden_to_output,
588 1 n->size.hidden + 1, n->size.output);
589  
590 1 return handle;
591 }
592  
593 /*
594 * Support functions for back propogation
595 */
596  
597 5 void c_assign_random_weights(NEURAL_NETWORK *n)
598 {
599 int hid, inp, out;
600  
601 23 ▶ for (inp = 0; inp < n->size.input + 1; inp++) {
Branch: 1 branch
BranchTrueFalseTotal
for (inp = 0; inp < n->size.input + 1; inp++) { 18 5 23
602 78 ▶ for (hid = 0; hid < n->size.hidden; hid++) {
Branch: 1 branch
BranchTrueFalseTotal
for (hid = 0; hid < n->size.hidden; hid++) { 60 18 78
603 60 n->weight.input_to_hidden[inp][hid] = RAND_WEIGHT;
604 }
605 }
606  
607 22 ▶ for (hid = 0; hid < n->size.hidden + 1; hid++) {
Branch: 1 branch
BranchTrueFalseTotal
for (hid = 0; hid < n->size.hidden + 1; hid++) { 17 5 22
608 51 ▶ for (out = 0; out < n->size.output; out++) {
Branch: 1 branch
BranchTrueFalseTotal
for (out = 0; out < n->size.output; out++) { 34 17 51
609 34 n->weight.hidden_to_output[hid][out] = RAND_WEIGHT;
610 }
611 }
612 5 }
613  
614 /*
615 * Feed-forward Algorithm
616 */
617  
618 80165 void c_feed_forward(NEURAL_NETWORK *n)
619 {
620 int inp, hid, out;
621 double sum;
622 double (*activation)(NEURAL_NETWORK *, double);
623  
624 80165 ▶ activation = n->use_bipolar ? hyperbolic_tan : sigmoid;
Branch: 1 branch
BranchTrueFalseTotal
activation = n->use_bipolar ? hyperbolic_tan : sigmoid; 40160 40005 80165
625  
626 /* calculate input to hidden layer */
627 160330 ▶ for (hid = 0; hid < n->size.hidden; hid++) {
Branch: 1 branch
BranchTrueFalseTotal
for (hid = 0; hid < n->size.hidden; hid++) { 80165 80165 160330
628  
629 80165 sum = 0.0;
630 240495 ▶ for (inp = 0; inp < n->size.input; inp++) {
Branch: 1 branch
BranchTrueFalseTotal
for (inp = 0; inp < n->size.input; inp++) { 160330 80165 240495
631 160330 sum += n->neuron.input[inp]
632 160330 * n->weight.input_to_hidden[inp][hid];
633 }
634  
635 /* add in bias */
636 80165 sum += n->weight.input_to_hidden[n->size.input][hid];
637  
638 80165 n->neuron.hidden[hid] = (*activation)(n, sum);
639 }
640  
641 /* calculate the hidden to output layer */
642 240495 ▶ for (out = 0; out < n->size.output; out++) {
Branch: 1 branch
BranchTrueFalseTotal
for (out = 0; out < n->size.output; out++) { 160330 80165 240495
643  
644 160330 sum = 0.0;
645 320660 ▶ for (hid = 0; hid < n->size.hidden; hid++) {
Branch: 1 branch
BranchTrueFalseTotal
for (hid = 0; hid < n->size.hidden; hid++) { 160330 160330 320660
646 160330 sum += n->neuron.hidden[hid]
647 160330 * n->weight.hidden_to_output[hid][out];
648 }
649  
650 /* add in bias */
651 160330 sum += n->weight.hidden_to_output[n->size.hidden][out];
652  
653 160330 n->neuron.output[out] = (*activation)(n, sum);
654 }
655 80165 }
656  
657 /*
658 * Back-propogation algorithm. This is where the learning gets done.
659 */
660 80149 void c_back_propagate(NEURAL_NETWORK *n)
661 {
662 int inp, hid, out;
663 double (*activation_derivative)(NEURAL_NETWORK *, double);
664  
665 160298 activation_derivative = n->use_bipolar ?
666 80149 ▶ hyperbolic_tan_derivative : sigmoid_derivative;
Branch: 1 branch
BranchTrueFalseTotal
hyperbolic_tan_derivative : sigmoid_derivative; 40148 40001 80149
667  
668 /* calculate the output layer error (step 3 for output cell) */
669 240447 ▶ for (out = 0; out < n->size.output; out++) {
Branch: 1 branch
BranchTrueFalseTotal
for (out = 0; out < n->size.output; out++) { 160298 80149 240447
670 160298 n->error.output[out] =
671 160298 (n->neuron.target[out] - n->neuron.output[out])
672 160298 * (*activation_derivative)(n, n->neuron.output[out]);
673 }
674  
675 /* calculate the hidden layer error (step 3 for hidden cell) */
676 160298 ▶ for (hid = 0; hid < n->size.hidden; hid++) {
Branch: 1 branch
BranchTrueFalseTotal
for (hid = 0; hid < n->size.hidden; hid++) { 80149 80149 160298
677  
678 80149 n->error.hidden[hid] = 0.0;
679 240447 ▶ for (out = 0; out < n->size.output; out++) {
Branch: 1 branch
BranchTrueFalseTotal
for (out = 0; out < n->size.output; out++) { 160298 80149 240447
680 160298 n->error.hidden[hid]
681 160298 += n->error.output[out]
682 160298 * n->weight.hidden_to_output[hid][out];
683 }
684 80149 n->error.hidden[hid]
685 80149 *= (*activation_derivative)(n, n->neuron.hidden[hid]);
686 }
687  
688 /* update the weights for the output layer (step 4) */
689 240447 ▶ for (out = 0; out < n->size.output; out++) {
Branch: 1 branch
BranchTrueFalseTotal
for (out = 0; out < n->size.output; out++) { 160298 80149 240447
690 320596 ▶ for (hid = 0; hid < n->size.hidden; hid++) {
Branch: 1 branch
BranchTrueFalseTotal
for (hid = 0; hid < n->size.hidden; hid++) { 160298 160298 320596
691 160298 n->weight.hidden_to_output[hid][out]
692 160298 += (n->learn_rate
693 160298 * n->error.output[out]
694 160298 * n->neuron.hidden[hid]);
695 }
696  
697 /* update the bias */
698 160298 n->weight.hidden_to_output[n->size.hidden][out]
699 160298 += (n->learn_rate
700 160298 * n->error.output[out]);
701 }
702  
703 /* update the weights for the hidden layer (step 4) */
704 160298 ▶ for (hid = 0; hid < n->size.hidden; hid++) {
Branch: 1 branch
BranchTrueFalseTotal
for (hid = 0; hid < n->size.hidden; hid++) { 80149 80149 160298
705  
706 240447 ▶ for (inp = 0; inp < n->size.input; inp++) {
Branch: 1 branch
BranchTrueFalseTotal
for (inp = 0; inp < n->size.input; inp++) { 160298 80149 240447
707 160298 n->weight.input_to_hidden[inp][hid]
708 160298 += (n->learn_rate
709 160298 * n->error.hidden[hid]
710 160298 * n->neuron.input[inp]);
711 }
712  
713 /* update the bias */
714 80149 n->weight.input_to_hidden[n->size.input][hid]
715 80149 += (n->learn_rate
716 80149 * n->error.hidden[hid]);
717 }
718 80149 }
719  
720 /*
721 * Compute the Mean Square Error between the actual output and the
722 * targeted output.
723 */
724 80149 double mean_square_error(NEURAL_NETWORK *n, double *target)
725 {
726 80149 double error = 0.0;
727 int i;
728  
729 240447 ▶ for (i = 0; i < n->size.output; i++)
Branch: 1 branch
BranchTrueFalseTotal
for (i = 0; i < n->size.output; i++) 160298 80149 240447
730 160298 error += sqr(target[i] - n->neuron.output[i]);
731  
732 80149 return 0.5 * error;
733 }
734  
735 80001 double c_train(int handle, SV* input, SV* output)
736 {
737 80001 NEURAL_NETWORK *n = c_get_network(handle);
738 int i,length;
739 AV *array;
740 80001 double *input_array = malloc(sizeof(double) * n->size.input);
741 80001 double *output_array = malloc(sizeof(double) * n->size.output);
742 double error;
743  
744 80001 ▶ if (! is_array_ref(input) || ! is_array_ref(output)) {
Branch: 2 branches
BranchTrueFalseTotal
if (! is_array_ref(input) || ! is_array_ref(output)) { 80001 0 80001
if (! is_array_ref(input) || ! is_array_ref(output)) { 0 80001 80001
745 0 croak("train() takes two arrayrefs.");
746 }
747
748 80001 array = get_array(input);
749 80001 length = av_len(array)+ 1;
750
751 80001 ▶ if (length != n->size.input) {
Branch: 1 branch
BranchTrueFalseTotal
if (length != n->size.input) { 0 80001 80001
752 0 croak("Length of input array does not match network");
753 }
754 240003 ▶ for (i = 0; i < length; i++) {
Branch: 1 branch
BranchTrueFalseTotal
for (i = 0; i < length; i++) { 160002 80001 240003
755 160002 input_array[i] = get_float_element(array, i);
756 }
757  
758 80001 array = get_array(output);
759 80001 length = av_len(array) + 1;
760
761 80001 ▶ if (length != n->size.output) {
Branch: 1 branch
BranchTrueFalseTotal
if (length != n->size.output) { 0 80001 80001
762 0 croak("Length of output array does not match network");
763 }
764 240003 ▶ for (i = 0; i < length; i++) {
Branch: 1 branch
BranchTrueFalseTotal
for (i = 0; i < length; i++) { 160002 80001 240003
765 160002 output_array[i] = get_float_element(array, i);
766 }
767  
768 80001 c_feed(n, input_array, output_array, 1);
769 80001 error = mean_square_error(n, output_array);
770  
771 80001 free(input_array);
772 80001 free(output_array);
773  
774 80001 return error;
775 }
776  
777 5 int c_new_network(int input, int hidden, int output)
778 {
779 NEURAL_NETWORK *n;
780 int handle;
781  
782 5 handle = c_new_handle();
783 5 n = c_get_network(handle);
784  
785 5 n->size.input = input;
786 5 n->size.hidden = hidden;
787 5 n->size.output = output;
788  
789 5 ▶ if (!c_create_network(n))
Branch: 1 branch
BranchTrueFalseTotal
if (!c_create_network(n)) 0 5 5
790 0 return -1;
791  
792 /* Perl already seeded the random number generator, via a rand(1) call */
793  
794 5 c_assign_random_weights(n);
795  
796 5 return handle;
797 }
798  
799 1 double c_train_set(int handle, SV* set, int iterations, double mse)
800 {
801 1 NEURAL_NETWORK *n = c_get_network(handle);
802 AV *input_array, *output_array; /* perl arrays */
803 double *input, *output; /* C arrays */
804 1 double max_error = 0.0;
805  
806 1 int set_length=0;
807 int i,j;
808 int index;
809  
810 1 set_length = av_len(get_array(set))+1;
811  
812 1 ▶ if (!set_length)
Branch: 1 branch
BranchTrueFalseTotal
if (!set_length) 0 1 1
813 0 croak("_train_set() array ref has no data");
814 1 ▶ if (set_length % 2)
Branch: 1 branch
BranchTrueFalseTotal
if (set_length % 2) 0 1 1
815 0 croak("_train_set array ref must have an even number of elements");
816  
817 /* allocate memory for out input and output arrays */
818 1 input_array = get_array_from_aoa(set, 0);
819 1 input = malloc(sizeof(double) * set_length * (av_len(input_array)+1));
820  
821 1 output_array = get_array_from_aoa(set, 1);
822 1 output = malloc(sizeof(double) * set_length * (av_len(output_array)+1));
823  
824 5 ▶ for (i=0; i < set_length; i += 2) {
Branch: 1 branch
BranchTrueFalseTotal
for (i=0; i < set_length; i += 2) { 4 1 5
825 4 input_array = get_array_from_aoa(set, i);
826
827 4 ▶ if (av_len(input_array)+1 != n->size.input)
Branch: 1 branch
BranchTrueFalseTotal
if (av_len(input_array)+1 != n->size.input) 0 4 4
828 0 croak("Length of input data does not match");
829
830 /* iterate over the input_array and assign the floats to input */
831
832 12 ▶ for (j = 0; j < n->size.input; j++) {
Branch: 1 branch
BranchTrueFalseTotal
for (j = 0; j < n->size.input; j++) { 8 4 12
833 8 index = (i/2*n->size.input)+j;
834 8 input[index] = get_float_element(input_array, j);
835 }
836
837 4 output_array = get_array_from_aoa(set, i+1);
838 4 ▶ if (av_len(output_array)+1 != n->size.output)
Branch: 1 branch
BranchTrueFalseTotal
if (av_len(output_array)+1 != n->size.output) 0 4 4
839 0 croak("Length of output data does not match");
840  
841 12 ▶ for (j = 0; j < n->size.output; j++) {
Branch: 1 branch
BranchTrueFalseTotal
for (j = 0; j < n->size.output; j++) { 8 4 12
842 8 index = (i/2*n->size.output)+j;
843 8 output[index] = get_float_element(output_array, j);
844 }
845 }
846  
847 37 ▶ for (i = 0; i < iterations; i++) {
Branch: 1 branch
BranchTrueFalseTotal
for (i = 0; i < iterations; i++) { 37 0 37
848 37 max_error = 0.0;
849  
850 185 ▶ for (j = 0; j < (set_length/2); j++) {
Branch: 1 branch
BranchTrueFalseTotal
for (j = 0; j < (set_length/2); j++) { 148 37 185
851 double error;
852  
853 148 c_feed(n, &input[j*n->size.input], &output[j*n->size.output], 1);
854  
855 148 ▶ if (mse >= 0.0 || i == iterations - 1) {
Branch: 2 branches
BranchTrueFalseTotal
if (mse >= 0.0 || i == iterations - 1) { 0 148 148
if (mse >= 0.0 || i == iterations - 1) { 0 0 0
856 148 error = mean_square_error(n, &output[j*n->size.output]);
857 148 ▶ if (error > max_error)
Branch: 1 branch
BranchTrueFalseTotal
if (error > max_error) 38 110 148
858 38 max_error = error;
859 }
860 }
861  
862 37 ▶ if (mse >= 0 && max_error <= mse) /* Below their target! */
Branch: 2 branches
BranchTrueFalseTotal
if (mse >= 0 && max_error <= mse) /* Below their target! */ 37 0 37
if (mse >= 0 && max_error <= mse) /* Below their target! */ 1 36 37
863 1 break;
864 }
865  
866 1 free(input);
867 1 free(output);
868  
869 1 return max_error;
870 }
871  
872 16 SV* c_infer(int handle, SV *array_ref)
873 {
874 16 NEURAL_NETWORK *n = c_get_network(handle);
875 int i;
876 16 AV *perl_array, *result = newAV();
877  
878 /* feed the data */
879 16 perl_array = get_array(array_ref);
880  
881 48 ▶ for (i = 0; i < n->size.input; i++)
Branch: 1 branch
BranchTrueFalseTotal
for (i = 0; i < n->size.input; i++) 32 16 48
882 32 n->tmp[i] = get_float_element(perl_array, i);
883  
884 16 c_feed(n, n->tmp, NULL, 0);
885  
886 /* read the results */
887 48 ▶ for (i = 0; i < n->size.output; i++) {
Branch: 1 branch
BranchTrueFalseTotal
for (i = 0; i < n->size.output; i++) { 32 16 48
888 32 av_push(result, newSVnv(n->neuron.output[i]));
889 }
890 16 return newRV_noinc((SV*) result);
891 }
892  
893 80165 void c_feed(NEURAL_NETWORK *n, double *input, double *output, int learn)
894 {
895 int i;
896  
897 240495 ▶ for (i=0; i < n->size.input; i++) {
Branch: 1 branch
BranchTrueFalseTotal
for (i=0; i < n->size.input; i++) { 160330 80165 240495
898 160330 n->neuron.input[i] = input[i];
899 }
900  
901 80165 ▶ if (learn)
Branch: 1 branch
BranchTrueFalseTotal
if (learn) 80149 16 80165
902 240447 ▶ for (i=0; i < n->size.output; i++)
Branch: 1 branch
BranchTrueFalseTotal
for (i=0; i < n->size.output; i++) 160298 80149 240447
903 160298 n->neuron.target[i] = output[i];
904  
905 80165 c_feed_forward(n);
906  
907 80165 ▶ if (learn) c_back_propagate(n);
Branch: 1 branch
BranchTrueFalseTotal
if (learn) c_back_propagate(n); 80149 16 80165
908 80165 }
909  
910 /*
911 * The original author of this code is M. Tim Jones <mtj@cogitollc.com> and
912 * written for the book "AI Application Programming", by Charles River Media.
913 *
914 * It's been so heavily modified that it bears little resemblance to the
915 * original, but credit should be given where credit is due. Therefore ...
916 *
917 * Copyright (c) 2003 Charles River Media. All rights reserved.
918 *
919 * Redistribution and use in source and binary forms, with or without
920 * modification, is hereby granted without fee provided that the following
921 * conditions are met:
922 *
923 * 1. Redistributions of source code must retain the above copyright
924 * notice, this list of conditions and the following disclaimer. 2.
925 * Redistributions in binary form must reproduce the above copyright
926 * notice, this list of conditions and the following disclaimer in the
927 * documentation and/or other materials provided with the distribution. 3.
928 * Neither the name of Charles River Media nor the names of its
929 * contributors may be used to endorse or promote products derived from
930 * this software without specific prior written permission.
931 *
932 * THIS SOFTWARE IS PROVIDED BY CHARLES RIVER MEDIA AND CONTRIBUTORS 'AS IS'
933 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
934 * IMPLIED WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE
935 * ARE DISCLAIMED. IN NO EVENT SHALL CHARLES RIVER MEDIA OR CONTRIBUTORS BE
936 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
937 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
938 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
939 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
940 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
941 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
942 * POSSIBILITY OF SUCH DAMAGE.
943 */
944  
945 MODULE = AI::NeuralNet::Simple PACKAGE = AI::NeuralNet::Simple
946  
947 PROTOTYPES: DISABLE
948  
949 int
950 is_array_ref (ref)
951 SV * ref
952  
953 AV *
954 get_array (aref)
955 SV * aref
956  
957 float
958 get_float_element (array, index)
959 AV * array
960 int index
961  
962 SV *
963 get_element (array, index)
964 AV * array
965 int index
966  
967 AV *
968 get_array_from_aoa (aref, index)
969 SV * aref
970 int index
971  
972 float
973 c_get_learn_rate (handle)
974 int handle
975  
976 void
977 c_set_learn_rate (handle, rate)
978 int handle
979 float rate
980 PREINIT:
981 I32* temp;
982 PPCODE:
983 5 temp = PL_markstack_ptr++;
984 5 c_set_learn_rate(handle, rate);
985 5 ▶ if (PL_markstack_ptr != temp) {
Branch: 1 branch
BranchTrueFalseTotal
if (PL_markstack_ptr != temp) { 5 0 5
986 /* truly void, because dXSARGS not invoked */
987 5 PL_markstack_ptr = temp;
988 5 XSRETURN_EMPTY; /* return empty stack */
989 }
990 /* must have used dXSARGS; list context implied */
991 0 return; /* assume stack size is correct */
992  
993 double
994 c_get_delta (handle)
995 int handle
996  
997 void
998 c_set_delta (handle, delta)
999 int handle
1000 double delta
1001 PREINIT:
1002 I32* temp;
1003 PPCODE:
1004 2 temp = PL_markstack_ptr++;
1005 2 c_set_delta(handle, delta);
1006 2 ▶ if (PL_markstack_ptr != temp) {
Branch: 1 branch
BranchTrueFalseTotal
if (PL_markstack_ptr != temp) { 2 0 2
1007 /* truly void, because dXSARGS not invoked */
1008 2 PL_markstack_ptr = temp;
1009 2 XSRETURN_EMPTY; /* return empty stack */
1010 }
1011 /* must have used dXSARGS; list context implied */
1012 0 return; /* assume stack size is correct */
1013  
1014 int
1015 c_get_use_bipolar (handle)
1016 int handle
1017  
1018 void
1019 c_set_use_bipolar (handle, bipolar)
1020 int handle
1021 int bipolar
1022 PREINIT:
1023 I32* temp;
1024 PPCODE:
1025 2 temp = PL_markstack_ptr++;
1026 2 c_set_use_bipolar(handle, bipolar);
1027 2 ▶ if (PL_markstack_ptr != temp) {
Branch: 1 branch
BranchTrueFalseTotal
if (PL_markstack_ptr != temp) { 2 0 2
1028 /* truly void, because dXSARGS not invoked */
1029 2 PL_markstack_ptr = temp;
1030 2 XSRETURN_EMPTY; /* return empty stack */
1031 }
1032 /* must have used dXSARGS; list context implied */
1033 0 return; /* assume stack size is correct */
1034  
1035 void
1036 c_destroy_network (handle)
1037 int handle
1038 PREINIT:
1039 I32* temp;
1040 PPCODE:
1041 6 temp = PL_markstack_ptr++;
1042 6 c_destroy_network(handle);
1043 6 ▶ if (PL_markstack_ptr != temp) {
Branch: 1 branch
BranchTrueFalseTotal
if (PL_markstack_ptr != temp) { 6 0 6
1044 /* truly void, because dXSARGS not invoked */
1045 6 PL_markstack_ptr = temp;
1046 6 XSRETURN_EMPTY; /* return empty stack */
1047 }
1048 /* must have used dXSARGS; list context implied */
1049 0 return; /* assume stack size is correct */
1050  
1051 SV *
1052 build_rv (av)
1053 AV * av
1054  
1055 SV *
1056 build_axaref (arena, rows, columns)
1057 void * arena
1058 int rows
1059 int columns
1060  
1061 SV *
1062 c_export_network (handle)
1063 int handle
1064  
1065 void
1066 c_load_axa (hold, idx, arena, rows, columns)
1067 AV * hold
1068 int idx
1069 void * arena
1070 int rows
1071 int columns
1072 PREINIT:
1073 I32* temp;
1074 PPCODE:
1075 0 temp = PL_markstack_ptr++;
1076 0 c_load_axa(hold, idx, arena, rows, columns);
1077 0 ▶ if (PL_markstack_ptr != temp) {
Branch: 1 branch
BranchTrueFalseTotal
if (PL_markstack_ptr != temp) { 0 0 0
1078 /* truly void, because dXSARGS not invoked */
1079 0 PL_markstack_ptr = temp;
1080 0 XSRETURN_EMPTY; /* return empty stack */
1081 }
1082 /* must have used dXSARGS; list context implied */
1083 0 return; /* assume stack size is correct */
1084  
1085 int
1086 c_import_network (rv)
1087 SV * rv
1088  
1089 double
1090 c_train (handle, input, output)
1091 int handle
1092 SV * input
1093 SV * output
1094  
1095 int
1096 c_new_network (input, hidden, output)
1097 int input
1098 int hidden
1099 int output
1100  
1101 double
1102 c_train_set (handle, set, iterations, mse)
1103 int handle
1104 SV * set
1105 int iterations
1106 double mse
1107  
1108 SV *
1109 c_infer (handle, array_ref)
1110 int handle
1111 SV * array_ref
1112  
« blib/lib/AI/NeuralNet/Simple.pm ↑ Summary