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
 structure to hold adaline model parameters More...
 

Macros

#define MAX_ITER   500
 Maximum number of iterations to learn.
 
#define ACCURACY   1e-5
 convergence accuracy \(=1\times10^{-5}\)
 

Functions

struct adaline new_adaline (const int num_features, const double eta)
 Default constructor. More...
 
void delete_adaline (struct adaline *ada)
 delete dynamically allocated memory More...
 
int activation (double x)
 Heaviside activation function
 
char * get_weights_str (struct adaline *ada)
 Operator to print the weights of the model.
 
int predict (struct adaline *ada, const double *x, double *out)
 predict the output of the model for given set of features More...
 
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. More...
 
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. More...
 
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. More...
 
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. More...
 
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. More...
 
int main (int argc, char **argv)
 Main function.
 

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

◆ delete_adaline()

void delete_adaline ( struct adaline ada)

delete dynamically allocated memory

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

◆ 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
172 {
173  double avg_pred_error = 1.f;
174 
175  int iter;
176  for (iter = 0; (iter < MAX_ITER) && (avg_pred_error > ACCURACY); iter++)
177  {
178  avg_pred_error = 0.f;
179 
180  // perform fit for each sample
181  for (int i = 0; i < N; i++)
182  {
183  double err = fit_sample(ada, X[i], y[i]);
184  avg_pred_error += fabs(err);
185  }
186  avg_pred_error /= N;
187 
188  // Print updates every 200th iteration
189  // if (iter % 100 == 0)
190  printf("\tIter %3d: Training weights: %s\tAvg error: %.4f\n", iter,
191  get_weights_str(ada), avg_pred_error);
192  }
193 
194  if (iter < MAX_ITER)
195  printf("Converged after %d iterations.\n", iter);
196  else
197  printf("Did not converged after %d iterations.\n", iter);
198 }
Here is the call graph for this function:

◆ 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
146 {
147  /* output of the model with current weights */
148  int p = predict(ada, x, NULL);
149  int prediction_error = y - p; // error in estimation
150  double correction_factor = ada->eta * prediction_error;
151 
152  /* update each weight, the last weight is the bias term */
153  for (int i = 0; i < ada->num_weights - 1; i++)
154  {
155  ada->weights[i] += correction_factor * x[i];
156  }
157  ada->weights[ada->num_weights - 1] += correction_factor; // update bias
158 
159  return correction_factor;
160 }
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
53 {
54  if (eta <= 0.f || eta >= 1.f)
55  {
56  fprintf(stderr, "learning rate should be > 0 and < 1\n");
57  exit(EXIT_FAILURE);
58  }
59 
60  // additional weight is for the constant bias term
61  int num_weights = num_features + 1;
62  struct adaline ada;
63  ada.eta = eta;
64  ada.num_weights = num_weights;
65  ada.weights = (double *)malloc(num_weights * sizeof(double));
66  if (!ada.weights)
67  {
68  perror("Unable to allocate error for weights!");
69  return ada;
70  }
71 
72  // initialize with random weights in the range [-50, 49]
73  for (int i = 0; i < num_weights; i++) ada.weights[i] = 1.f;
74  // ada.weights[i] = (double)(rand() % 100) - 50);
75 
76  return ada;
77 }

