第3章曲线拟合的最小二乘法
- 格式:ppt
- 大小:347.50 KB
- 文档页数:20


曲线拟合最小二乘法
曲线拟合是指通过已知数据点来推导出一条函数曲线,使得该曲线尽
可能地贴近这些数据点。
而最小二乘法(Least Squares Method)是求解
这种拟合问题的一种常用方法。
最小二乘法的核心思想是尽量减小误差平方和。
假设已知的数据点为$(x_i, y_i)$,曲线函数为 $y=f(x)$,我们希望找到一组参数 $\theta$,使得 $f(x_i;\theta)$ 与 $y_i$ 的差距最小,即:
$$\min_{\theta}\sum_{i=1}^n [y_i - f(x_i;\theta)]^2$$。
这个式子被称为目标函数,也叫做残差平方和(RSS)。
通过对目标
函数进行求导,可以得到最优参数 $\theta^*$ 的解析解:
$$\theta^* = (\mathbf{X}^T \mathbf{X})^{-1} \mathbf{X}^T
\mathbf{y}$$。
其中,$\mathbf{X}$ 是一个 $n \times p$ 的矩阵,每一行代表一
个数据点的特征向量,$p$ 是曲线函数的参数个数。
$\mathbf{y}$ 是一
个 $n \times 1$ 的列向量,代表数据点的真实输出值。
最小二乘法在实际应用中有很广泛的应用。
例如,可以用它来构建多
项式回归模型、高斯过程回归模型等。
此外,在机器学习领域,最小二乘
法也被用于求解线性回归模型、岭回归模型等。
Lab04.曲线拟合的最小二乘法实验【实验目的和要求】1.让学生体验曲线拟合的最小二乘法,加深对曲线拟合的最小二乘法的理解;2.掌握函数ployfit和函数lsqcurvefit功能和使用方法,分别用这两个函数进行多项式拟合和非多项式拟合。
【实验内容】1.在Matlab命令窗口,用help命令查询函数polyfit和函数lsqcurvefit 功能和使用方法。
2.用多项式y=x3-6x2+5x-3,产生一组数据(xi,yi)(i=1,2,…,n),再在yi上添加随机干扰(可用rand产生(0,1)均匀分布随机数,或用randn产生N(0,1)均匀分布随机数),然后对xi和添加了随机干扰的yi用Matlab提供的函数ployfit用3次多项式拟合,将结果与原系数比较。
再作2或4次多项式拟合,分析所得结果。
3.用电压V=10伏的电池给电容器充电,电容器上t时刻的电压为,其中V0是电容器的初始电压,τ是充电常数。
对于下面的一组t,v数据,用Matlab提供的函数lsqcurvefit确定V0和τ。
t(秒) 0.5 1 2 3 4 5 7 9v(伏) 6.36 6.48 7.26 8.22 8.66 8.99 9.43 9.63 【实验仪器与软件】1.CPU主频在1GHz以上,内存在128Mb以上的PC;2.Matlab 6.0及以上版本。
实验讲评:实验成绩:评阅教师:200 年月日问题及算法分析:1、利用help命令,在MATLAB中查找polyfit和lsqcurvefit函数的用法。
2、在一组数据(xi,yi)(i=1,2,…,n)上,对yi上添加随机干扰,运用多项式拟合函数,对数据进行拟合(分别用2次,3次,4次拟合),分析拟合的效果。
3、根据t和V的关系画散点图,再根据给定的函数运用最小二乘拟合函数,确定其相应参数。
第一题:(1)>> help polyfitPOLYFIT Fit polynomial to data.P = POLYFIT(X,Y,N) finds the coefficients of a polynomial P(X) ofdegree N that fits the data Y best in a least-squares sense. P is arow vector of length N+1 containing the polynomial coefficients indescending powers, P(1)*X^N + P(2)*X^(N-1) +...+ P(N)*X + P(N+1).[P,S] = POLYFIT(X,Y,N) returns the polynomial coefficients P and astructure S for use with POLYVAL to obtain error estimates forpredictions. S contains fields for the triangular factor (R) from a QRdecomposition of the Vandermonde matrix of X, the degrees of freedom(df), and the norm of the residuals (normr). If the data Y are random,an estimate of the covariance matrix of P is(Rinv*Rinv')*normr^2/df,where Rinv is the inverse of R.[P,S,MU] = POLYFIT(X,Y,N) finds the coefficients of a polynomial inXHAT = (X-MU(1))/MU(2) where MU(1) = MEAN(X) and MU(2) = STD(X). Thiscentering and scaling transformation improves the numerical propertiesof both the polynomial and the fitting algorithm.Warning messages result if N is >= length(X), if X has repeated, ornearly repeated, points, or if X might need centering and scaling.Class support for inputs X,Y:float: double, singleSee also poly, polyval, roots.Reference page in Help browserdoc polyfit>>(2)>> help lsqcurvefitLSQCURVEFIT solves non-linear least squares problems.LSQCURVEFIT attempts to solve problems of the form:min sum {(FUN(X,XDATA)-YDATA).^2} where X, XDATA, YDATA and the valuesX returned by FUN can be vectors ormatrices.X=LSQCURVEFIT(FUN,X0,XDATA,YDATA) starts at X0 and finds coefficients Xto best fit the nonlinear functions in FUN to the data YDATA (in theleast-squares sense). FUN accepts inputs X and XDATA and returns avector (or matrix) of function values F, where F is the same size asYDATA, evaluated at X and XDATA. NOTE: FUN should returnFUN(X,XDATA)and not the sum-of-squares sum((FUN(X,XDATA)-YDATA).^2).((FUN(X,XDATA)-YDATA) is squared and summed implicitly in thealgorithm.)X=LSQCURVEFIT(FUN,X0,XDATA,YDATA,LB,UB) defines a set of lower andupper bounds on the design variables, X, so that the solution is in therange LB <= X <= UB. Use empty matrices for LB and UB if no boundsexist. Set LB(i) = -Inf if X(i) is unbounded below; set UB(i) = Inf ifX(i) is unbounded above.X=LSQCURVEFIT(FUN,X0,XDATA,YDATA,LB,UB,OPTIONS) minimizes with thedefault parameters replaced by values in the structure OPTIONS, anargument created with the OPTIMSET function. See OPTIMSET for details.Used options are Display, TolX, TolFun, DerivativeCheck, Diagnostics,FunValCheck, Jacobian, JacobMult, JacobPattern, LineSearchType,LevenbergMarquardt, MaxFunEvals, MaxIter, DiffMinChange andDiffMaxChange, LargeScale, MaxPCGIter, PrecondBandWidth, TolPCG,OutputFcn, and TypicalX. Use the Jacobian option to specify that FUNalso returns a second output argument J that is the Jacobian matrix atthe point X. If FUN returns a vector F of m components when X has length n, then J is an m-by-n matrix where J(i,j) is the partialderivative of F(i) with respect to x(j). (Note that the Jacobian J isthe transpose of the gradient of F.)[X,RESNORM]=LSQCURVEFIT(FUN,X0,XDATA,YDATA,...) returns the valueof thesquared 2-norm of the residual at X: sum {(FUN(X,XDATA)-YDATA).^2}.[X,RESNORM,RESIDUAL]=LSQCURVEFIT(FUN,X0,...) returns the value of residual,FUN(X,XDATA)-YDATA, at the solution X.[X,RESNORM,RESIDUAL,EXITFLAG]=LSQCURVEFIT(FUN,X0,XDATA,YDATA,...) returnsan EXITFLAG that describes the exit condition of LSQCURVEFIT. Possiblevalues of EXITFLAG and the corresponding exit conditions are1 LSQCURVEFIT converged to a solution X.2 Change in X smaller than the specified tolerance.3 Change in the residual smaller than the specified tolerance.4 Magnitude of search direction smaller than the specified tolerance.0 Maximum number of function evaluations or of iterations reached.-1 Algorithm terminated by the output function.-2 Bounds are inconsistent.-4 Line search cannot sufficiently decrease the residual alongthecurrent search direction.[X,RESNORM,RESIDUAL,EXITFLAG,OUTPUT]=LSQCURVEFIT(FUN,X0,XDATA,YDATA ,...)returns a structure OUTPUT with the number of iterations taken inOUTPUT.iterations, the number of function evaluations inOUTPUT.funcCount,the algorithm used in OUTPUT.algorithm, the number of CG iterations (ifused) in OUTPUT.cgiterations, the first-order optimality (if used)inOUTPUT.firstorderopt, and the exit message in OUTPUT.message.[X,RESNORM,RESIDUAL,EXITFLAG,OUTPUT,LAMBDA]=LSQCURVEFIT(FUN,X0,XDAT A,YDATA,...)returns the set of Lagrangian multipliers, LAMBDA, at the solution:LAMBDA.lower for LB and LAMBDA.upper for UB.[X,RESNORM,RESIDUAL,EXITFLAG,OUTPUT,LAMBDA,JACOBIAN]=LSQCURVEFIT(FU N,X0,XDATA,YDATA,...)returns the Jacobian of FUN at X.ExamplesFUN can be specified using @:xdata = [5;4;6]; % example xdataydata = 3*sin([5;4;6])+6; % example ydatax = lsqcurvefit(@myfun, [2 7], xdata, ydata)where myfun is a MATLAB function such as:function F = myfun(x,xdata)F = x(1)*sin(xdata)+x(2);FUN can also be an anonymous function:x = lsqcurvefit(@(x,xdata) x(1)*sin(xdata)+x(2),[2 7],xdata,ydata)If FUN is parameterized, you can use anonymous functions to capture theproblem-dependent parameters. Suppose you want to solve the curve-fittingproblem given in the function myfun, which is parameterized by its secondargument c. Here myfun is an M-file function such asfunction F = myfun(x,xdata,c)F = x(1)*exp(c*xdata)+x(2);To solve the curve-fitting problem for a specific value of c, first assignthe value to c. Then create a two-argument anonymous function that capturesthat value of c and calls myfun with three arguments. Finally, pass thisanonymous function to LSQCURVEFIT:xdata = [3; 1; 4]; % example xdataydata = 6*exp(-1.5*xdata)+3; % example ydatac = -1.5; % define parameterx = lsqcurvefit(@(x,xdata) myfun(x,xdata,c),[5;1],xdata,ydata) See also optimset, lsqnonlin, fsolve, @, inline.Reference page in Help browserdoc lsqcurvefit>>第二题:1 三次线性拟合clear allx=0:0.5:5;y=x.^3-6*x.^2+5*x-3;y1=y;for i=1:length(y)y1(i)=y1(i)+rand;enda=polyfit(x,y1,3);b=polyval(a,x);plot(x,y,'*',x,b),aa =1.0121 -6.1033 5.1933 -2.4782② 二次线性拟合clear allx=0:0.5:20;y=x.^3-6*x.^2+5*x-3;y1=y;for i=1:length(y)y1(i)=y1(i)+rand;enda=polyfit(x,y1,2);b=polyval(a,x);plot(x,y,'*',x,b),aa =23.9982 -232.0179 367.9756③ 四次线性拟合clear allx=0:0.5:20;y=x.^3-6*x.^2+5*x-3;y1=y;for j=1:length(y)y1(j)=y1(j)+rand;enda=polyfit(x,y1,4);b=polyval(a,x);plot(x,y,'*',x,b),aa =-0.0001 1.0038 -6.0561 5.2890 -2.8249 >>第三题:1 拟合曲线为:f(x)=定义函数:function f=fun(a,x)f=a(1)-(a(1)-a(2))*exp(-a(3)*x);主程序:clear allclcx=[0.5 1 2 3 4 5 7 9];y=[6.36 6.48 7.26 8.22 8.66 8.99 9.43 9.63];a0=[1 1 1];a=lsqcurvefit('fun',a0,x,y);y1=a(1)-(a(1)-a(2))*exp(-a(3)*x);plot(x,y,'r*',x,y1,'b')V1=a(2)tei=1/a(3)Optimization terminated: relative function value changing by less than OPTIONS.TolFun.。