Algorithms_in_C  1.0.0
Set of algorithms implemented in C.
adaline_learning.c File Reference

Adaptive Linear Neuron (ADALINE) implementation More...

#include <assert.h>
#include <limits.h>
#include <math.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
Include dependency graph for adaline_learning.c:

Data Structures

struct  adaline
 

Macros

#define MAX_ITER   500
 
#define ACCURACY   1e-5
 convergence accuracy \(=1\times10^{-5}\)
 

Functions

struct adaline new_adaline (const int num_features, const double eta)
 
void delete_adaline (struct adaline *ada)
 
int activation (double x)
 
char * get_weights_str (struct adaline *ada)
 
int predict (struct adaline *ada, const double *x, double *out)
 
double fit_sample (struct adaline *ada, const double *x, const int y)
 
void fit (struct adaline *ada, double **X, const int *y, const int N)
 
void test1 (double eta)
 
void test2 (double eta)
 
void test3 (double eta)
 
int main (int argc, char **argv)
 

Detailed Description

Adaptive Linear Neuron (ADALINE) implementation

Author
Krishna Vedala

source ADALINE is one of the first and simplest single layer artificial neural network. The algorithm essentially implements a linear function

\[ f\left(x_0,x_1,x_2,\ldots\right) = \sum_j x_jw_j+\theta \]

where \(x_j\) are the input features of a sample, \(w_j\) are the coefficients of the linear function and \(\theta\) is a constant. If we know the \(w_j\), then for any given set of features, \(y\) can be computed. Computing the \(w_j\) is a supervised learning algorithm wherein a set of features and their corresponding outputs are given and weights are computed using stochastic gradient descent method.

Function Documentation

◆ activation()

int activation ( double  x)

Heaviside activation function

94 { return x > 0 ? 1 : -1; }

◆ delete_adaline()

void delete_adaline ( struct adaline ada)

delete dynamically allocated memory

Parameters
[in]adamodel from which the memory is to be freeed.
82 {
83  if (ada == NULL)
84  return;
85 
86  free(ada->weights);
87 };

◆ fit()

void fit ( struct adaline ada,
double **  X,
const int *  y,
const int  N 
)

Update the weights of the model using supervised learning for an array of vectors.

Parameters
[in]adaadaline model to train
[in]Xarray of feature vector
[in]yknown output value for each feature vector
[in]Nnumber of training samples
171 {
172  double avg_pred_error = 1.f;
173 
174  int iter;
175  for (iter = 0; (iter < MAX_ITER) && (avg_pred_error > ACCURACY); iter++)
176  {
177  avg_pred_error = 0.f;
178 
179  // perform fit for each sample
180  for (int i = 0; i < N; i++)
181  {
182  double err = fit_sample(ada, X[i], y[i]);
183  avg_pred_error += fabs(err);
184  }
185  avg_pred_error /= N;
186 
187  // Print updates every 200th iteration
188  // if (iter % 100 == 0)
189  printf("\tIter %3d: Training weights: %s\tAvg error: %.4f\n", iter,
190  get_weights_str(ada), avg_pred_error);
191  }
192 
193  if (iter < MAX_ITER)
194  printf("Converged after %d iterations.\n", iter);
195  else
196  printf("Did not converged after %d iterations.\n", iter);
197 }

◆ fit_sample()

double fit_sample ( struct adaline ada,
const double *  x,
const int  y 
)

Update the weights of the model using supervised learning for one feature vector

Parameters
[in]adaadaline model to fit
[in]xfeature vector
[in]yknown output value
Returns
correction factor
145 {
146  /* output of the model with current weights */
147  int p = predict(ada, x, NULL);
148  int prediction_error = y - p; // error in estimation
149  double correction_factor = ada->eta * prediction_error;
150 
151  /* update each weight, the last weight is the bias term */
152  for (int i = 0; i < ada->num_weights - 1; i++)
153  {
154  ada->weights[i] += correction_factor * x[i];
155  }
156  ada->weights[ada->num_weights - 1] += correction_factor; // update bias
157 
158  return correction_factor;
159 }
Here is the call graph for this function:

