Post

Coding with Karthik: Perceptron Learning Algorithm in C

Coding with Karthik: Visualizing the Perceptron Learning Algorithm

Remember that blog post? ^

Well, I wanted to do the same thing but in the C Programming Language.

K&R Book

To write the perceptron learning algorithm in C, I had to let go of my comforts. File reading became a task of its own. I spent a couple hours trying to figure out pointers. Hopefully I don’t have memory leaks – I think free()‘d whenever I malloc()‘d. 😀

Below is the code. Enjoy!

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
/*
 * LOGIC:
 * 1. Start with random B, W1, W2,
 * 2. get_misclassified(B, W1, W2)
 * 3. for sample in misclassified:
 *        get values x1, x2, y (y is binary)
 *        if y == 0: y = -1
 *        B = B + y * 1 * LR
 *        W1 = W1 + y * x1 * LR
 *        W2 = W2 + y * x2 * LR
 */

#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>

#define MAX_LINE_LENGTH 100

typedef struct datapoint {
  double x1;
  double x2;
  bool y;
} datapoint;

const double LR = 1; // learning rate
const int STOP_ITER = 10000; // maximum number of epochs run
int dataset_size;

// generate random decimal between -1 and 1
double gen_random_neg1_1() { 
  double r = -1 + 2 * ((float)rand()) / RAND_MAX;
  return r;
}

bool gen_true_false() {
  int i = rand() % 2;

  if (i == 1) {
    return true;
  } else {
    return false;
  }
}

datapoint *get_misclassified(datapoint *dataset, int dataset_len, double b, double w1, double w2, int *pmisclassified_count) {

  datapoint *misclassified_points;
  misclassified_points =
      malloc(dataset_len * sizeof(datapoint)); // maximum the list can go

  *pmisclassified_count = 0;

  for (int i = 0; i < dataset_len; i++) {
    datapoint sample = dataset[i];
    double pred = b + w1 * sample.x1 + w2 * sample.x2;

    if (pred > 0 != sample.y) {
      misclassified_points[*pmisclassified_count] = sample;
      (*pmisclassified_count)++;
    }
  }

  return misclassified_points;
}

int get_file_len(char *filename) {
  FILE *pfile = fopen(filename, "r");
  if (pfile == NULL) {
    printf("No file %s", filename);
    exit(1);
  }

  int lines = 0;

  while (!feof(pfile)) {
    int ch = fgetc(pfile);
    if (ch == '\n') {
      lines++;
    }
  }

  return lines;
}

datapoint *get_dataset(char *filename) {
  FILE *pfile = fopen(filename, "r");
  if (pfile == NULL) {
    printf("No file %s", filename);
    return 0;
  }

  dataset_size = get_file_len(filename);

  int count = 0;

  datapoint *dataset;
  dataset = malloc(dataset_size * sizeof(datapoint));

  char line[MAX_LINE_LENGTH];

  while (fgets(line, MAX_LINE_LENGTH, pfile) != NULL) {
    line[strcspn(line, "\n")] = '\0'; // strip newline
    char *token = strtok(line, ",");
    if (token != NULL) {
      dataset[count].x1 = atof(token);
      token = strtok(NULL, ",");
      if (token != NULL) {
        dataset[count].x2 = atof(token);
        token = strtok(NULL, ",");
        if (token != NULL) {
          dataset[count].y = atoi(token);
          count++;
        }
      }
    }
  }

  fclose(pfile);

  return dataset;
}

int main(int argc, char *argv[]) {
  srand(time(NULL)); // Initialization, should only be called once.

  double b = gen_random_neg1_1();
  double w1 = gen_random_neg1_1();
  double w2 = gen_random_neg1_1();

  datapoint *dataset = get_dataset(argv[1]);

  // get array of misclassified points and the length of the array
  int misclassified_count;
  datapoint *misclassified =
      get_misclassified(dataset, dataset_size, b, w1, w2, &misclassified_count);

  int count = 0; // count number of epochs

  while (misclassified_count > 0) {
    for (int i = 0; i < misclassified_count; i++) {
      // get sample and update weights

      datapoint sample = misclassified[i];
      int multiplier = sample.y ? 1 : -1;

      b = b + multiplier * LR;
      w1 = w1 + multiplier * sample.x1 * LR;
      w2 = w2 + multiplier * sample.x2 * LR;
    }

    free(misclassified);
    misclassified = get_misclassified(dataset, dataset_size, b, w1, w2, &misclassified_count);

    count++;

    if (count > STOP_ITER) {
      break;
    }
  }

  free(dataset);
  free(misclassified);

  printf("FINAL VALUES\n");
  printf("b:  %f\n", b);
  printf("w1: %f\n", w1);
  printf("w2: %f\n", w2);
  printf("Misclassified count %d", misclassified_count);
  printf("\n\n");

  return 0;
}
This post is licensed under CC BY 4.0 by the author.