15.4 General Linear Least Squares 671 15.4 General Linear Least Squares An immediate generalization of $15.2 is to fit a set of data points (xi,yi)to a model that is not just a linear combination of 1 and z(namely a+bz),but rather a linear combination of any M specified functions of x.For example,the functions could be 1,z2,...,M-1,in which case their general linear combination, y()=a1+a2z+a3z2+...+aMzM-1 (15.4.1) is a polynomial of degree M-1.Or,the functions could be sines and cosines,in which case their general linear combination is a harmonic series. The general form of this kind of model is M y()=>axXx(z) (15.4.2) k=1 ICAL where Xi(),...,XM()are arbitrary fixed functions of called the basis functions. Note that the functions X()can be wildly nonlinear functions of z.In this discussion"linear"refers only to the model's dependence on its parameters ak 之 9 For these linear models we generalize the discussion of the previous section by defining a merit function -∑1aXx( 73 (15.4.3) 9 =1 0 As before,o;is the measurement error (standard deviation)of the ith data point. presumed to be known.If the measurement errors are not known,they may all (as discussed at the end of $15.1)be set to the constant valueo=1. 61 Once again,we will pick as best parameters those that minimize x2.There are several different techniques available for finding this minimum.Two are particularly useful,and we will discuss both in this section.To introduce them and elucidate their relationship,we need some notation. Let A be a matrix whose N x M components are constructed from the M basis functions evaluated at the N abscissas zi,and from the N measurement errors oi,by the prescription Numerica 10621 4=) (15.4.4) 0 The matrix A is called the design matrix of the fitting problem.Notice that in general A has more rows than columns,N >M,since there must be more data points than model parameters to be solved for.(You can fit a straight line to two points,but not a very meaningful quintic!)The design matrix is shown schematically in Figure 15.4.1. Also define a vector b of length N by b=班 (15.4.5 and denote the M vector whose components are the parameters to be fitted, a1,...,aM,by a
15.4 General Linear Least Squares 671 Permission is granted for internet users to make one paper copy for their own personal use. Further reproduction, or any copyin Copyright (C) 1988-1992 by Cambridge University Press. Programs Copyright (C) 1988-1992 by Numerical Recipes Software. Sample page from NUMERICAL RECIPES IN C: THE ART OF SCIENTIFIC COMPUTING (ISBN 0-521-43108-5) g of machinereadable files (including this one) to any server computer, is strictly prohibited. To order Numerical Recipes books or CDROMs, visit website http://www.nr.com or call 1-800-872-7423 (North America only), or send email to directcustserv@cambridge.org (outside North America). 15.4 General Linear Least Squares An immediate generalization of §15.2 is to fit a set of data points (xi, yi) to a model that is not just a linear combination of 1 and x (namely a + bx), but rather a linear combination of any M specified functions of x. For example, the functions could be 1, x, x2,...,xM−1, in which case their general linear combination, y(x) = a1 + a2x + a3x2 + ··· + aM xM−1 (15.4.1) is a polynomial of degree M − 1. Or, the functions could be sines and cosines, in which case their general linear combination is a harmonic series. The general form of this kind of model is y(x) = M k=1 akXk(x) (15.4.2) where X1(x),...,XM(x) are arbitrary fixed functions of x, called the basis functions. Note that the functions Xk(x) can be wildly nonlinear functions of x. In this discussion “linear” refers only to the model’s dependence on its parameters a k. For these linear models we generalize the discussion of the previous section by defining a merit function χ2 = N i=1 yi − M k=1 akXk(xi) σi 2 (15.4.3) As before, σi is the measurement error (standard deviation) of the ith data point, presumed to be known. If the measurement errors are not known, they may all (as discussed at the end of §15.1) be set to the constant value σ = 1. Once again, we will pick as best parameters those that minimize χ2. There are several different techniques available for finding this minimum. Two are particularly useful, and we will discuss both in this section. To introduce them and elucidate their relationship, we need some notation. Let A be a matrix whose N × M components are constructed from the M basis functions evaluated at the N abscissas xi, and from the N measurement errors σi, by the prescription Aij = Xj (xi) σi (15.4.4) The matrix A is called the design matrix of the fitting problem. Notice that in general A has more rows than columns, N ≥M, since there must be more data points than model parameters to be solved for. (You can fit a straight line to two points, but not a very meaningful quintic!) The design matrix is shown schematically in Figure 15.4.1. Also define a vector b of length N by bi = yi σi (15.4.5) and denote the M vector whose components are the parameters to be fitted, a1,...,aM, by a.
672 Chapter 15.Modeling of Data basis functions- X()X()···X) 1 X(x1) X3(x) XM(x1) 01 01 01 X2 X(x2) X(x2) XM(x2) 02 02 61 Permission is read able files Sample page : .. Xi(N) X(IN) XM(XN) http://www.nr.com or call 1-800-872-7423(North America (including this one)to any server computer, granted for interet users to make one paper Copyright (C)1988-1992 by Cambridge University Press. from NUMERICAL RECIPES IN C: ON ON Figure 15.4.1.Design matrix for the least-squares fit of a linear combination of M basis functions to N data points.The matrix elements involve the basis functions evaluated at the values of the independent variable at which measurements are made,and the standard deviations of the measured dependent variable. 是 The measured values of the dependent variable do not enter the design matrix. Programs Solution by Use of the Normal Equations copy for their The minimum of(15.4.3)occurs where the derivative ofx2 with respect to all M parameters ak vanishes.Specializing equation(15.1.7)to the case of the model to dir Copyright(C) (15.4.2),this condition yields the M equations 1788-1982 THE ART OF SCIENTIFIC COMPUTING(ISBN 0-521 N 0= Xk(zi) k=1,M (15.4.6) Interchanging the order of summations,we can write(15.4.6)as the matrix equation .Further reproduction, Numerical Recipes -43108-5 M (15.4.7) (outside j=1 Software. where Amer N Xj(zi)Xk(zi) ying of machine visit website akj= or equivalently [a]=AT.A (15.4.8) i=1 0 an M x M matrix,and A=∑ w or equivalently [31=AT.b (15.4.9) =1
672 Chapter 15. Modeling of Data Permission is granted for internet users to make one paper copy for their own personal use. Further reproduction, or any copyin Copyright (C) 1988-1992 by Cambridge University Press. Programs Copyright (C) 1988-1992 by Numerical Recipes Software. Sample page from NUMERICAL RECIPES IN C: THE ART OF SCIENTIFIC COMPUTING (ISBN 0-521-43108-5) g of machinereadable files (including this one) to any server computer, is strictly prohibited. To order Numerical Recipes books or CDROMs, visit website http://www.nr.com or call 1-800-872-7423 (North America only), or send email to directcustserv@cambridge.org (outside North America). X1(x1) σ1 x1 X2(x1) σ1 . . . XM(x1) σ1 X1( ) X2( ) . . . XM( ) X1(x2) σ2 x2 X2(x2) σ2 . . . XM(x2) σ2 . . . . . . . . . . . . . . . . . . . . . X1(xN) σN xN X2(xN) σN . . . XM(xN) σN data points basis functions Figure 15.4.1. Design matrix for the least-squares fit of a linear combination of M basis functions to N data points. The matrix elements involve the basis functions evaluated at the values of the independent variable at which measurements are made, and the standard deviations of the measured dependent variable. The measured values of the dependent variable do not enter the design matrix. Solution by Use of the Normal Equations The minimum of (15.4.3) occurs where the derivative of χ2 with respect to all M parameters ak vanishes. Specializing equation (15.1.7) to the case of the model (15.4.2), this condition yields the M equations 0 = N i=1 1 σ2 i yi − M j=1 ajXj (xi) Xk(xi) k = 1,...,M (15.4.6) Interchanging the order of summations, we can write (15.4.6) as the matrix equation M j=1 αkjaj = βk (15.4.7) where αkj = N i=1 Xj(xi)Xk(xi) σ2 i or equivalently [α] = AT · A (15.4.8) an M × M matrix, and βk = N i=1 yiXk(xi) σ2 i or equivalently [β] = AT · b (15.4.9)
15.4 General Linear Least Squares 673 a vector of length M. The equations (15.4.6)or(15.4.7)are called the normal equations of the least- squares problem.They can be solved for the vector of parameters a by the standard methods of Chapter 2,notably LU decomposition and backsubstitution,Choleksy decomposition,or Gauss-Jordan elimination.In matrix form,the normal equations can be written as either [al·a=[例 or as (AT.A)·a=AT.b (15.4.10) The inverse matrix C is closely related to the probable (or,more precisely,standard)uncertainties of the estimated parameters a.To estimate these uncertainties,consider that M ∑aR=∑C 02 (15.4.11) and that the variance associated with the estimate a;can be found as in (15.2.7)from RECIPES 令 2(a) ∑ (15.4.12) Press. Note that ajk is independent of yi,so that 9 M =CjkXx(1)/o? (15.4.13) 0班 IENTIFIC k=1 6 Consequently,we find that o2(aj) Xk(zi)XI(xi) 15.4.14) k=1= The final term in brackets is just the matrix [a].Since this is the matrix inverse of Numerical 105211 [C],(15.4.14)reduces immediately to 431 a2(a)=C7 (15.4.15) (outside Recipes In other words,the diagonal elements of [C]are the variances (squared North uncertainties)of the fitted parameters a.It should not surprise you to learn that the off-diagonal elements Cik are the covariances between a;and ak(cf.15.2.10);but we shall defer discussion of these to 815.6. We will now give a routine that implements the above formulas for the general linear least-squares problem,by the method of normal equations.Since we wish to compute not only the solution vector a but also the covariance matrix [C],it is most convenient to use Gauss-Jordan elimination(routine gaussj of 82.1)to perform the linear algebra.The operation count,in this application,is no larger than that for LU decomposition.If you have no need for the covariance matrix,however,you can save a factor of 3 on the linear algebra by switching to LU decomposition,without
15.4 General Linear Least Squares 673 Permission is granted for internet users to make one paper copy for their own personal use. Further reproduction, or any copyin Copyright (C) 1988-1992 by Cambridge University Press. Programs Copyright (C) 1988-1992 by Numerical Recipes Software. Sample page from NUMERICAL RECIPES IN C: THE ART OF SCIENTIFIC COMPUTING (ISBN 0-521-43108-5) g of machinereadable files (including this one) to any server computer, is strictly prohibited. To order Numerical Recipes books or CDROMs, visit website http://www.nr.com or call 1-800-872-7423 (North America only), or send email to directcustserv@cambridge.org (outside North America). a vector of length M. The equations (15.4.6) or (15.4.7) are called the normal equations of the leastsquares problem. They can be solved for the vector of parameters a by the standard methods of Chapter 2, notably LU decomposition and backsubstitution, Choleksy decomposition, or Gauss-Jordan elimination. In matrix form, the normal equations can be written as either [α] · a = [β] or as AT · A · a = AT · b (15.4.10) The inverse matrix Cjk ≡ [α] −1 jk is closely related to the probable (or, more precisely, standard) uncertainties of the estimated parameters a. To estimate these uncertainties, consider that aj = M k=1 [α] −1 jk βk = M k=1 Cjk N i=1 yiXk(xi) σ2 i (15.4.11) and that the variance associated with the estimate aj can be found as in (15.2.7) from σ2(aj ) = N i=1 σ2 i ∂aj ∂yi 2 (15.4.12) Note that αjk is independent of yi, so that ∂aj ∂yi = M k=1 CjkXk(xi)/σ2 i (15.4.13) Consequently, we find that σ2(aj ) = M k=1 M l=1 CjkCjl N i=1 Xk(xi)Xl(xi) σ2 i (15.4.14) The final term in brackets is just the matrix [α]. Since this is the matrix inverse of [C], (15.4.14) reduces immediately to σ2(aj ) = Cjj (15.4.15) In other words, the diagonal elements of [C] are the variances (squared uncertainties) of the fitted parameters a. It should not surprise you to learn that the off-diagonal elements Cjk are the covariances between aj and ak (cf. 15.2.10); but we shall defer discussion of these to §15.6. We will now give a routine that implements the above formulas for the general linear least-squares problem, by the method of normal equations. Since we wish to compute not only the solution vector a but also the covariance matrix [C], it is most convenient to use Gauss-Jordan elimination (routine gaussj of §2.1) to perform the linear algebra. The operation count, in this application, is no larger than that for LU decomposition. If you have no need for the covariance matrix, however, you can save a factor of 3 on the linear algebra by switching to LU decomposition, without
674 Chapter 15.Modeling of Data computation of the matrix inverse.In theory,since AT.A is positive definite, Cholesky decomposition is the most efficient way to solve the normal equations. However,in practice most of the computing time is spent in looping over the data to form the equations,and Gauss-Jordan is quite adequate. We need to warn you that the solution of a least-squares problem directly from the normal equations is rather susceptible to roundoff error.An alternative,and preferred,technique involves QR decomposition (82.10,$11.3,and $11.6)of the design matrix A.This is essentially what we did at the end of 815.2 for fitting data to a straight line,but without invoking all the machinery of OR to derive the necessary formulas.Later in this section,we will discuss other difficulties in the least-squares problem,for which the cure is singular value decomposition(SVD),of which we give an implementation.It turns out that SVD also fixes the roundoff problem,so it is our recommended technique for all but"easyleast-squares problems.It is for these easy g problems that the following routine,which solves the normal equations,is intended The routine below introduces one bookkeeping trick that is quite useful in practical work.Frequently it is a matter of"art"to decide which parameters ak in a model should be fit from the data set,and which should be held constant at fixed values,for example values predicted by a theory or measured in a previous experiment.One wants,therefore,to have a convenient means for "freezing" and"unfreezing"the parameters ak.In the following routine the total number of THE parameters ak is denoted ma(called M above).As input to the routine,you supply ART an array ia[1..ma],whose components are either zero or nonzero (e.g..1).Zeros indicate that you want the corresponding elements of the parameter vector a [1..ma] Programs to be held fixed at their input values.Nonzeros indicate parameters that should be fitted for.On output,any frozen parameters will have their variances,and all their covariances,set to zero in the covariance matrix to dir #include "nrutil.h" void lfit(f1oatx[],f1oaty▣,f1 oat sig0,int ndat,f1oata▣,int ia0, OF SCIENTIFIC COMPUTING(ISBN int ma,float **covar,float *chisq, void (*funcs)(float,float []int)) 1988-19920 Given a set of data points x[1..ndat],y[1..ndat]with individual standard deviations sig[1..ndat],use x minimization to fit for some or all of the coefficients a[1..ma]of a function that depends linearly on a,y=>;ai x afunci(x).The input array ia[1..ma] indicates by nonzero entries those components of a that should be fitted for,and by zero entries those components that should be held fixed at their input values.The program returns values for a[1..ma],x2=chisq,and the covariance matrix covar [1..ma][1..ma].(Parameters Numerical Recipes 10-621 43108 held fixed will return zero covariances.The user supplies a routine funcs(x,afunc,ma)that returns the ma basis functions evaluated at =x in the array afunc[1..ma]. (outside void covsrt(float **covar,int ma,int ia[],int mfit); North Software. void gaussj(float **a,int n,float **b,int m); 1nt1,j,k,1,m,mf1t=0; float ym,wt,sum,sig2i,**beta,*afunc; Ame beta=matrix(1,ma,1,1); afunc-vector(1,ma); for (j=1;j<=ma;j++) if (ia[j])mfit++; if (mfit ==0)nrerror("lfit:no parameters to be fitted"); for (j=1;j<=mfit;j++) Initialize the (symmetric)matrix. for (k=1;k<=mfit;k++)covar [j][k]=0.0; beta[j][1]=0.0; 2 for (i=1;i<=ndat;i++){ Loop over data to accumulate coefficients of the normal equations
674 Chapter 15. Modeling of Data Permission is granted for internet users to make one paper copy for their own personal use. Further reproduction, or any copyin Copyright (C) 1988-1992 by Cambridge University Press. Programs Copyright (C) 1988-1992 by Numerical Recipes Software. Sample page from NUMERICAL RECIPES IN C: THE ART OF SCIENTIFIC COMPUTING (ISBN 0-521-43108-5) g of machinereadable files (including this one) to any server computer, is strictly prohibited. To order Numerical Recipes books or CDROMs, visit website http://www.nr.com or call 1-800-872-7423 (North America only), or send email to directcustserv@cambridge.org (outside North America). computation of the matrix inverse. In theory, since AT · A is positive definite, Cholesky decomposition is the most efficient way to solve the normal equations. However, in practice most of the computing time is spent in looping over the data to form the equations, and Gauss-Jordan is quite adequate. We need to warn you that the solution of a least-squares problem directly from the normal equations is rather susceptible to roundoff error. An alternative, and preferred, technique involves QR decomposition (§2.10, §11.3, and §11.6) of the design matrix A. This is essentially what we did at the end of §15.2 for fitting data to a straight line, but without invoking all the machinery of QR to derive the necessary formulas. Later in this section, we will discuss other difficulties in the least-squares problem, for which the cure issingular value decomposition (SVD), of which we give an implementation. It turns out that SVD also fixes the roundoff problem, so it is our recommended technique for all but “easy” least-squares problems. It is for these easy problems that the following routine, which solves the normal equations, is intended. The routine below introduces one bookkeeping trick that is quite useful in practical work. Frequently it is a matter of “art” to decide which parameters a k in a model should be fit from the data set, and which should be held constant at fixed values, for example values predicted by a theory or measured in a previous experiment. One wants, therefore, to have a convenient means for “freezing” and “unfreezing” the parameters ak. In the following routine the total number of parameters ak is denoted ma (called M above). As input to the routine, you supply an array ia[1..ma], whose components are either zero or nonzero (e.g., 1). Zeros indicate that you want the corresponding elements of the parameter vector a[1..ma] to be held fixed at their input values. Nonzeros indicate parameters that should be fitted for. On output, any frozen parameters will have their variances, and all their covariances, set to zero in the covariance matrix. #include "nrutil.h" void lfit(float x[], float y[], float sig[], int ndat, float a[], int ia[], int ma, float **covar, float *chisq, void (*funcs)(float, float [], int)) Given a set of data points x[1..ndat], y[1..ndat] with individual standard deviations sig[1..ndat], use χ2 minimization to fit for some or all of the coefficients a[1..ma] of a function that depends linearly on a, y = i ai × afunci(x). The input array ia[1..ma] indicates by nonzero entries those components of a that should be fitted for, and by zero entries those components that should be held fixed at their input values. The program returns values for a[1..ma], χ2 = chisq, and the covariance matrix covar[1..ma][1..ma]. (Parameters held fixed will return zero covariances.)The user supplies a routine funcs(x,afunc,ma) that returns the ma basis functions evaluated at x = x in the array afunc[1..ma]. { void covsrt(float **covar, int ma, int ia[], int mfit); void gaussj(float **a, int n, float **b, int m); int i,j,k,l,m,mfit=0; float ym,wt,sum,sig2i,**beta,*afunc; beta=matrix(1,ma,1,1); afunc=vector(1,ma); for (j=1;j<=ma;j++) if (ia[j]) mfit++; if (mfit == 0) nrerror("lfit: no parameters to be fitted"); for (j=1;j<=mfit;j++) { Initialize the (symmetric)matrix. for (k=1;k<=mfit;k++) covar[j][k]=0.0; beta[j][1]=0.0; } for (i=1;i<=ndat;i++) { Loop over data to accumulate coefficients of the normal equations.
15.4 General Linear Least Squares 675 (*funcs)(x[i],afunc,ma); ym=y[i]: if (mfit ma){ Subtract off dependences on known pieces for (j=1;j=1;j--)[ if(1a[j]){ for (i=1;i<=ma;i++)SWAP(covar[i][k],covar[i][j]) for (i=1;i<=ma;i++)SWAP(covar[k][i],covar[j][i]) 22
15.4 General Linear Least Squares 675 Permission is granted for internet users to make one paper copy for their own personal use. Further reproduction, or any copyin Copyright (C) 1988-1992 by Cambridge University Press. Programs Copyright (C) 1988-1992 by Numerical Recipes Software. Sample page from NUMERICAL RECIPES IN C: THE ART OF SCIENTIFIC COMPUTING (ISBN 0-521-43108-5) g of machinereadable files (including this one) to any server computer, is strictly prohibited. To order Numerical Recipes books or CDROMs, visit website http://www.nr.com or call 1-800-872-7423 (North America only), or send email to directcustserv@cambridge.org (outside North America). (*funcs)(x[i],afunc,ma); ym=y[i]; if (mfit =1;j--) { if (ia[j]) { for (i=1;i<=ma;i++) SWAP(covar[i][k],covar[i][j]) for (i=1;i<=ma;i++) SWAP(covar[k][i],covar[j][i]) k--; } } }
676 Chapter 15.Modeling of Data Solution by Use of Singular Value Decomposition In some applications,the normal equations are perfectly adequate for linear least-squares problems.However,in many cases the normal equations are very close to singular.A zero pivot element may be encountered during the solution of the linear equations(e.g.,in gaussj),in which case you get no solution at all.Or a very small pivot may occur,in which case you typically get fitted parameters ak with very large magnitudes that are delicately(and unstably)balanced to cancel out almost precisely when the fitted function is evaluated. Why does this commonly occur?The reason is that,more often than experi- 81 menters would like to admit,data do not clearly distinguish between two or more of the basis functions provided.If two such functions,or two different combinations of functions,happen to fit the data about equally well-or equally badly-then the matrix [a],unable to distinguish between them,neatly folds up its tent and becomes singular.There is a certain mathematical irony in the fact that least-squares problems are both overdetermined(number of data points greater than number of parameters)and underdetermined (ambiguous combinations of parameters exist); but that is how it frequently is.The ambiguities can be extremely hard to notice a priori in complicated problems. 9 Enter singular value decomposition(SVD).This would be a good time for you to review the material in $2.6,which we will not repeat here.In the case of an overdetermined system,SVD produces a solution that is the best approximation in the least-squares sense,cf.equation(2.6.10).That is exactly what we want.In the case of an underdetermined system,SVD produces a solution whose values(for us, 、孕20 the ak's)are smallest in the least-squares sense,cf.equation (2.6.8).That is also what we want:When some combination of basis functions is irrelevant to the fit,that combination will be driven down to a small,innocuous,value,rather than pushed 名a2, 6 up to delicately canceling infinities. In terms of the design matrix A (equation 15.4.4)and the vector b (equation 15.4.5),minimization of x2 in (15.4.3)can be written as find a that minimizes x2=A.a-b2 (15.4.16) Numerical 10621 Comparing to equation(2.6.9),we see that this is precisely the problem that routines svdcmp and svbksb are designed to solve.The solution,which is given by equation (2.6.12),can be rewritten as follows:If U and V enter the SVD decomposition of A according to equation (2.6.1),as computed by svdcmp,then let the vectors U()i=1,...,M denote the columns of U (each one a vector of length N);and let the vectors V();i=1,...,M denote the columns of V (each one a vector of length M).Then the solution (2.6.12)of the least-squares problem (15.4.16) can be written as (15.4.17) where the w;are,as in 82.6,the singular values calculated by svdcmp. Equation(15.4.17)says that the fitted parameters a are linear combinations of the columns of V,with coefficients obtained by forming dot products of the columns
676 Chapter 15. Modeling of Data Permission is granted for internet users to make one paper copy for their own personal use. Further reproduction, or any copyin Copyright (C) 1988-1992 by Cambridge University Press. Programs Copyright (C) 1988-1992 by Numerical Recipes Software. Sample page from NUMERICAL RECIPES IN C: THE ART OF SCIENTIFIC COMPUTING (ISBN 0-521-43108-5) g of machinereadable files (including this one) to any server computer, is strictly prohibited. To order Numerical Recipes books or CDROMs, visit website http://www.nr.com or call 1-800-872-7423 (North America only), or send email to directcustserv@cambridge.org (outside North America). Solution by Use of Singular Value Decomposition In some applications, the normal equations are perfectly adequate for linear least-squares problems. However, in many cases the normal equations are very close to singular. A zero pivot element may be encountered during the solution of the linear equations (e.g., in gaussj), in which case you get no solution at all. Or a very small pivot may occur, in which case you typically get fitted parameters a k with very large magnitudes that are delicately (and unstably) balanced to cancel out almost precisely when the fitted function is evaluated. Why does this commonly occur? The reason is that, more often than experimenters would like to admit, data do not clearly distinguish between two or more of the basis functions provided. If two such functions, or two different combinations of functions, happen to fit the data about equally well — or equally badly — then the matrix [α], unable to distinguish between them, neatly folds up its tent and becomes singular. There is a certain mathematical irony in the fact that least-squares problems are both overdetermined (number of data points greater than number of parameters) and underdetermined (ambiguous combinations of parameters exist); but that is how it frequently is. The ambiguities can be extremely hard to notice a priori in complicated problems. Enter singular value decomposition (SVD). This would be a good time for you to review the material in §2.6, which we will not repeat here. In the case of an overdetermined system, SVD produces a solution that is the best approximation in the least-squares sense, cf. equation (2.6.10). That is exactly what we want. In the case of an underdetermined system, SVD produces a solution whose values (for us, the ak’s) are smallest in the least-squares sense, cf. equation (2.6.8). That is also what we want: When some combination of basis functions is irrelevant to the fit, that combination will be driven down to a small, innocuous, value, rather than pushed up to delicately canceling infinities. In terms of the design matrix A (equation 15.4.4) and the vector b (equation 15.4.5), minimization of χ2 in (15.4.3) can be written as find a that minimizes χ2 = |A · a − b| 2 (15.4.16) Comparing to equation (2.6.9), we see that this is precisely the problem that routines svdcmp and svbksb are designed to solve. The solution, which is given by equation (2.6.12), can be rewritten as follows: If U and V enter the SVD decomposition of A according to equation (2.6.1), as computed by svdcmp, then let the vectors U(i) i = 1,...,M denote the columns of U (each one a vector of length N); and let the vectors V(i);i = 1,...,M denote the columns of V (each one a vector of length M). Then the solution (2.6.12) of the least-squares problem (15.4.16) can be written as a = M i=1 U(i) · b wi V(i) (15.4.17) where the wi are, as in §2.6, the singular values calculated by svdcmp. Equation (15.4.17) says that the fitted parameters a are linear combinations of the columns of V, with coefficients obtained by forming dot products of the columns
15.4 General Linear Least Squares 677 of U with the weighted data vector (15.4.5).Though it is beyond our scope to prove here,it turns out that the standard(loosely,"probable")errors in the fitted parameters are also linear combinations of the columns of V.In fact,equation(15.4.17)can be written in a form displaying these errors as Vo) (15.4.18) W1 VOD WM Here each+is followed by a standard deviation.The amazing fact is that, decomposed in this fashion,the standard deviations are all mutually independent 81 (uncorrelated).Therefore they can be added together in root-mean-square fashion. What is going on is that the vectors V(are the principal axes of the error ellipsoid of the fitted parameters a(see $15.6). It follows that the variance in the estimate of a parameter aj is given by ICAL (15.4.19) 9 whose result should be identical with(15.4.14).As before,you should not be surprised at the formula for the covariances,here given without proof, Cov(aj:ak (15.4.20) 是后0 9 We introduced this subsection by noting that the normal equations can fail by encountering a zero pivot.We have not yet,however,mentioned how SVD overcomes this problem.The answer is:If any singular value w:is zero,its 61 reciprocal in equation (15.4.18)should be set to zero,not infinity.(Compare the discussion preceding equation 2.6.7.)This corresponds to adding to the fitted parameters aa zero multiple,rather than some random large multiple,of any linear combination of basis functions that are degenerate in the fit.It is a good thing to do! Moreover,if a singular value wi is nonzero but very small,you should also define its reciprocal to be zero,since its apparent value is probably an artifact of Numerica 10621 roundofferror,not a meaningful number.A plausible answer to the question"how 431 small is small?"is to edit in this fashion all singular values whose ratio to the Recipes largest singular value is less than N times the machine precision e.(You might argue for vN,or a constant,instead of N as the multiple;that starts getting into hardware-dependent questions. There is another reason for editing even additional singular values,ones large enough that roundoff error is not a question.Singular value decomposition allows you to identify linear combinations of variables that just happen not to contribute much to reducing the x2 of your data set.Editing these can sometimes reduce the probable error on your coefficients quite significantly,while increasing the minimum x2only negligibly.We will learn more about identifying and treating such cases in $15.6.In the following routine,the point at which this kind of editing would occur is indicated. Generally speaking,we recommend that you always use SVD techniques instead of using the normal equations.SVD's only significant disadvantage is that it requires
15.4 General Linear Least Squares 677 Permission is granted for internet users to make one paper copy for their own personal use. Further reproduction, or any copyin Copyright (C) 1988-1992 by Cambridge University Press. Programs Copyright (C) 1988-1992 by Numerical Recipes Software. Sample page from NUMERICAL RECIPES IN C: THE ART OF SCIENTIFIC COMPUTING (ISBN 0-521-43108-5) g of machinereadable files (including this one) to any server computer, is strictly prohibited. To order Numerical Recipes books or CDROMs, visit website http://www.nr.com or call 1-800-872-7423 (North America only), or send email to directcustserv@cambridge.org (outside North America). of U with the weighted data vector (15.4.5). Though it is beyond our scope to prove here, it turns out that the standard (loosely, “probable”) errors in the fitted parameters are also linear combinations of the columns of V. In fact, equation (15.4.17) can be written in a form displaying these errors as a = M i=1 U(i) · b wi V(i) ± 1 w1 V(1) ±···± 1 wM V(M) (15.4.18) Here each ± is followed by a standard deviation. The amazing fact is that, decomposed in this fashion, the standard deviations are all mutually independent (uncorrelated). Therefore they can be added together in root-mean-square fashion. What is going on is that the vectors V(i) are the principal axes of the error ellipsoid of the fitted parameters a (see §15.6). It follows that the variance in the estimate of a parameter aj is given by σ2(aj ) = M i=1 1 w2 i [V(i)] 2 j = M i=1 Vji wi 2 (15.4.19) whose result should be identical with (15.4.14). As before, you should not be surprised at the formula for the covariances, here given without proof, Cov(aj , ak) = M i=1 VjiVki w2 i (15.4.20) We introduced this subsection by noting that the normal equations can fail by encountering a zero pivot. We have not yet, however, mentioned how SVD overcomes this problem. The answer is: If any singular value wi is zero, its reciprocal in equation (15.4.18) should be set to zero, not infinity. (Compare the discussion preceding equation 2.6.7.) This corresponds to adding to the fitted parameters a a zero multiple, rather than some random large multiple, of any linear combination of basis functions that are degenerate in the fit. It is a good thing to do! Moreover, if a singular value wi is nonzero but very small, you should also define its reciprocal to be zero, since its apparent value is probably an artifact of roundoff error, not a meaningful number. A plausible answer to the question “how small is small?” is to edit in this fashion all singular values whose ratio to the largest singular value is less than N times the machine precision . (You might argue for √ N, or a constant, instead of N as the multiple; that starts getting into hardware-dependent questions.) There is another reason for editing even additional singular values, ones large enough that roundoff error is not a question. Singular value decomposition allows you to identify linear combinations of variables that just happen not to contribute much to reducing the χ2 of your data set. Editing these can sometimes reduce the probable error on your coefficients quite significantly, while increasing the minimum χ2 only negligibly. We will learn more about identifying and treating such cases in §15.6. In the following routine, the point at which this kind of editing would occur is indicated. Generally speaking, we recommend that you always use SVD techniques instead of using the normal equations. SVD’s only significant disadvantage is that it requires
678 Chapter 15.Modeling of Data an extra array of size N x M to store the whole design matrix.This storage is overwritten by the matrix U.Storage is also required for the M x M matrix V,but this is instead of the same-sized matrix for the coefficients of the normal equations.SVD can be significantly slower than solving the normal equations; however,its great advantage,that it(theoretically)cannot fail,more than makes up for the speed disadvantage. In the routine that follows,the matrices u,v and the vector w are input as working space.The logical dimensions of the problem are ndata data points by ma basis functions (and fitted parameters).If you care only about the values a of the fitted parameters,then u,v,w contain no useful information on output.If you want probable errors for the fitted parameters,read on. 19881992 #include "nrutil.h" #define TOL 1.0e-5 Default value for single precision and vari- ables scaled to order unity void svdfit(f1oatx[],float y[l,float sig[☐,int ndata,f1oata☐,int ma, float **u,float **v,float w[],float *chisg, from NUMERICAL RECIPESI void (*funcs)(float,float []int)) Given a set of data points x[1..ndata],y[1..ndata]with individual standard deviations sig[1..ndata],use x2 minimization to determine the coefficients a[1..ma]of the fit- (Nort server 令 ting function y =>ai x afunci(x).Here we solve the fitting equations using singular value decomposition of the ndata by ma matrix,as in $2.6.Arrays u[1..ndata][1..ma], THE v[1..ma][1..ma],and w[1..ma]provide workspace on input;on output they define the Americ computer, singular value decomposition,and can be used to obtain the covariance matrix.The pro- ART gram returns values for the ma fit parameters a,and x2,chisq.The user supplies a routine funcs(x,afunc,ma)that returns the ma basis functions evaluated at x =x in the array afunc[1..ma] Programs void svbksb(float**u,float w[,f1oat**v,intm,intn,float b☐ f1oatx▣); void svdcmp(float **a,int m,int n,float w,float **v); int j,i; to dir float wmax,tmp,thresh,sum,*b,*afunc; b=vector(1,ndata); OF SCIENTIFIC COMPUTING(ISBN afunc=vector(1,ma); 19881992 for (i=1;i<-ndata;i++){ Accumulate coefficients of the fitting ma- (*funcs)(x[i],afunc,ma); trix. tmp=1.0/sig[1]; 10-621 for (j=1;j<=ma;j++)u[i][j]=afunc[j]*tmp; b[i]=y[i]*tmp; 43108 svdcmp(u,ndata,ma,w,v); Singular value decomposition. Numerical Recipes wmax=0.0; Edit the singular values,given TOL from the for (j=1;j<=ma;j++) #define statement,between here... (outside if (w[j]wmax) wmax=w[】; thresh=TOL*wmax; North Software. for (j=1;j<=ma;j++) if (w[j]thresh)w[j]=0.0; ...and here. svbksb(u,w,v,ndata,ma,b,a); *chisq=0.0; Evaluate chi-square. for (i=1;i<=ndata;i++){ (*funcs)(x[i],afunc,ma); for (sum=0.0,j=1;j<=ma;j++)sum +a[j]*afunc[j]; *chisq +(tmp=(y[i]-sum)/sig[i],tmp*tmp); free_vector(afunc,1,ma); free_vector(b,1,ndata);
678 Chapter 15. Modeling of Data Permission is granted for internet users to make one paper copy for their own personal use. Further reproduction, or any copyin Copyright (C) 1988-1992 by Cambridge University Press. Programs Copyright (C) 1988-1992 by Numerical Recipes Software. Sample page from NUMERICAL RECIPES IN C: THE ART OF SCIENTIFIC COMPUTING (ISBN 0-521-43108-5) g of machinereadable files (including this one) to any server computer, is strictly prohibited. To order Numerical Recipes books or CDROMs, visit website http://www.nr.com or call 1-800-872-7423 (North America only), or send email to directcustserv@cambridge.org (outside North America). an extra array of size N × M to store the whole design matrix. This storage is overwritten by the matrix U. Storage is also required for the M × M matrix V, but this is instead of the same-sized matrix for the coefficients of the normal equations. SVD can be significantly slower than solving the normal equations; however, its great advantage, that it (theoretically) cannot fail, more than makes up for the speed disadvantage. In the routine that follows, the matrices u,v and the vector w are input as working space. The logical dimensions of the problem are ndata data points by ma basis functions (and fitted parameters). If you care only about the values a of the fitted parameters, then u,v,w contain no useful information on output. If you want probable errors for the fitted parameters, read on. #include "nrutil.h" #define TOL 1.0e-5 Default value for single precision and variables scaled to order unity. void svdfit(float x[], float y[], float sig[], int ndata, float a[], int ma, float **u, float **v, float w[], float *chisq, void (*funcs)(float, float [], int)) Given a set of data points x[1..ndata],y[1..ndata] with individual standard deviations sig[1..ndata], use χ2 minimization to determine the coefficients a[1..ma] of the fitting function y = i ai × afunci(x). Here we solve the fitting equations using singular value decomposition of the ndata by ma matrix, as in §2.6. Arrays u[1..ndata][1..ma], v[1..ma][1..ma], and w[1..ma] provide workspace on input; on output they define the singular value decomposition, and can be used to obtain the covariance matrix. The program returns values for the ma fit parameters a, and χ2, chisq. The user supplies a routine funcs(x,afunc,ma) that returns the ma basis functions evaluated at x = x in the array afunc[1..ma]. { void svbksb(float **u, float w[], float **v, int m, int n, float b[], float x[]); void svdcmp(float **a, int m, int n, float w[], float **v); int j,i; float wmax,tmp,thresh,sum,*b,*afunc; b=vector(1,ndata); afunc=vector(1,ma); for (i=1;i wmax) wmax=w[j]; thresh=TOL*wmax; for (j=1;j<=ma;j++) if (w[j] < thresh) w[j]=0.0; ...and here. svbksb(u,w,v,ndata,ma,b,a); *chisq=0.0; Evaluate chi-square. for (i=1;i<=ndata;i++) { (*funcs)(x[i],afunc,ma); for (sum=0.0,j=1;j<=ma;j++) sum += a[j]*afunc[j]; *chisq += (tmp=(y[i]-sum)/sig[i],tmp*tmp); } free_vector(afunc,1,ma); free_vector(b,1,ndata); }
15.4 General Linear Least Squares 679 Feeding the matrix v and vector w output by the above program into the following short routine,you easily obtain variances and covariances of the fitted parameters a.The square roots of the variances are the standard deviations of the fitted parameters.The routine straightforwardly implements equation(15.4.20) above,with the convention that singular values equal to zero are recognized as having been edited out of the fit. #include "nrutil.h" void svdvar(float **v,int ma,float w[],float **cvm) To evaluate the covariance matrix cvm[1..ma][1..ma]of the fit for ma parameters obtained by svdfit,call this routine with matrices v[1..ma][1..ma],w[1..ma]as returned from 81 svdfit. int k,j,i; float sum,*wti; -00 from NUMERICAL 18881892 wti=vector(1,ma); for(i=1;i<ma;1++)[ wti[i]=0.0; RECIPES I if(w[i])ti[i]=1.0/(w[i]*w[i]); for(1=1;1<=ma;1++)[ Sum contributions to covariance matrix (15.4.20). for(j=1;j<=1;j++)[ for (sum=0.0,k=1;k<=ma;k++)sum +v[i][k]*v[j][k]*wti[k]; America computer, Press. cvm[j][i]=cvm[i][j]=sum; 9 ART free_vector(wti,1,ma); Programs 2 Examples to dir Be aware that some apparently nonlinear problems can be expressed so that 1992 SCIENTIFIC COMPUTING (ISBN they are linear.For example,an exponential model with two parameters a and b, y(r)=aexp(-bx) (15.4.21) can be rewritten as 10521 logy(x)】=c-bz (15.4.22) Numerical which is linear in its parameters c and b.(Of course you must be aware that such 43106 transformations do not exactly take Gaussian errors into Gaussian errors.) Recipes Also watch out for“non-parameters,.”asin y(x)=aexp(-bx+d) (15.4.23) North Here the parameters a and d are,in fact,indistinguishable.This is a good example of where the normal equations will be exactly singular,and where SVD will find a zero singular value.SVD will then make a"least-squares"choice for setting a balance between a and d (or,rather,their equivalents in the linear model derived by taking the logarithms).However-and this is true whenever SVD gives back a zero singular value-you are better advised to figure out analytically where the degeneracy is among your basis functions,and then make appropriate deletions in the basis set. Here are two examples for user-supplied routines funcs.The first one is trivial and fits a general polynomial to a set of data:
15.4 General Linear Least Squares 679 Permission is granted for internet users to make one paper copy for their own personal use. Further reproduction, or any copyin Copyright (C) 1988-1992 by Cambridge University Press. Programs Copyright (C) 1988-1992 by Numerical Recipes Software. Sample page from NUMERICAL RECIPES IN C: THE ART OF SCIENTIFIC COMPUTING (ISBN 0-521-43108-5) g of machinereadable files (including this one) to any server computer, is strictly prohibited. To order Numerical Recipes books or CDROMs, visit website http://www.nr.com or call 1-800-872-7423 (North America only), or send email to directcustserv@cambridge.org (outside North America). Feeding the matrix v and vector w output by the above program into the following short routine, you easily obtain variances and covariances of the fitted parameters a. The square roots of the variances are the standard deviations of the fitted parameters. The routine straightforwardly implements equation (15.4.20) above, with the convention that singular values equal to zero are recognized as having been edited out of the fit. #include "nrutil.h" void svdvar(float **v, int ma, float w[], float **cvm) To evaluate the covariance matrix cvm[1..ma][1..ma] of the fit for ma parameters obtained by svdfit, call this routine with matrices v[1..ma][1..ma], w[1..ma] as returned from svdfit. { int k,j,i; float sum,*wti; wti=vector(1,ma); for (i=1;i<=ma;i++) { wti[i]=0.0; if (w[i]) wti[i]=1.0/(w[i]*w[i]); } for (i=1;i<=ma;i++) { Sum contributions to covariance matrix (15.4.20). for (j=1;j<=i;j++) { for (sum=0.0,k=1;k<=ma;k++) sum += v[i][k]*v[j][k]*wti[k]; cvm[j][i]=cvm[i][j]=sum; } } free_vector(wti,1,ma); } Examples Be aware that some apparently nonlinear problems can be expressed so that they are linear. For example, an exponential model with two parameters a and b, y(x) = a exp(−bx) (15.4.21) can be rewritten as log[y(x)] = c − bx (15.4.22) which is linear in its parameters c and b. (Of course you must be aware that such transformations do not exactly take Gaussian errors into Gaussian errors.) Also watch out for “non-parameters,” as in y(x) = a exp(−bx + d) (15.4.23) Here the parameters a and d are, in fact, indistinguishable. This is a good example of where the normal equations will be exactly singular, and where SVD will find a zero singular value. SVD will then make a “least-squares” choice for setting a balance between a and d (or, rather, their equivalents in the linear model derived by taking the logarithms). However — and this is true whenever SVD gives back a zero singular value — you are better advised to figure out analytically where the degeneracy is among your basis functions, and then make appropriate deletions in the basis set. Here are two examples for user-supplied routines funcs. The first one is trivial and fits a general polynomial to a set of data:
680 Chapter 15.Modeling of Data void fpoly(float x,float p[],int np) Fitting routine for a polynomial of degree np-1,with coefficients in the array p[1..np]. int ji p[1]=1.0: for (j=2;j2)[ twox=2.0*x; f2=x; d=1.0: server computer, (North America University Press. THE for (j=3;j<=nl;j++){ make one paper f1=d++; ART f2 +tvox; p1[j]=(f2*p1[j-1]-f1*p1[j-2])/d; strictly proh Programs 22 to dir Multidimensional Fits OF SCIENTIFIC COMPUTING(ISBN If you are measuring a single variable y as a function of more than one variable 17881992b -say,a vector of variables x,then your basis functions will be functions of a vector, X(x),...,X(x).The x2 merit function is now Numerical 10-621 k1akXk(x)》 43108 (15.4.24) 0 All of the preceding discussion goes through unchanged,with x replaced by x.In (outside Recipes fact,if you are willing to tolerate a bit of programming hack,you can use the above North Software. programs without any modification:In both lfit and svdfit,the only use made of the array elementsx[i]is that each element is in turn passed to the user-supplied routine funcs,which duly gives back the values of the basis functions at that point. If you set x[i]=i before calling lfit or svdfit,and independently provide funcs machine with the true vector values of your data points(e.g.,in global variables),then funcs can translate from the fictitious x [i]'s to the actual data points before doing its work. CITED REFERENCES AND FURTHER READING: Bevington,P.R.1969,Data Reduction and Error Analysis for the Physical Sciences (New York: McGraw-Hill),Chapters 8-9
680 Chapter 15. Modeling of Data Permission is granted for internet users to make one paper copy for their own personal use. Further reproduction, or any copyin Copyright (C) 1988-1992 by Cambridge University Press. Programs Copyright (C) 1988-1992 by Numerical Recipes Software. Sample page from NUMERICAL RECIPES IN C: THE ART OF SCIENTIFIC COMPUTING (ISBN 0-521-43108-5) g of machinereadable files (including this one) to any server computer, is strictly prohibited. To order Numerical Recipes books or CDROMs, visit website http://www.nr.com or call 1-800-872-7423 (North America only), or send email to directcustserv@cambridge.org (outside North America). void fpoly(float x, float p[], int np) Fitting routine for a polynomial of degree np-1, with coefficients in the array p[1..np]. { int j; p[1]=1.0; for (j=2;j 2) { twox=2.0*x; f2=x; d=1.0; for (j=3;j<=nl;j++) { f1=d++; f2 += twox; pl[j]=(f2*pl[j-1]-f1*pl[j-2])/d; } } } Multidimensional Fits If you are measuring a single variable y as a function of more than one variable — say, a vector of variables x, then your basis functions will be functions of a vector, X1(x),...,XM(x). The χ2 merit function is now χ2 = N i=1 yi − M k=1 akXk(xi) σi 2 (15.4.24) All of the preceding discussion goes through unchanged, with x replaced by x. In fact, if you are willing to tolerate a bit of programming hack, you can use the above programs without any modification: In both lfit and svdfit, the only use made of the array elements x[i] is that each element is in turn passed to the user-supplied routine funcs, which duly gives back the values of the basis functions at that point. If you set x[i]=i before calling lfit or svdfit, and independently provide funcs with the true vector values of your data points (e.g., in global variables), then funcs can translate from the fictitious x[i]’s to the actual data points before doing its work. CITED REFERENCES AND FURTHER READING: Bevington, P.R. 1969, Data Reduction and Error Analysis for the Physical Sciences (New York: McGraw-Hill), Chapters 8–9.