-
-
Notifications
You must be signed in to change notification settings - Fork 1
/
ann.c
1462 lines (1199 loc) · 38.6 KB
/
ann.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**********************************************************************************/
/* Copyright (c) 2023 Mark Seminatore */
/* All rights reserved. */
/* */
/* Permission is hereby granted, free of charge, to any person obtaining a copy */
/* of this software and associated documentation files(the "Software"), to deal */
/* in the Software without restriction, including without limitation the rights */
/* to use, copy, modify, merge, publish, distribute, sublicense, and / or sell */
/* copies of the Software, and to permit persons to whom the Software is */
/* furnished to do so, subject to the following conditions: */
/* */
/* The above copyright notice and this permission notice shall be included in all */
/* copies or substantial portions of the Software. */
/* */
/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR */
/* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, */
/* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE */
/* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER */
/* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, */
/* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE */
/* SOFTWARE. */
/**********************************************************************************/
#ifdef _WIN32
# define _CRT_SECURE_NO_WARNINGS
#endif
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <stdarg.h>
#include <assert.h>
#include <time.h>
#include "ann.h"
//------------------------------------------------
// define the text and binary file format versions
//------------------------------------------------
static const int ANN_TEXT_FORMAT_VERSION = 1;
static const int ANN_BINARY_FORMAT_VERSION = 1;
#if defined(_WIN32) && !defined(_WIN64)
# define R_MIN -1
# define R_MAX 1
#else
# define R_MIN -1.0
# define R_MAX 1.0
#endif
//-----------------------------------------------
// optimizer printable names
//-----------------------------------------------
static const char *optimizers[] = {
"Stochastic Gradient Descent",
"Stochastic Gradient Descent with decay",
"Adaptive Stochastic Gradient Descent",
"SGD with momentum",
"RMSPROP",
"ADAGRAD",
"Adam",
"SGD"
};
//-----------------------------------------------
// loss function printable anmes
//-----------------------------------------------
static const char *loss_types[] = {
"Mean Squared Error",
"Categorical Cross-Entropy",
"Mean Squared Error"
};
//-----------------------------------------------
// default lib output function
//-----------------------------------------------
static void ann_puts(const char *s)
{
fputs(s, stdout);
}
//-----------------------------------------------
// formatted output
//-----------------------------------------------
static void ann_printf(PNetwork pnet, const char *format, ...)
{
char buf[DEFAULT_SMALL_BUF_SIZE];
va_list valist;
va_start(valist, format);
vsprintf(buf, format, valist);
va_end(valist);
pnet->print_func(buf);
}
//------------------------------
// null activation
//------------------------------
static real no_activation(real x) { return x; }
//------------------------------
// compute the sigmoid activation
//------------------------------
static real sigmoid(real x)
{
return (real)(1.0 / (1.0 + exp(-x)));
}
//------------------------------
// compute the ReLU activation
//------------------------------
static real relu(real x)
{
return (real)fmax(0.0, x);
}
//------------------------------
// compute the leaky ReLU activation
//------------------------------
static real leaky_relu(real x)
{
return (real)fmax(0.01 * x, x);
}
//------------------------------
// compute the tanh activation
//------------------------------
static real ann_tanh(real x)
{
return (real)tanh(x);
}
//---------------------------------
// compute the softsign activation
//--------------------------------
static real softsign(real x)
{
return (real)(x / (1.0 + fabs(x)));
}
//------------------------------
// compute the softmax
//------------------------------
static void softmax(PNetwork pnet)
{
real one_over_sum = 0.0;
real sum = 0.0;
// find the sum of the output node values, excluding the bias node
int output_layer = pnet->layer_count - 1;
int node_count = pnet->layers[output_layer].node_count;
//tensor_exp(pnet->layers[output_layer].t_values);
//one_over_sum = (real)1.0 / (tensor_sum(pnet->layers[output_layer].t_values) - 1.0);
//tensor_mul_scalar(pnet->layers[output_layer].t_values, one_over_sum);
for (int node = 0; node < node_count; node++)
{
sum += (real)exp(pnet->layers[output_layer].t_values->values[node]);
}
for (int node = 0; node < node_count; node++)
{
pnet->layers[output_layer].t_values->values[node] = (real)(exp(pnet->layers[output_layer].t_values->values[node]) / sum);
}
}
//------------------------------
// return rand num [min..max)
//------------------------------
static real get_rand(real min, real max)
{
real r = (real)rand() / (real)RAND_MAX;
real scale = max - min;
r *= scale;
r += min;
return r;
}
//------------------------------
// print the network
//------------------------------
static void print_network(PNetwork pnet)
{
if (!pnet)
return;
puts("");
// print each layer
for (int layer = 0; layer < pnet->layer_count; layer++)
{
// ann_printf(pnet, "\nLayer %d\n"
// "--------\n", layer);
putchar('[');
// print nodes in the layer
for (int node = 0; node < pnet->layers[layer].node_count; node++)
{
// ann_printf(pnet, "(%3.2g, ", pnet->layers[layer].nodes[node].value);
if (layer > 0)
{
for (int prev_node = 0; prev_node < pnet->layers[layer - 1].node_count; prev_node++)
{
// ann_printf(pnet, "%3.2g, ", pnet->layers[layer].nodes[node].weights[prev_node]);
}
}
}
puts("]");
}
}
//------------------------------
// initialize the weights
//------------------------------
static void init_weights(PNetwork pnet)
{
if (!pnet)
return;
for (int layer = 1; layer < pnet->layer_count; layer++)
{
// output layers don't have weights
//if (pnet->layers[layer].layer_type == LAYER_OUTPUT)
// continue;
// int weight_count = pnet->layers[layer - 1].node_count;
// int node_count = pnet->layers[layer].node_count;
// TODO - glorot uniform limits
// real limit = (real)sqrt(6.0 / (weight_count + node_count));
// real limit = (real)sqrt(1.0 / (weight_count));
tensor_random_uniform(pnet->layers[layer - 1].t_bias, (real)-pnet->weight_limit, (real)pnet->weight_limit);
tensor_random_uniform(pnet->layers[layer - 1].t_weights, (real)-pnet->weight_limit, (real)pnet->weight_limit);
}
pnet->weights_set = 1;
}
//--------------------------------
// print nodes in the output layer
//--------------------------------
void print_outputs(PNetwork pnet)
{
if (!pnet)
return;
puts("");
PLayer pLayer = &pnet->layers[0];
pLayer = &pnet->layers[pnet->layer_count - 1];
tensor_print(pLayer->t_values);
}
//--------------------------------
// compute the mean squared error
//--------------------------------
static real compute_ms_error(PNetwork pnet, PTensor outputs)
{
// get the output layer
PLayer poutput_layer = &pnet->layers[pnet->layer_count - 1];
assert(poutput_layer->layer_type == LAYER_OUTPUT);
real mse = (real)0.0, diff;
for (int i = 0; i < poutput_layer->node_count; i++)
{
diff = outputs->values[i] - poutput_layer->t_values->values[i];
mse += diff * diff;
}
return mse;
}
//---------------------------------------------
// compute the categorical cross entropy error
//---------------------------------------------
static real compute_cross_entropy(PNetwork pnet, PTensor outputs)
{
// get the output layer
PLayer poutput_layer = &pnet->layers[pnet->layer_count - 1];
assert(poutput_layer->layer_type == LAYER_OUTPUT);
real xe = (real)0.0;
for (int i = 0; i < poutput_layer->node_count; i++)
{
xe += (real)(outputs->values[i] * log(poutput_layer->t_values->values[i]));
}
return -xe;
}
//------------------------------
// forward evaluate the network
//------------------------------
static void eval_network(PNetwork pnet)
{
if (!pnet)
return;
// loop over the non-output layers
for (int layer = 0; layer < pnet->layer_count - 1; layer++)
{
// y = Wx + b
tensor_matvec(Tensor_NoTranspose, (real)1.0, pnet->layers[layer].t_weights, (real)0.0, pnet->layers[layer].t_values, pnet->layers[layer + 1].t_values);
tensor_add(pnet->layers[layer + 1].t_values, pnet->layers[layer].t_bias);
// apply activation function to values
for (int i = 0; i < pnet->layers[layer + 1].node_count; i++)
{
pnet->layers[layer + 1].t_values->values[i] = pnet->layers[layer + 1].activation_func(pnet->layers[layer + 1].t_values->values[i]);
}
}
// apply softmax on output, if requested
if (pnet->layers[pnet->layer_count - 1].activation == ACTIVATION_SOFTMAX)
softmax(pnet);
}
//-------------------------------------------
// back propagate output error to prev layer
//-------------------------------------------
static void back_propagate_output(PNetwork pnet, PLayer layer, PLayer prev_layer, PTensor outputs)
{
//-------------------------------
// output layer back-propagation
//-------------------------------
// compute dL_dy = (r - y)
tensor_axpby(1.0, outputs, -1.0, layer->t_values);
// bias = bias + n * dL_dy
tensor_axpy(pnet->learning_rate, layer->t_values, prev_layer->t_bias);
// gradient += dL_dy * z
tensor_outer((real)1.0, layer->t_values, prev_layer->t_values, prev_layer->t_gradients);
// dL_dz = weights.T * dL_dy
tensor_matvec(Tensor_Transpose, (real)1.0, prev_layer->t_weights, (real)0.0, layer->t_values, prev_layer->t_dl_dz);
}
//-------------------------------------------
// propagate back for sigmoid layers
//-------------------------------------------
static void back_propagate_sigmoid(PNetwork pnet, PLayer layer, PLayer prev_layer)
{
//
// gradient = dl_dz * z * (1 - z) * x = dl_dz_zomz * x
//
// dl_dz = dl_dz * z
tensor_mul(layer->t_dl_dz, layer->t_values);
// z = z ^2
tensor_square(layer->t_values);
// z = z * dl_dz
tensor_mul(layer->t_values, layer->t_dl_dz);
// dl_dz = dl_dz - dl_dz * z^2
tensor_sub(layer->t_dl_dz, layer->t_values);
// bias = bias + n * dL_dz
tensor_axpy(pnet->learning_rate, layer->t_dl_dz, prev_layer->t_bias);
// gradient += dl_dz * x
tensor_outer((real)1.0, layer->t_dl_dz, prev_layer->t_values, prev_layer->t_gradients);
// dL_dz = weights.T * dL_dy
tensor_matvec(Tensor_Transpose, (real)1.0, prev_layer->t_weights, (real)0.0, layer->t_dl_dz, prev_layer->t_dl_dz);
}
//-------------------------------------------
// propagate back for RELU layers
//-------------------------------------------
static void back_propagate_relu(PNetwork pnet, PLayer layer, PLayer prev_layer)
{
//
// gradient = dl_dz * d * x, where d is derivative of RELU(x) which is 0 or 1
//
// x = d * x
tensor_heaviside(layer->t_values);
// dl_dz = dl_dz * x
tensor_mul(layer->t_dl_dz, layer->t_values);
// bias = bias + n * dl_dz
tensor_axpy(pnet->learning_rate, layer->t_dl_dz, prev_layer->t_bias);
// gradient += dl_dz * d * x
tensor_outer((real)1.0, layer->t_dl_dz, prev_layer->t_values, prev_layer->t_gradients);
// dl_dz = weights.T * dl_dy ??? is that right?
tensor_matvec(Tensor_Transpose, (real)1.0, prev_layer->t_weights, (real)0.0, layer->t_dl_dz, prev_layer->t_dl_dz);
}
//-------------------------------------------
// compute the gradients via back propagation
//-------------------------------------------
static void back_propagate(PNetwork pnet, PTensor outputs)
{
// for each node in the output layer, excluding output layer bias node
int output_layer = pnet->layer_count - 1;
back_propagate_output(pnet, &pnet->layers[output_layer], &pnet->layers[output_layer - 1], outputs);
//-------------------------------
// hidden layer back-propagation
// excluding the input layer
//-------------------------------
for (int layer = output_layer - 1; layer > 0; layer--)
{
pnet->layers[layer].back_prop_func(pnet, &pnet->layers[layer], &pnet->layers[layer - 1]);
}
}
//-------------------------------------------------
// train the network over a single input/output set
//-------------------------------------------------
static real train_pass_network(PNetwork pnet, PTensor inputs, PTensor outputs)
{
if (!pnet || !inputs || !outputs)
return 0.0;
assert(pnet->layers[0].layer_type == LAYER_INPUT);
assert(pnet->layers[pnet->layer_count - 1].layer_type == LAYER_OUTPUT);
// set the input values on the network
int node_count = pnet->layers[0].node_count;
PLayer pLayer = &pnet->layers[0];
for (int node = 0; node < node_count; node++)
{
pLayer->t_values->values[node] = inputs->values[node];
}
// forward evaluate the network
eval_network(pnet);
// compute the Loss function
real loss = pnet->loss_func(pnet, outputs);
// back propagate error through network to compute gradients
back_propagate(pnet, outputs);
return loss;
}
//-----------------------------------------------
// shuffle the indices
// https://en.wikipedia.org/wiki/Fisher–Yates_shuffle
//-----------------------------------------------
static void shuffle_indices(int *input_indices, int count)
{
// Knuth's algorithm to shuffle an array a of n elements (indices 0..n-1):
for (int i = 0; i < count - 2; i++)
{
int j = i + (rand() % (count - i));
int val = input_indices[i];
input_indices[i] = input_indices[j];
input_indices[j] = val;
}
}
//-----------------------------------------------
// null optimization
//-----------------------------------------------
static void optimize_none(PNetwork pnet)
{
// do nothing!
}
//-----------------------------------------------
// SG with decaying learning rate
//-----------------------------------------------
static void optimize_decay(PNetwork pnet, real loss)
{
pnet->learning_rate *= (real)DEFAULT_LEARNING_DECAY;
}
//-----------------------------------------------
// adaptive learning rate
//-----------------------------------------------
static void optimize_adapt(PNetwork pnet, real loss)
{
// adapt the learning rate
optimize_decay(pnet, loss);
real lastMSE = 0.0;
// average the last 4 learning rates
for (int i = 0; i < DEFAULT_MSE_AVG; i++)
{
lastMSE += pnet->lastMSE[i];
}
lastMSE /= DEFAULT_MSE_AVG;
if (lastMSE > 0.0)
{
if (loss < lastMSE)
{
pnet->learning_rate += (real)DEFAULT_LEARN_ADD;
// don't let learning rate go above 1
if (pnet->learning_rate > 1.0)
pnet->learning_rate = 1.0;
}
else
{
pnet->learning_rate -= (real)DEFAULT_LEARN_SUB * pnet->learning_rate;
// don't let rate go below zero
if (pnet->learning_rate <= 0.0)
assert(0);
}
}
int index = (pnet->mseCounter++) & (DEFAULT_MSE_AVG - 1);
pnet->lastMSE[index] = loss;
}
//--------------------------------------------------------
// Stochastic Gradient Descent (SGD)
//
// update the weights based on gradients
//--------------------------------------------------------
static void optimize_sgd(PNetwork pnet)
{
for (int layer = 0; layer < pnet->layer_count - 1; layer++)
{
// W = W + n * gradients
tensor_axpy(pnet->learning_rate, pnet->layers[layer].t_gradients, pnet->layers[layer].t_weights);
}
}
//-----------------------------------------------
// Gradient descent with momentum
//-----------------------------------------------
static void optimize_momentum(PNetwork pnet)
{
real beta = (real)0.9, one_minus_beta = (real)0.1;
for (int layer = 0; layer < pnet->layer_count - 1; layer++)
{
// momentum = beta * m + one_minus_beta * gradients
tensor_axpby(one_minus_beta, pnet->layers[layer].t_gradients, beta, pnet->layers[layer].t_m);
// W = W + n * m
tensor_axpy(pnet->learning_rate, pnet->layers[layer].t_m, pnet->layers[layer].t_weights);
}
}
//-----------------------------------------------
// Adaptive gradient descent
//-----------------------------------------------
static void optimize_adagrad(PNetwork pnet)
{
}
//-----------------------------------------------
// Gradient descent with adaptive learning
//-----------------------------------------------
static void optimize_rmsprop(PNetwork pnet)
{
//real beta = (real)0.9, one_minus_beta = (real)0.1;
//real epsilon = (real)1e-6;
//real v, gradient;
//// for each layer after input
//for (int layer = 1; layer < pnet->layer_count; layer++)
//{
// // for each node in the layer
// int node_count = pnet->layers[layer].node_count;
// for (int node = 1; node < node_count; node++)
// {
// // for each node in previous layer
// int prev_node_count = pnet->layers[layer - 1].node_count;
// for (int prev_node = 0; prev_node < prev_node_count; prev_node++)
// {
// // update the weights by the change
// gradient = pnet->layers[layer].nodes[node].gradients[prev_node];
// v = beta * pnet->layers[layer].nodes[node].v[prev_node] + one_minus_beta * gradient * gradient;
// pnet->layers[layer].nodes[node].v[prev_node] = v;
// pnet->layers[layer].nodes[node].weights[prev_node] += pnet->learning_rate * gradient / (real)(sqrt(v) + epsilon);
// }
// }
//}
}
//-----------------------------------------------
// Adaptive moment estimation
//-----------------------------------------------
static void optimize_adam(PNetwork pnet)
{
//real beta1 = (real)0.9, one_minus_beta1 = (real)0.1;
//real beta2 = (real)0.999, one_minus_beta2 = (real)0.001;
//real epsilon = (real)1e-8;
//real m, v, mhat, vhat, gradient;
//pnet->train_iteration++;
//real one_minus_beta1_t = (real)1.0 / (real)(1.0 - pow(beta1, pnet->train_iteration));
//real one_minus_beta2_t = (real)1.0 / (real)(1.0 - pow(beta2, pnet->train_iteration));
//// for each layer after input
//for (int layer = 1; layer < pnet->layer_count; layer++)
//{
// // for each node in the layer
// int node_count = pnet->layers[layer].node_count;
// for (int node = 1; node < node_count; node++)
// {
// // for each node in previous layer
// int prev_node_count = pnet->layers[layer - 1].node_count;
// for (int prev_node = 0; prev_node < prev_node_count; prev_node++)
// {
// // update the weights by the change
// gradient = pnet->layers[layer].nodes[node].gradients[prev_node];
// m = beta1 * pnet->layers[layer].nodes[node].m[prev_node] + one_minus_beta1 * gradient;
// v = beta2 * pnet->layers[layer].nodes[node].v[prev_node] + one_minus_beta2 * gradient * gradient;
// mhat = m * one_minus_beta1_t;
// vhat = v * one_minus_beta2_t;
// pnet->layers[layer].nodes[node].m[prev_node] = m;
// pnet->layers[layer].nodes[node].v[prev_node] = v;
// pnet->layers[layer].nodes[node].weights[prev_node] += pnet->learning_rate * mhat / (real)(sqrt(vhat) + epsilon);
// }
// }
//}
}
//[]---------------------------------------------[]
// Public ANN library interfaces
//[]---------------------------------------------[]
//------------------------------
// add a new layer to the network
//------------------------------
int ann_add_layer(PNetwork pnet, int node_count, Layer_type layer_type, Activation_type activation_type)
{
if (!pnet)
return ERR_FAIL;
// check whether we've run out of layers
pnet->layer_count++;
if (pnet->layer_count > pnet->layer_size)
{
// need to allocate more layers
pnet->layer_size <<= 1;
PLayer layer = realloc(pnet->layers, pnet->layer_size * (sizeof(Layer)));
if (NULL == layer)
return ERR_FAIL;
pnet->layers = layer;
}
int cur_layer = pnet->layer_count - 1;
pnet->layers[cur_layer].layer_type = layer_type;
pnet->layers[cur_layer].activation = activation_type;
pnet->layers[cur_layer].back_prop_func = NULL;
switch (activation_type)
{
case ACTIVATION_SIGMOID:
pnet->layers[cur_layer].activation_func = sigmoid;
pnet->layers[cur_layer].back_prop_func = back_propagate_sigmoid;
break;
case ACTIVATION_RELU:
pnet->layers[cur_layer].activation_func = relu;
pnet->layers[cur_layer].back_prop_func = back_propagate_relu;
break;
case ACTIVATION_LEAKY_RELU:
pnet->layers[cur_layer].activation_func = leaky_relu;
break;
case ACTIVATION_TANH:
pnet->layers[cur_layer].activation_func = ann_tanh;
break;
case ACTIVATION_SOFTSIGN:
pnet->layers[cur_layer].activation_func = softsign;
break;
case ACTIVATION_NULL:
pnet->layers[cur_layer].activation_func = no_activation;
break;
case ACTIVATION_SOFTMAX:
pnet->layers[cur_layer].activation_func = no_activation;
// handled after full network is evaluated
break;
default:
assert(0);
break;
}
//--------------------
// allocate the nodes
//--------------------
// create the node values tensor
pnet->layers[cur_layer].t_values = tensor_zeros(1, node_count);
pnet->layers[cur_layer].node_count = node_count;
// create the tensors
if (cur_layer > 0)
{
assert(pnet->layers[cur_layer - 1].t_weights == NULL);
pnet->layers[cur_layer - 1].t_weights = tensor_zeros(node_count, pnet->layers[cur_layer - 1].node_count);
pnet->layers[cur_layer - 1].t_v = tensor_zeros(node_count, pnet->layers[cur_layer - 1].node_count);
pnet->layers[cur_layer - 1].t_m = tensor_zeros(node_count, pnet->layers[cur_layer - 1].node_count);
pnet->layers[cur_layer - 1].t_gradients = tensor_zeros(node_count, pnet->layers[cur_layer - 1].node_count);
pnet->layers[cur_layer - 1].t_dl_dz = tensor_zeros(1, pnet->layers[cur_layer - 1].node_count);
pnet->layers[cur_layer - 1].t_bias = tensor_zeros(1, node_count);
}
return ERR_OK;
}
//------------------------------
// make a new network
//------------------------------
PNetwork ann_make_network(Optimizer_type opt, Loss_type loss_type)
{
PNetwork pnet = malloc(sizeof(Network));
if (NULL == pnet)
return NULL;
// set default values
pnet->layer_size = DEFAULT_LAYERS;
pnet->layers = malloc(pnet->layer_size * (sizeof(Layer)));
if (NULL == pnet->layers)
{
free(pnet);
return NULL;
}
pnet->layer_count = 0;
pnet->learning_rate = (real)DEFAULT_LEARNING_RATE;
pnet->weights_set = 0;
pnet->convergence_epsilon = (real)DEFAULT_CONVERGENCE;
pnet->mseCounter = 0;
pnet->dbg = NULL;
pnet->weight_limit = R_MAX;
pnet->init_bias = (real)1.0;
for (int i = 0; i < pnet->layer_size; i++)
{
pnet->layers[i].t_m = NULL;
pnet->layers[i].t_v = NULL;
pnet->layers[i].t_values = NULL;
pnet->layers[i].t_weights = NULL;
pnet->layers[i].t_gradients = NULL;
pnet->layers[i].t_dl_dz = NULL;
pnet->layers[i].t_bias = NULL;
}
for (int i = 0; i < DEFAULT_MSE_AVG; i++)
{
pnet->lastMSE[i] = (real)0.0;
}
ann_set_loss_function(pnet, loss_type);
pnet->epochLimit = 10000;
pnet->train_iteration = 0;
pnet->batchSize = DEFAULT_BATCH_SIZE;
pnet->print_func = ann_puts;
pnet->optimizer = opt;
switch(opt)
{
case OPT_ADAM:
pnet->optimize_func = optimize_adam;
pnet->learning_rate = (real)0.001;
break;
case OPT_ADAPT:
pnet->optimize_func = optimize_sgd;
break;
case OPT_SGD_WITH_DECAY:
pnet->optimize_func = optimize_sgd;
break;
case OPT_MOMENTUM:
pnet->optimize_func = optimize_momentum;
pnet->learning_rate = (real)0.01;
break;
case OPT_RMSPROP:
pnet->optimize_func = optimize_rmsprop;
pnet->learning_rate = (real)0.001;
break;
default:
case OPT_SGD:
pnet->optimize_func = optimize_sgd;
}
return pnet;
}
//-----------------------------------------------
// Train the network for a set of inputs/outputs
//-----------------------------------------------
real ann_train_network(PNetwork pnet, PTensor inputs, PTensor outputs, int rows)
{
if (!pnet)
return 0.0;
// ensure batch size is appropriate
if (rows < 5000)
pnet->batchSize = 1;
ann_printf(pnet, "\nTraining ANN\n"
"------------\n");
ann_print_props(pnet);
ann_printf(pnet, " Training size: %u rows\n\n", rows);
time_t time_start = time(NULL);
pnet->train_iteration = 0;
// initialize weights to random values if not already initialized
init_weights(pnet);
int converged = 0;
real loss;
unsigned epoch = 0;
unsigned correct = 0;
int row;
// create indices for shuffling the inputs and outputs
int *input_indices = alloca(rows * sizeof(int));
for (int i = 0; i < rows; i++)
{
input_indices[i] = i;
}
int inc = max(1, rows / 20);
int input_node_count = (pnet->layers[0].node_count);
int output_node_count = (pnet->layers[pnet->layer_count - 1].node_count);
// validation data
//PTensor x_valid = tensor_slice_rows(inputs, 50000);
//PTensor y_valid = tensor_slice_rows(outputs, 50000);
// tensors to hold input/output batches
//PTensor input_batch = tensor_create(pnet->batchSize, input_node_count);
//PTensor output_batch = tensor_create(pnet->batchSize, output_node_count);
PTensor input_batch = tensor_create(1, input_node_count);
PTensor output_batch = tensor_create(1, output_node_count);
int batch_count = rows / pnet->batchSize;
// train over epochs until done
while (!converged)
{
// re-shuffle the indices for this epoch
shuffle_indices(input_indices, rows);
// iterate over all sets of inputs in this epoch/minibatch
ann_printf(pnet, "Epoch %u/%u\n[", ++epoch, pnet->epochLimit);
loss = (real)0.0;
// iterate over all batches
for (int batch = 0; batch < batch_count; batch++)
{
// zero the gradients
for (int layer = 0; layer < pnet->layer_count - 1; layer++)
{
tensor_fill(pnet->layers[layer].t_gradients, (real)0.0);
}
loss = (real)0.0;
for (unsigned batch_index = 0; batch_index < pnet->batchSize; batch_index++)
{
row = batch * pnet->batchSize + batch_index;
real *ins = inputs->values + input_indices[row] * input_node_count;
real *outs = outputs->values + input_indices[row] * output_node_count;
memcpy(input_batch->values, inputs->values + input_indices[row] * input_node_count, input_node_count * sizeof(real));
memcpy(output_batch->values, outputs->values + input_indices[row] * output_node_count, output_node_count * sizeof(real));
loss += train_pass_network(pnet, input_batch, output_batch);
if (row % inc == 0)
{
putchar('=');
}
}
// average loss over batch-size
loss /= (real)pnet->batchSize;
// update weights based on batched gradients
// using the chosen optimization function
pnet->optimize_func(pnet);
}
ann_printf(pnet, "] - loss: %3.2g - LR: %3.2g\n", loss, pnet->learning_rate);
// optimize learning once per epoch
if (pnet->optimizer == OPT_SGD_WITH_DECAY || pnet->optimizer == OPT_MOMENTUM)
optimize_decay(pnet, loss);
else if (pnet->optimizer == OPT_ADAPT)
optimize_adapt(pnet, loss);
if (loss < pnet->convergence_epsilon)
{
ann_printf(pnet, "Network converged with loss: %3.2g out of %3.2g\n", loss, pnet->convergence_epsilon);
converged = 1;
}
// check for no convergence
if (epoch >= pnet->epochLimit)
{
converged = 1;
}
}
// free up batch tensors
tensor_free(input_batch);
tensor_free(output_batch);
//tensor_free(x_valid);
//tensor_free(y_valid);
time_t time_end = time(NULL);
double diff_t = (double)(time_end - time_start);
double per_step = 1000.0 * diff_t / (rows * epoch);
ann_printf(pnet, "\nTraining time: %f seconds, %f ms/step\n", diff_t, per_step);
return loss;
}
//------------------------------
// evaluate the accuracy
//------------------------------
real ann_evaluate_accuracy(PNetwork pnet, PTensor inputs, PTensor outputs)
{
int correct = 0;
if (!pnet || !inputs || !outputs)
{
return -1.0;
}
int classes = outputs->cols;
real *pred = alloca(classes * sizeof(real));
int pred_class, act_class;
for (int i = 0; i < inputs->rows; i++)
{
ann_predict(pnet, &inputs->values[i * inputs->cols], pred);
pred_class = ann_class_prediction(pred, classes);
act_class = ann_class_prediction(&outputs->values[i * outputs->cols], classes);
if (pred_class == act_class)
correct++;
}
return (real)correct / inputs->rows;
}
//------------------------------------
// predict class from onehot vector
//------------------------------------
int ann_class_prediction(real *outputs, int classes)
{
int class = -1;
real prob = -1.0;
for (int i = 0; i < classes; i++)
{
if (outputs[i] > prob)
{
prob = outputs[i];
class = i;
}
}
return class;
}
//------------------------------