## File: Fitting-large-linear-systems-example.html

package info (click to toggle)
gsl-ref-html 2.3-1
• area: non-free
• in suites: bullseye, buster, sid
• size: 6,876 kB
• ctags: 4,574
• sloc: makefile: 35
 file content (290 lines) | stat: -rw-r--r-- 10,813 bytes parent folder | download
 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290  GNU Scientific Library – Reference Manual: Fitting large linear systems example

38.8.6 Large Dense Linear Regression Example

The following program demostrates the large dense linear least squares solvers. This example is adapted from Trefethen and Bau, and fits the function f(t) = \exp{(\sin^3{(10t)}}) on the interval [0,1] with a degree 15 polynomial. The program generates n = 50000 equally spaced points t_i on this interval, calculates the function value and adds random noise to determine the observation value y_i. The entries of the least squares matrix are X_{ij} = t_i^j, representing a polynomial fit. The matrix is highly ill-conditioned, with a condition number of about 1.4 \cdot 10^{11}. The program accumulates the matrix into the least squares system in 5 blocks, each with 10000 rows. This way the full matrix X is never stored in memory. We solve the system with both the normal equations and TSQR methods. The results are shown in the plot below. In the top left plot, we see the unregularized normal equations solution has larger error than TSQR due to the ill-conditioning of the matrix. In the bottom left plot, we show the L-curve, which exhibits multiple corners. In the top right panel, we plot a regularized solution using \lambda = 10^{-6}. The TSQR and normal solutions now agree, however they are unable to provide a good fit due to the damping. This indicates that for some ill-conditioned problems, regularizing the normal equations does not improve the solution. This is further illustrated in the bottom right panel, where we plot the L-curve calculated from the normal equations. The curve agrees with the TSQR curve for larger damping parameters, but for small \lambda, the normal equations approach cannot provide accurate solution vectors leading to numerical inaccuracies in the left portion of the curve.

#include <gsl/gsl_math.h> #include <gsl/gsl_vector.h> #include <gsl/gsl_matrix.h> #include <gsl/gsl_rng.h> #include <gsl/gsl_randist.h> #include <gsl/gsl_multifit.h> #include <gsl/gsl_multilarge.h> #include <gsl/gsl_blas.h>  /* function to be fitted */ double func(const double t) {   double x = sin(10.0 * t);   return exp(x*x*x); }  /* construct a row of the least squares matrix */ int build_row(const double t, gsl_vector *row) {   const size_t p = row->size;   double Xj = 1.0;   size_t j;    for (j = 0; j < p; ++j)     {       gsl_vector_set(row, j, Xj);       Xj *= t;     }    return 0; }  int solve_system(const int print_data, const gsl_multilarge_linear_type * T,              const double lambda, const size_t n, const size_t p,              gsl_vector * c) {   const size_t nblock = 5;         /* number of blocks to accumulate */   const size_t nrows = n / nblock; /* number of rows per block */   gsl_multilarge_linear_workspace * w =     gsl_multilarge_linear_alloc(T, p);   gsl_matrix *X = gsl_matrix_alloc(nrows, p);   gsl_vector *y = gsl_vector_alloc(nrows);   gsl_rng *r = gsl_rng_alloc(gsl_rng_default);   const size_t nlcurve = 200;   gsl_vector *reg_param = gsl_vector_alloc(nlcurve);   gsl_vector *rho = gsl_vector_alloc(nlcurve);   gsl_vector *eta = gsl_vector_alloc(nlcurve);   size_t rowidx = 0;   double rnorm, snorm, rcond;   double t = 0.0;   double dt = 1.0 / (n - 1.0);    while (rowidx < n)     {       size_t nleft = n - rowidx;         /* number of rows left to accumulate */       size_t nr = GSL_MIN(nrows, nleft); /* number of rows in this block */       gsl_matrix_view Xv = gsl_matrix_submatrix(X, 0, 0, nr, p);       gsl_vector_view yv = gsl_vector_subvector(y, 0, nr);       size_t i;        /* build (X,y) block with 'nr' rows */       for (i = 0; i < nr; ++i)         {           gsl_vector_view row = gsl_matrix_row(&Xv.matrix, i);           double fi = func(t);           double ei = gsl_ran_gaussian (r, 0.1 * fi); /* noise */           double yi = fi + ei;            /* construct this row of LS matrix */           build_row(t, &row.vector);            /* set right hand side value with added noise */           gsl_vector_set(&yv.vector, i, yi);            if (print_data && (i % 100 == 0))             printf("%f %f\n", t, yi);            t += dt;         }        /* accumulate (X,y) block into LS system */       gsl_multilarge_linear_accumulate(&Xv.matrix, &yv.vector, w);        rowidx += nr;     }    if (print_data)     printf("\n\n");    /* compute L-curve */   gsl_multilarge_linear_lcurve(reg_param, rho, eta, w);    /* solve large LS system and store solution in c */   gsl_multilarge_linear_solve(lambda, c, &rnorm, &snorm, w);    /* compute reciprocal condition number */   gsl_multilarge_linear_rcond(&rcond, w);    fprintf(stderr, "=== Method %s ===\n", gsl_multilarge_linear_name(w));   fprintf(stderr, "condition number = %e\n", 1.0 / rcond);   fprintf(stderr, "residual norm    = %e\n", rnorm);   fprintf(stderr, "solution norm    = %e\n", snorm);    /* output L-curve */   {     size_t i;     for (i = 0; i < nlcurve; ++i)       {         printf("%.12e %.12e %.12e\n",                gsl_vector_get(reg_param, i),                gsl_vector_get(rho, i),                gsl_vector_get(eta, i));       }     printf("\n\n");   }    gsl_matrix_free(X);   gsl_vector_free(y);   gsl_multilarge_linear_free(w);   gsl_rng_free(r);   gsl_vector_free(reg_param);   gsl_vector_free(rho);   gsl_vector_free(eta);    return 0; }  int main(int argc, char *argv[]) {   const size_t n = 50000;   /* number of observations */   const size_t p = 16;      /* polynomial order + 1 */   double lambda = 0.0;      /* regularization parameter */   gsl_vector *c_tsqr = gsl_vector_alloc(p);   gsl_vector *c_normal = gsl_vector_alloc(p);    if (argc > 1)     lambda = atof(argv[1]);    /* solve system with TSQR method */   solve_system(1, gsl_multilarge_linear_tsqr, lambda, n, p, c_tsqr);    /* solve system with Normal equations method */   solve_system(0, gsl_multilarge_linear_normal, lambda, n, p, c_normal);    /* output solutions */   {     gsl_vector *v = gsl_vector_alloc(p);     double t;      for (t = 0.0; t <= 1.0; t += 0.01)       {         double f_exact = func(t);         double f_tsqr, f_normal;          build_row(t, v);         gsl_blas_ddot(v, c_tsqr, &f_tsqr);         gsl_blas_ddot(v, c_normal, &f_normal);          printf("%f %e %e %e\n", t, f_exact, f_tsqr, f_normal);       }      gsl_vector_free(v);   }    gsl_vector_free(c_tsqr);   gsl_vector_free(c_normal);    return 0; }