[关闭]
@ljt12138 2017-05-10T21:25:10.000000Z 字数 2332 阅读 793

最小二乘法的实现


问题描述

给定一组基函数f0(x),f1(x),,fk1(x)和一组数据点(xi,yi),求系数c1,c2,,ck使得函数f(x)=cifi(x)对于数据点的拟合程度最高,即最小化:

i(f(xi)y(i))2

分析

原问题可以表述成矩阵形式:

A=f0(x0)f1(x1)f1(xn1)f1(x0)f2(x1)f2(xn1)fk1(x0)fk1(x1)fk1(xn1)c=c0c1ck1,y=y0y1yn1(96)

则误差矩阵:

η=Acy

最小化:

iη2i=i(kAkiciyi)2

依次对cp,p=0,1,2求导并令导数为0,得到方程:

AT(Acy)=0

解得:

c=(ATA)1ATy

如果选取幂函数作为基函数,则是用多项式拟合一个函数。

Code

  1. #include <bits/stdc++.h>
  2. using namespace std;
  3. const int MAXN = 505;
  4. double A[MAXN][MAXN], AT[MAXN][MAXN];
  5. double B[MAXN][MAXN], M[MAXN][MAXN], R[MAXN][MAXN];
  6. void mul(double A[MAXN][MAXN], double B[MAXN][MAXN], int n, int m, int q)
  7. {
  8. memset(M, 0, sizeof M);
  9. for (int i = 1; i <= n; i++)
  10. for (int j = 1; j <= q; j++)
  11. for (int k = 1; k <= m; k++)
  12. M[i][j] += A[i][k]*B[k][j];
  13. }
  14. void T(double A[MAXN][MAXN], int n, int m)
  15. {
  16. for (int i = 1; i <= n; i++)
  17. for (int j = 1; j <= m; j++)
  18. M[j][i] = A[i][j];
  19. }
  20. void inverse(double A[MAXN][MAXN], int n)
  21. {
  22. memcpy(M, A, sizeof A), memset(R, 0, sizeof R);
  23. for (int i = 1; i <= n; i++) R[i][i] = 1;
  24. for (int i = 1; i <= n; i++) {
  25. double mx = A[i][i];
  26. int id = i;
  27. for (int j = i+1; j <= n; j++)
  28. if (A[j][i] > mx)
  29. mx = A[j][i], id = i;
  30. swap(A[i], A[id]);
  31. for (int j = 1; j <= n; j++) {
  32. if (j == i) continue;
  33. double v = -M[j][i]/M[i][i];
  34. for (int k = 1; k <= n; k++)
  35. M[j][k] += M[i][k]*v, R[j][k] += R[i][k]*v;
  36. }
  37. }
  38. for (int i = 1; i <= n; i++) {
  39. for (int j = 1; j <= n; j++)
  40. R[i][j] /= M[i][i];
  41. }
  42. memcpy(M, R, sizeof R);
  43. }
  44. double x[MAXN], y[MAXN], ATy[MAXN];
  45. int n, k;
  46. int main()
  47. {
  48. scanf("%d%d", &n, &k);
  49. for (int i = 1; i <= n; i++)
  50. scanf("%lf%lf", &x[i], &y[i]);
  51. for (int i = 1; i <= n; i++) {
  52. A[i][1] = 1;
  53. for (int j = 2; j <= k; j++)
  54. A[i][j] = A[i][j-1]*x[i];
  55. }
  56. T(A, n, k);
  57. memcpy(AT, M, sizeof M);
  58. for (int i = 1; i <= k; i++) {
  59. ATy[i] = 0;
  60. for (int j = 1; j <= n; j++)
  61. ATy[i] += AT[i][j]*y[j];
  62. }
  63. mul(AT, A, k, n, k);
  64. memcpy(B, M, sizeof M);
  65. inverse(B, k);
  66. memcpy(B, M, sizeof M);
  67. for (int i = 1; i <= k; i++) {
  68. double c = 0;
  69. for (int j = 1; j <= k; j++)
  70. c += B[i][j]*ATy[j];
  71. printf("%.3f\n", c);
  72. }
  73. return 0;
  74. }
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注