dooooooduo

CI_ASS2_Single Neuron Classification_C

Jan 2nd, 2017
171
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.72 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <time.h>
  4.  
  5. // from http://stackoverflow.com/a/686373
  6. float rand_weight (float min, float max) {
  7.     return min + ((float) rand()) / ((float) (RAND_MAX / (max - min)));
  8. }
  9.  
  10. int main() {
  11.  
  12.     srand(time(NULL));
  13.  
  14.     float sets[1000][3];
  15.     float weights[3] = {
  16.         rand_weight(-.001, .001),
  17.         rand_weight(-.001, .001),
  18.         rand_weight(-.001, .001)
  19.     };
  20.  
  21.     float learning_rate = .001;
  22.  
  23.     float p0, p1;
  24.     char desired_out[2];
  25.     int count = 0;
  26.     while (1) {
  27.         scanf("%f,%f,%s\n", &p0, &p1, desired_out);
  28.         if (p0 == 0 && p1 == 0 && desired_out[0] == '0') break;
  29.        
  30.         sets[count][0] = p0;
  31.         sets[count][1] = p1;
  32.         sets[count][2] = desired_out[0] == '+' ? 1 : -1;
  33.         count++;
  34.     }
  35.  
  36.     // The training process starts
  37.     while (1) {
  38.         int i;
  39.         float old_weights[] = {weights[0], weights[1], weights[2]};
  40.         //printf("Interation: %d\n", ++j);
  41.         for (i = 0; i < count; i++) {
  42.             float out   =  sets[i][0] * weights[0] + sets[i][1] * weights[1] + weights[2] >= 0 ? 1 : -1;
  43.             float delta =  learning_rate * (sets[i][2] - out);
  44.  
  45.             weights[0] += delta * sets[i][0];
  46.             weights[1] += delta * sets[i][1];
  47.             weights[2] += delta;
  48.         }
  49.         //printf("Weights: %f, %f, %f\n", weights[0], weights[1], weights[2]);
  50.         if (old_weights[0] == weights[0] && old_weights[1] == weights[1] && old_weights[2] == weights[2]) break;
  51.     }
  52.  
  53.     while (scanf("%f,%f\n", &p0, &p1) != EOF) {
  54.         char* out_str = p0 * weights[0] + p1 * weights[1] + weights[2] >= 0 ? "+1" : "-1";
  55.         printf("%s\n", out_str);
  56.     }
  57.  
  58.     return 0;
  59. }
Advertisement
Add Comment
Please, Sign In to add comment