◆ get_weights_str()

char* get_weights_str ( struct adaline ada)

Operator to print the weights of the model

100 {
101  static char out[100]; // static so the value is persistent
102 
103  sprintf(out, "<");
104  for (int i = 0; i < ada->num_weights; i++)
105  {
106  sprintf(out, "%s%.4g", out, ada->weights[i]);
107  if (i < ada->num_weights - 1)
108  sprintf(out, "%s, ", out);
109  }
110  sprintf(out, "%s>", out);
111  return out;
112 }

◆ main()

int main ( int  argc,
char **  argv 
)

Main function

379 {
380  srand(time(NULL)); // initialize random number generator
381 
382  double eta = 0.1; // default value of eta
383  if (argc == 2) // read eta value from commandline argument if present
384  eta = strtof(argv[1], NULL);
385 
386  test1(eta);
387 
388  printf("Press ENTER to continue...\n");
389  getchar();
390 
391  test2(eta);
392 
393  printf("Press ENTER to continue...\n");
394  getchar();
395 
396  test3(eta);
397 
398  return 0;
399 }
Here is the call graph for this function:

◆ new_adaline()

struct adaline new_adaline ( const int  num_features,
const double  eta 
)

Default constructor

Parameters
[in]num_featuresnumber of features present
[in]etalearning rate (optional, default=0.1)
Returns
new adaline model
52 {
53  if (eta <= 0.f || eta >= 1.f)
54  {
55  fprintf(stderr, "learning rate should be > 0 and < 1\n");
56  exit(EXIT_FAILURE);
57  }
58 
59  // additional weight is for the constant bias term
60  int num_weights = num_features + 1;
61  struct adaline ada;
62  ada.eta = eta;
63  ada.num_weights = num_weights;
64  ada.weights = (double *)malloc(num_weights * sizeof(double));
65  if (!ada.weights)
66  {
67  perror("Unable to allocate error for weights!");
68  return ada;
69  }
70 
71  // initialize with random weights in the range [-50, 49]
72  for (int i = 0; i < num_weights; i++) ada.weights[i] = 1.f;
73  // ada.weights[i] = (double)(rand() % 100) - 50);
74 
75  return ada;
76 }

◆ predict()

int predict ( struct adaline ada,
const double *  x,
double *  out 
)

predict the output of the model for given set of features

Parameters
[in]adaadaline model to predict
[in]xinput vector
[out]outoptional argument to return neuron output before applying activation function (NULL to ignore)
Returns
model prediction output
124 {
125  double y = ada->weights[ada->num_weights - 1]; // assign bias value
126 
127  for (int i = 0; i < ada->num_weights - 1; i++) y += x[i] * ada->weights[i];
128 
129  if (out) // if out variable is not NULL
130  *out = y;
131 
132  return activation(y); // quantizer: apply ADALINE threshold function
133 }
Here is the call graph for this function:

◆ test1()

void test1 ( double  eta)

test function to predict points in a 2D coordinate system above the line \(x=y\) as +1 and others as -1. Note that each point is defined by 2 values or 2 features.

