2
0

twice.c 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <time.h>
  4. float train[][2] = {
  5. {0, 0},
  6. {1, 2},
  7. {2, 4},
  8. {3, 6},
  9. {4, 8},
  10. };
  11. #define train_count (sizeof(train)/sizeof(train[0]))
  12. float rand_float(void)
  13. {
  14. return (float) rand()/ (float) RAND_MAX;
  15. }
  16. // x1, x2, x3, ..., b
  17. // w1, w2, w3, ...
  18. // y = x1*w1 + x2*w2 + x3*w3 + ... + b
  19. float cost(float w)
  20. {
  21. float result = 0.0f;
  22. size_t n = train_count;
  23. for (size_t i = 0; i < n; ++i) {
  24. float x = train[i][0];
  25. float y = x*w;
  26. float d = y - train[i][1];
  27. result += d*d;
  28. }
  29. result /= n;
  30. return result;
  31. }
  32. float dcost(float w)
  33. {
  34. float result = 0.0f;
  35. size_t n = train_count;
  36. for (size_t i = 0; i < n; ++i) {
  37. float x = train[i][0];
  38. float y = train[i][1];
  39. result += 2*(x*w - y)*x;
  40. }
  41. result /= n;
  42. return result;
  43. }
  44. int main()
  45. {
  46. // srand(time(0));
  47. srand(69);
  48. float w = rand_float()*10.0f;
  49. float rate = 1e-1;
  50. printf("cost = %f, w = %f\n", cost(w), w);
  51. for (size_t i = 0; i < 50; ++i) {
  52. #if 0
  53. float eps = 1e-3;
  54. float c = cost(w);
  55. float dw = (cost(w + eps) - c)/eps;;
  56. #else
  57. float dw = dcost(w);
  58. #endif
  59. w -= rate*dw;
  60. printf("cost = %f, w = %f\n", cost(w), w);
  61. }
  62. printf("------------------------------\n");
  63. printf("w = %f\n", w);
  64. return 0;
  65. }