◆ 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
125 {
126  double y = ada->weights[ada->num_weights - 1]; // assign bias value
127 
128  for (int i = 0; i < ada->num_weights - 1; i++) y += x[i] * ada->weights[i];
129 
130  if (out) // if out variable is not NULL
131  *out = y;
132 
133  return activation(y); // quantizer: apply ADALINE threshold function
134 }
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)
207 {
208  struct adaline ada = new_adaline(2, eta); // 2 features
209 
210  const int N = 10; // number of sample points
211  const double saved_X[10][2] = {{0, 1}, {1, -2}, {2, 3}, {3, -1},
212  {4, 1}, {6, -5}, {-7, -3}, {-8, 5},
213  {-9, 2}, {-10, -15}};
214 
215  double **X = (double **)malloc(N * sizeof(double *));
216  const int Y[10] = {1, -1, 1, -1, -1,
217  -1, 1, 1, 1, -1}; // corresponding y-values
218  for (int i = 0; i < N; i++)
219  {
220  X[i] = (double *)saved_X[i];
221  }
222 
223  printf("------- Test 1 -------\n");
224  printf("Model before fit: %s", get_weights_str(&ada));
225 
226  fit(&ada, X, Y, N);
227  printf("Model after fit: %s\n", get_weights_str(&ada));
228 
229  double test_x[] = {5, -3};
230  int pred = predict(&ada, test_x, NULL);
231  printf("Predict for x=(5,-3): % d", pred);
232  assert(pred == -1);
233  printf(" ...passed\n");
234 
235  double test_x2[] = {5, 8};
236  pred = predict(&ada, test_x2, NULL);
237  printf("Predict for x=(5, 8): % d", pred);
238  assert(pred == 1);
239  printf(" ...passed\n");
240 
241  // for (int i = 0; i < N; i++)
242  // free(X[i]);
243  free(X);
244  delete_adaline(&ada);
245 }
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)
255 {
256  struct adaline ada = new_adaline(2, eta); // 2 features
257 
258  const int N = 50; // number of sample points
259 
260  double **X = (double **)malloc(N * sizeof(double *));
261  int *Y = (int *)malloc(N * sizeof(int)); // corresponding y-values
262  for (int i = 0; i < N; i++) X[i] = (double *)malloc(2 * sizeof(double));
263 
264  // generate sample points in the interval
265  // [-range2/100 , (range2-1)/100]
266  int range = 500; // sample points full-range
267  int range2 = range >> 1; // sample points half-range
268  for (int i = 0; i < N; i++)
269  {
270  double x0 = ((rand() % range) - range2) / 100.f;
271  double x1 = ((rand() % range) - range2) / 100.f;
272  X[i][0] = x0;
273  X[i][1] = x1;
274  Y[i] = (x0 + 3. * x1) > -1 ? 1 : -1;
275  }
276 
277  printf("------- Test 2 -------\n");
278  printf("Model before fit: %s", get_weights_str(&ada));
279 
280  fit(&ada, X, Y, N);
281  printf("Model after fit: %s\n", get_weights_str(&ada));
282 
283  int N_test_cases = 5;
284  double test_x[2];
285  for (int i = 0; i < N_test_cases; i++)
286  {
287  double x0 = ((rand() % range) - range2) / 100.f;
288  double x1 = ((rand() % range) - range2) / 100.f;
289 
290  test_x[0] = x0;
291  test_x[1] = x1;
292  int pred = predict(&ada, test_x, NULL);
293  printf("Predict for x=(% 3.2f,% 3.2f): % d", x0, x1, pred);
294 
295  int expected_val = (x0 + 3. * x1) > -1 ? 1 : -1;
296  assert(pred == expected_val);
297  printf(" ...passed\n");
298  }
299 
300  for (int i = 0; i < N; i++) free(X[i]);
301  free(X);
302  free(Y);
303  delete_adaline(&ada);
304 }
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)
318 {
319  struct adaline ada = new_adaline(6, eta); // 2 features
320 
321  const int N = 50; // number of sample points
322 
323  double **X = (double **)malloc(N * sizeof(double *));
324  int *Y = (int *)malloc(N * sizeof(int)); // corresponding y-values
325  for (int i = 0; i < N; i++) X[i] = (double *)malloc(6 * sizeof(double));
326 
327  // generate sample points in the interval
328  // [-range2/100 , (range2-1)/100]
329  int range = 200; // sample points full-range
330  int range2 = range >> 1; // sample points half-range
331  for (int i = 0; i < N; i++)
332  {
333  double x0 = ((rand() % range) - range2) / 100.f;
334  double x1 = ((rand() % range) - range2) / 100.f;
335  double x2 = ((rand() % range) - range2) / 100.f;
336  X[i][0] = x0;
337  X[i][1] = x1;
338  X[i][2] = x2;
339  X[i][3] = x0 * x0;
340  X[i][4] = x1 * x1;
341  X[i][5] = x2 * x2;
342  Y[i] = (x0 * x0 + x1 * x1 + x2 * x2) <= 1 ? 1 : -1;
343  }
344 
345  printf("------- Test 3 -------\n");
346  printf("Model before fit: %s", get_weights_str(&ada));
347 
348  fit(&ada, X, Y, N);
349  printf("Model after fit: %s\n", get_weights_str(&ada));
350 
351  int N_test_cases = 5;
352  double test_x[6];
353  for (int i = 0; i < N_test_cases; i++)
354  {
355  double x0 = ((rand() % range) - range2) / 100.f;
356  double x1 = ((rand() % range) - range2) / 100.f;
357  double x2 = ((rand() % range) - range2) / 100.f;
358  test_x[0] = x0;
359  test_x[1] = x1;
360  test_x[2] = x2;
361  test_x[3] = x0 * x0;
362  test_x[4] = x1 * x1;
363  test_x[5] = x2 * x2;
364  int pred = predict(&ada, test_x, NULL);
365  printf("Predict for x=(% 3.2f,% 3.2f): % d", x0, x1, pred);
366 
367  int expected_val = (x0 * x0 + x1 * x1 + x2 * x2) <= 1 ? 1 : -1;
368  assert(pred == expected_val);
369  printf(" ...passed\n");
370  }
371 
372  for (int i = 0; i < N; i++) free(X[i]);
373  free(X);
374  free(Y);
375  delete_adaline(&ada);
376 }
Here is the call graph for this function:
MAX_ITER
#define MAX_ITER
Maximum number of iterations to learn.
Definition: adaline_learning.c:34
get_weights_str
char * get_weights_str(struct adaline *ada)
Operator to print the weights of the model.
Definition: adaline_learning.c:100
adaline::weights
double * weights
weights of the neural network
Definition: adaline_learning.c:40
delete_adaline
void delete_adaline(struct adaline *ada)
delete dynamically allocated memory
Definition: adaline_learning.c:82
data
Definition: prime_factoriziation.c:25
N
#define N
number of digits of the large number
Definition: sol1.c:109
adaline::eta
double eta
learning rate of the algorithm
Definition: adaline_learning.c:39
predict
int predict(struct adaline *ada, const double *x, double *out)
predict the output of the model for given set of features
Definition: adaline_learning.c:124
new_adaline
struct adaline new_adaline(const int num_features, const double eta)
Default constructor.
Definition: adaline_learning.c:52
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.
Definition: adaline_learning.c:145
activation
int activation(double x)
Heaviside activation function
Definition: adaline_learning.c:95
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.
Definition: adaline_learning.c:171
adaline
structure to hold adaline model parameters
Definition: adaline_learning.c:38
ACCURACY
#define ACCURACY
convergence accuracy
Definition: adaline_learning.c:44
adaline::num_weights
int num_weights
number of weights of the neural network
Definition: adaline_learning.c:41