Parameters
[in]etalearning rate (optional, default=0.01)
206 {
207  struct adaline ada = new_adaline(2, eta); // 2 features
208 
209  const int N = 10; // number of sample points
210  const double saved_X[10][2] = {{0, 1}, {1, -2}, {2, 3}, {3, -1},
211  {4, 1}, {6, -5}, {-7, -3}, {-8, 5},
212  {-9, 2}, {-10, -15}};
213 
214  double **X = (double **)malloc(N * sizeof(double *));
215  const int Y[10] = {1, -1, 1, -1, -1,
216  -1, 1, 1, 1, -1}; // corresponding y-values
217  for (int i = 0; i < N; i++)
218  {
219  X[i] = (double *)saved_X[i];
220  }
221 
222  printf("------- Test 1 -------\n");
223  printf("Model before fit: %s", get_weights_str(&ada));
224 
225  fit(&ada, X, Y, N);
226  printf("Model after fit: %s\n", get_weights_str(&ada));
227 
228  double test_x[] = {5, -3};
229  int pred = predict(&ada, test_x, NULL);
230  printf("Predict for x=(5,-3): % d", pred);
231  assert(pred == -1);
232  printf(" ...passed\n");
233 
234  double test_x2[] = {5, 8};
235  pred = predict(&ada, test_x2, NULL);
236  printf("Predict for x=(5, 8): % d", pred);
237  assert(pred == 1);
238  printf(" ...passed\n");
239 
240  // for (int i = 0; i < N; i++)
241  // free(X[i]);
242  free(X);
243  delete_adaline(&ada);
244 }
Here is the call graph for this function:

◆ test2()

void test2 ( double  eta)

test function to predict points in a 2D coordinate system above the line \(x+3y=-1\) as +1 and others as -1. Note that each point is defined by 2 values or 2 features. The function will create random sample points for training and test purposes.

Parameters
[in]etalearning rate (optional, default=0.01)
254 {
255  struct adaline ada = new_adaline(2, eta); // 2 features
256 
257  const int N = 50; // number of sample points
258 
259  double **X = (double **)malloc(N * sizeof(double *));
260  int *Y = (int *)malloc(N * sizeof(int)); // corresponding y-values
261  for (int i = 0; i < N; i++) X[i] = (double *)malloc(2 * sizeof(double));
262 
263  // generate sample points in the interval
264  // [-range2/100 , (range2-1)/100]
265  int range = 500; // sample points full-range
266  int range2 = range >> 1; // sample points half-range
267  for (int i = 0; i < N; i++)
268  {
269  double x0 = ((rand() % range) - range2) / 100.f;
270  double x1 = ((rand() % range) - range2) / 100.f;
271  X[i][0] = x0;
272  X[i][1] = x1;
273  Y[i] = (x0 + 3. * x1) > -1 ? 1 : -1;
274  }
275 
276  printf("------- Test 2 -------\n");
277  printf("Model before fit: %s", get_weights_str(&ada));
278 
279  fit(&ada, X, Y, N);
280  printf("Model after fit: %s\n", get_weights_str(&ada));
281 
282  int N_test_cases = 5;
283  double test_x[2];
284  for (int i = 0; i < N_test_cases; i++)
285  {
286  double x0 = ((rand() % range) - range2) / 100.f;
287  double x1 = ((rand() % range) - range2) / 100.f;
288 
289  test_x[0] = x0;
290  test_x[1] = x1;
291  int pred = predict(&ada, test_x, NULL);
292  printf("Predict for x=(% 3.2f,% 3.2f): % d", x0, x1, pred);
293 
294  int expected_val = (x0 + 3. * x1) > -1 ? 1 : -1;
295  assert(pred == expected_val);
296  printf(" ...passed\n");
297  }
298 
299  for (int i = 0; i < N; i++) free(X[i]);
300  free(X);
301  free(Y);
302  delete_adaline(&ada);
303 }
Here is the call graph for this function:

◆ test3()

void test3 ( double  eta)

test function to predict points in a 3D coordinate system lying within the sphere of radius 1 and centre at origin as +1 and others as -1. Note that each point is defined by 3 values but we use 6 features. The function will create random sample points for training and test purposes. The sphere centred at origin and radius 1 is defined as: \(x^2+y^2+z^2=r^2=1\) and if the \(r^2<1\), point lies within the sphere else, outside.

