dooooooduo

CI_ASS2_Single Neuron Regression_C

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