ae2f_docs
MlpTrainXOR.c
Go to the documentation of this file.
1#define ae2f_MAC_BUILD 0
2
3#include "ae2f/Float.h"
4#include <ae2f/Ann/Mlp.h>
5#include <stdio.h>
6#include <math.h>
7
8static void Act(ae2f_float_t* r, ae2f_float_t x) {
9 *r = 1.0 / (1.0 + exp(-x));
10}
11
12static void ActDeriv(ae2f_float_t* r, ae2f_float_t output) {
13 *r = output * (1.0 - output);
14}
15
16static void LossDeriv(ae2f_float_t* r, const ae2f_float_t* output, const ae2f_float_t* target, size_t i, size_t c) {
17 *r = ((output[i] - target[i]) / c);
18}
19
20/** Cross entrophy */
21static void
22LossDerivCROSS(ae2f_float_t* r, const ae2f_float_t* output, const ae2f_float_t* target, size_t i, size_t c) {
23 const ae2f_float_t epsilon = 1e-7; // Small value to prevent division by zero
24 ae2f_float_t o_i = output[i];
25 // Clip output to avoid log(0) or division by zero
26 o_i = o_i < epsilon ? epsilon : (o_i > 1.0 - epsilon ? 1.0 - epsilon : o_i);
27 r[0] = (o_i - target[i]) / (c * o_i * (1.0 - o_i));
28}
29
30const ae2f_float_t inp[4][2] = {
31 {0, 0},
32 {0, 1},
33 {1, 0},
34 {1, 1}
35};
36
37const ae2f_float_t goal_xor[4] = {0, 1, 1, 0};
38
39ae2f_float_t output[1] = { 0.5 };
40ae2f_err_t err[1] = {0, };
41ae2f_AnnMlp* mlp;
42size_t lenv[] = {2, 3, 1};
43
44size_t i, j, k;
45
46int main() {
47 ae2f_AnnMlpMk(err, &mlp, 3
48 , lenv
49 , 0, 0, 0
50 , LossDerivCROSS
51 , 0, 0, 0, 0
52 , 0.6, 0.5
53
54 , 3, 3
55 );
56
57 assert(mlp->m_learningrate != 0);
58 assert(mlp->m_learningrate_bias != 0);
59
60 for(i = 0; i < 2; i++) {
61 mlp->m_bias[i] = ((double)rand() / RAND_MAX) - 0.5;
62 mlp->m_act[i] = Act;
63 mlp->m_actderiv[i] = ActDeriv;
64 for(j = 0; j < 9; j++) {
65 mlp->m_weight[j + i * 9] = ((double)rand() / RAND_MAX) - 0.5;
66 }
67 }
68
69 if(err[0]) {
70 printf("[Error]: %d\n", err[0]);
71 assert(0 && "errval has occurred.");
72 }
73
74 for(j = 0; j < 4; j++) {
75 ae2f_AnnMlpPredict(err, mlp, inp[j], output);
76 assert(!err[0] && "err from predict");
77 printf("%f %f -> %f\n", inp[j][0], inp[j][1], output[0]);
78 }
79
80 for(i = 0; i < 9000; i++) {
81 for(j = 0; j < 4; j++) {
83 err, mlp, inp[j]
84 , &goal_xor[j]);
85
86 assert(!err[0] && "err from TrainAutoStream");
87 }
88 }
89
90 for(j = 0; j < 4; j++) {
91 ae2f_AnnMlpPredict(err, mlp, inp[j], output);
92 assert(!err[0] && "err from predict");
93 printf("%f %f -> %f\n", inp[j][0], inp[j][1], output[0]);
94 }
95
96 ae2f_AnnMlpDel(mlp);
97 return 0;
98}
ae2f_float ae2f_float_t
Definition Float.h:38
ae2f_float_t output[1]
const ae2f_float_t goal_xor[4]
ae2f_AnnMlp_t mlp
const ae2f_float_t inp[4][2]
ae2f_err_t err[1]
Definition MlpTrainXOR.c:40
size_t lenv[]
Definition MlpTrainXOR.c:42
uint8_t ae2f_err_t
Informs that this number represents the error.
Definition errGlob.h:19
#define ae2f_AnnMlpMk
Definition Mlp.h:282
#define ae2f_AnnMlpPredict
Definition Mlp.h:285
#define ae2f_AnnMlpDel
Definition Mlp.h:283
#define ae2f_AnnMlpTrainAuto
Definition Mlp.h:291