Parameters
[in]etalearning rate (optional, default=0.01)
317 {
318  struct adaline ada = new_adaline(6, eta); // 2 features
319 
320  const int N = 50; // number of sample points
321 
322  double **X = (double **)malloc(N * sizeof(double *));
323  int *Y = (int *)malloc(N * sizeof(int)); // corresponding y-values
324  for (int i = 0; i < N; i++) X[i] = (double *)malloc(6 * sizeof(double));
325 
326  // generate sample points in the interval
327  // [-range2/100 , (range2-1)/100]
328  int range = 200; // sample points full-range
329  int range2 = range >> 1; // sample points half-range
330  for (int i = 0; i < N; i++)
331  {
332  double x0 = ((rand() % range) - range2) / 100.f;
333  double x1 = ((rand() % range) - range2) / 100.f;
334  double x2 = ((rand() % range) - range2) / 100.f;
335  X[i][0] = x0;
336  X[i][1] = x1;
337  X[i][2] = x2;
338  X[i][3] = x0 * x0;
339  X[i][4] = x1 * x1;
340  X[i][5] = x2 * x2;
341  Y[i] = (x0 * x0 + x1 * x1 + x2 * x2) <= 1 ? 1 : -1;
342  }
343 
344  printf("------- Test 3 -------\n");
345  printf("Model before fit: %s", get_weights_str(&ada));
346 
347  fit(&ada, X, Y, N);
348  printf("Model after fit: %s\n", get_weights_str(&ada));
349 
350  int N_test_cases = 5;
351  double test_x[6];
352  for (int i = 0; i < N_test_cases; i++)
353  {
354  double x0 = ((rand() % range) - range2) / 100.f;
355  double x1 = ((rand() % range) - range2) / 100.f;
356  double x2 = ((rand() % range) - range2) / 100.f;
357  test_x[0] = x0;
358  test_x[1] = x1;
359  test_x[2] = x2;
360  test_x[3] = x0 * x0;
361  test_x[4] = x1 * x1;
362  test_x[5] = x2 * x2;
363  int pred = predict(&ada, test_x, NULL);
364  printf("Predict for x=(% 3.2f,% 3.2f): % d", x0, x1, pred);
365 
366  int expected_val = (x0 * x0 + x1 * x1 + x2 * x2) <= 1 ? 1 : -1;
367  assert(pred == expected_val);
368  printf(" ...passed\n");
369  }
370 
371  for (int i = 0; i < N; i++) free(X[i]);
372  free(X);
373  free(Y);
374  delete_adaline(&ada);
375 }
Here is the call graph for this function:
get_weights_str
char * get_weights_str(struct adaline *ada)
Definition: adaline_learning.c:99
adaline::weights
double * weights
weights of the neural network
Definition: adaline_learning.c:39
delete_adaline
void delete_adaline(struct adaline *ada)
Definition: adaline_learning.c:81
data
Definition: prime_factoriziation.c:25
N
#define N
Definition: sol1.c:109
adaline::eta
double eta
learning rate of the algorithm
Definition: adaline_learning.c:38
predict
int predict(struct adaline *ada, const double *x, double *out)
Definition: adaline_learning.c:123
new_adaline
struct adaline new_adaline(const int num_features, const double eta)
Definition: adaline_learning.c:51
test3
void test3(double eta)
Definition: adaline_learning.c:316
fit_sample
double fit_sample(struct adaline *ada, const double *x, const int y)
Definition: adaline_learning.c:144
activation
int activation(double x)
Definition: adaline_learning.c:94
test1
void test1(double eta)
Definition: adaline_learning.c:205
test2
void test2(double eta)
Definition: adaline_learning.c:253
fit
void fit(struct adaline *ada, double **X, const int *y, const int N)
Definition: adaline_learning.c:170
adaline
Definition: adaline_learning.c:37
ACCURACY
#define ACCURACY
convergence accuracy
Definition: adaline_learning.c:43
adaline::num_weights
int num_weights
number of weights of the neural network
Definition: adaline_learning.c:40