matlab练习_MATLAB教程-台大郭彦甫-第十四节,含练习答案
14-回歸與內插
一、Polynomial curve fitting(多項式曲線擬合)
(一)Simple Linear Regression(簡單線性回歸)
1、A bunch of data points(
)are collected(收集一些二維數據點)如體重(Height)和身高(Weith)
2、Assume
and are linearly correlated(假設x和y線性相關)(二)Linear Regression Formulation(線性回歸公式)
1、Define sum of squared errors(SSE):(定義平方誤差之和)
2、Given that the regression model:(假設回歸模型)
(三)Solving Least-squares Problem(最小二乘問題的求解)
1、SSE is minimized when its gradient with respect to each parameter is equal to zero:(當SSE相對于每個參數的梯度等于零時,SSE最小)
聯立二元一次方程式(四)Least-squares Solution(最小二乘解)
1、Suppose there exists N data points:(假設存在N個數據點:)
只有β0和β1是未知,其他均為已知(五)Polynomial Curve Fitting:polyfit()(多項式曲線擬合)
1、Curve fitting for polynomials of different orders(不同階多項式的曲線擬合)
示例代碼:
x = [-1.2 -0.5 0.3 0.9 1.8 2.6 3.0 3.5]; y = [-15.6 -8.5 2.2 4.5 6.6 8.2 8.9 10.0]; fit = polyfit(x,y,1);%order,1次方的多項式 %poly會產生兩個值fit(1)和fit(2)對應斜率和截距 %% 繪制圖形 xfit = x(1):0.1:x(end); %即xfit = [-1.2 -1.1 -1.0 ... 3.5] yfit = fit(1) * xfit + fit(2); %即y = ax + b plot(x,y,'ro',xfit,yfit); set(gca,'FontSize',14); legend('data points','best-fit','Location','northwest');輸出代碼:
(六)Excise
1、Given the table below:
(1)Find the
和 of the regression line(找到回歸線)(2)Plot the figure
答案代碼:
TC = [0.025 0.035 0.050 0.060 0.080]; T = [20 30 40 50 60]; fit = polyfit(T,TC,1)Tfit = T(1):0.01:T(end); TCfit = fit(1) * Tfit + fit(2); plot(T,TC,'ko',Tfit,TCfit,'r','LineWidth',2); set(gca,'FontSize',14); grid on; set(gca,'GridLineStyle','--'); %設置網格線為虛線 xlabel('Temperature(^oC)'); ylabel('TC output(mV)'); title('Calibration of TC')輸出結果:
(七)Area x and y Linearly Correlated(區域x和y是否線性相關?)
1、If not,the line may not well describe their relationship(擬合的線或許不能很好的描述他們之間關系)
2、Check the linearity by using (檢查他們的線性關系使用)
(1)scatter():scatterplot(散點圖)
(2)corrcoef():correlation coefficient,-1≤r≤1(相關系數,很強的正相關接近1,很強負相關-1)
示例代碼:
x = [-1.2 -0.5 0.3 0.9 1.8 2.6 3.0 3.5]; y = [-15.6 -8.5 2.2 4.5 6.6 8.2 8.9 10.0]; scatter(x,y);%散點圖 box on; axis square; corrcoef(x,y)%相關系數輸出結果:
注意:
corrcoef(x,y)%相關系數
(八)Higher Order Polynomials(高階多項式)
示例代碼:
x = [-1.2 -0.5 0.3 0.9 1.8 2.6 3.0 3.5]; y = [-15.6 -8.5 2.2 4.5 6.6 8.2 8.9 10.0]; figure('Position',[50 50 1500 400]);%可繪制區域的位置和大小 for i = 1:3subplot(1,3,i);p = polyfit(x,y,i);%多項式曲線擬合 %i = 1:3 分別畫出了1次擬合,2次擬合,3次擬合 %擬合階數越高,平均差值越小xfit = x(1):0.1:x(end);yfit = polyval(p,xfit);%多項式計算plot(x,y,'ro',xfit,yfit);set(gca,'FontSize',14);ylim([-17,11]);legend('Data points','Fitted curve','Location','southeast'); end輸出結果:
注意:
(1)figure('Position',[50501500400]);%可繪制區域的位置和大小
(2) p =polyfit(x,y,i);%多項式曲線擬合
(3)yfit =polyval(p,xfit);%多項式計算
(九)Excise
1、Find the
-order polynomials2、Is it better to use higher order polynomials?(錯,可能過擬合)
答案代碼:
x = [-1.2 -0.5 0.3 0.9 1.8 2.6 3.0 3.5]; y = [-15.6 -8.5 2.2 4.5 6.6 8.2 8.9 10.0]; figure('Position',[50 50 1500 400]); for i = 4:6subplot(1,3,i-3);%由于與order用的是同樣的變量,所以只需減掉多的3階即可p = polyfit(x,y,i);xfit = x(1):0.1:x(end);yfit = polyval(p,xfit);plot(x,y,'ro',xfit,yfit);set(gca,'FontSize',14);ylim([-17,11]);legend('Data points','Fitted curve','Location','southeast'); end輸出結果:
二、Multiple regression(多元回歸)
(一)What If There Exists More Variables?(如果有更多的變量呢?)
1、Equations associated with more than one explanatory variables: (有多個解釋變量的相關方程)
2、Multiple linear regression:regress()(多元線性回歸)
3、Note:the function given you more statistics(e.g.,R2)of the regression model(該函數為您提供了回歸模型的更多統計信息)
(二)Multiple Linear Regression:regress()(多元線性回歸)
示例代碼:
load carsmall; y = MPG;%1加侖的汽油可以走多少英里 x1 = Weight;%重量 x2 = Horsepower;%馬力 X = [ones(length(x1),1) x1 x2];%增廣矩陣,第一行為1向量,即常數項 %即y = a + bx1 + cx2 b = regress(y,X);%多元線性回歸%% 繪制圖形 x1fit = min(x1):100:max(x1); x2fit = min(x2):10:max(x2); [X1FIT,X2FIT] = meshgrid(x1fit,x2fit); YFIT = b(1) + b(2) * X1FIT + b(3) * X2FIT; %即y = a + bx1 + cx2 scatter3(x1,x2,y,'filled'); %三維散點圖 %filled表示填充標記 hold on; mesh(X1FIT,X2FIT,YFIT); hold off; xlabel('Weight'); ylabel('Horsepower'); zlabel('MPG'); view(50,10);輸出結果:
注意:
(1)b= regress(y,X)返回向量b,其中包含向量y中的響應對矩陣X中的預測變量的多元線性回歸的系數估計值。要計算具有常數項(截距)的模型的系數估計值,請在矩陣X中包含一個由 1 構成的列。
(三)What If the Equations Area NOT Linear?(如果方程區域不是線性的呢)
1、What are linear equations?(什么是線性方程式)
2、How do we do curve fitting using nonlinear equations?(如何利用非線性方程進行曲線擬合)
(二)DC Motor System Identification(DC馬達系統辨識)
1、For a typical DC motor,the velocity
and displacement profile of a step responses of are(對一個典型的DC馬達,速度和位移關于時間的關系)2、The displacement
profile is:(求位移的方程,三個未知數 )where
is the time constant(β是時間的常數)(三)Curve Fitting Toolbox:cftool()(曲線擬合內件)
1、鍵入cftool
三、Interpolation(插值,或稱內插)
(一)Interpolation vs Regression(插值與回歸)
1、Interpolation(插值)
(1)The process of finding an approximation of a function(求函數逼近的過程)
(2)The fit does traverse all known points(擬合會遍歷所有已知點)
2、Regression(回歸)
(1)The process of finding a curve of best fit(尋找最佳擬合曲線的過程)
(2)The fit generally does not pass through the data points(擬合通常不通過數據點)
(二)Common Interpolation Approaches(常用插值方法)
1、piecewise linear interpolation(分段線性插值)
2、piecewise cubic polynomial interpolation(分段三次多項式插值)
3、Cubic spline interpolation(三次樣條插值)
(三)Linear Interpolation:interp1()(線性插值)
示例代碼:
%% 構造分散點 x = linspace(0,2 * pi,40);%在0到2pi之間生成間隔相同的40個點 x_m = x; x_m([11:13,28:30]) = NaN;%手動將11-13,28-30這6個點變為空,制造下圖中的斷點 y_m = sin(x_m); %% 繪制圖形 plot(x_m,y_m,'ro','MarkerFaceColor','r'); xlim([0,2*pi]); ylim([-1.2,1.2]); box on; %set(gca,'FontName','symbol','FontSize',16);高版本不需要這一句 set(gca,'XTick',0:pi/2:2*pi); set(gca,'XTickLabel',{'0','pi/2','pi','3pi/2','2pi'}); %% 內插 m_i = ~isnan(x_m); %'~':表示取非,這里是將右邊判斷空值所形成的數組取非后賦值給左邊 %isnan():確定哪些數組元素為 NaN y_i = interp1(x_m(m_i),...y_m(m_i),x); %interp1():一維數據插值(表查找) hold on; plot(x,y_i,'-b',...'LineWidth',2); hold off;輸出結果:
注意:
(1)‘~’表示取非,這里是將右邊判斷空值所形成的數組取非后賦值給左邊
(2)TF= isnan(A)返回一個邏輯數組,其中的1(true) 對應A中的NaN元素,0(false) 對應其他元素。如果A包含復數,則isnan(A)中的1對應實部或虛部為NaN值的元素,0對應實部和虛部均非NaN值的元素。
(3)vq = interp1(x,v,xq) 使用線性插值返回一維函數在特定查詢點的插入值。向量 x 包含樣本點,v 包含對應值 v(x)。向量 xq 包含查詢點的坐標。
如果您有多個在同一點坐標采樣的數據集,則可以將 v 以數組的形式進行傳遞。數組 v 的每一列都包含一組不同的一維樣本值。
(四)Spline Interpolation:spline()(樣條插值)
示例代碼:
x = linspace(0,2 * pi,40); x_m = x; x_m([11:13,28:30]) = NaN; y_m = sin(x_m); plot(x_m,y_m,'ro','MarkerFaceColor','r');%繪制散點圖 xlim([0,2*pi]); ylim([-1.2,1.2]); box on; %set(gca,'FontName','symbol','FontSize',16);高版本不需要這一句 set(gca,'XTick',0:pi/2:2*pi); set(gca,'XTickLabel',{'0','pi/2','pi','3pi/2','2pi'}); %% 內插 m_i = ~isnan(x_m); y_i1 = spline(x_m(m_i),y_m(m_i),x);%使用內插值線段連接 y_i2 = interp1(x_m(m_i),y_m(m_i),x);%使用樣條差值連接 hold on; plot(x,y_i1,'-b','LineWidth',2);% plot(x,y_i2,'-g','LineWidth',2); hold off; h = legend('Original','Linear','Spline'); set(h,'FontName','Times New Roman');輸出結果:
(五)What Are Splines?
1、Piecewise polynomial functions(分段多項式函數)
(六)Excise
1、Fit the data using linear lines and cubic splines(用直線和三次樣條擬合數據)
答案代碼:
x = [0 0.25 0.75 1.25 1.5 1.75 1.875 2 2.125 2.25]; y = [1.2 1.18 1.1 1 0.92 0.8 0.7 0.55 0.35 0]; x_i = 0:0.1:2.5; hold on plot(x,y,'bo');%繪制散點圖 xlim([0,2.5]); ylim([0,1.4]); box on; y_i1 = interp1(x,y,x_i);%使用內插值線段連接 y_i2 = interp1(x,y,x_i,'spine');%使用樣條差值連接 plot(x_i,y_i2,'r','linewidth',1); plot(x_i,y_i1,'c'); xlabel('x(ft)'); ylabel('y(ft)'); title('Data & Fit Model'); set(gca,'fontsize',14); legend('Data','Linear','Spline') hold off輸出結果:
(七)Cubic Spline vs. Hermite Polynomial(三次樣條曲線與埃爾米特多項式)
1、p = pchip(x,y,t);:Hermite Polynomial,埃爾米特多項式
最大的不同在于,埃爾米特多項式在點和點連接曲線不會片離連接的線段
埃爾米特多項式_百度百科?baike.baidu.com示例代碼:
x = -3:3; y = [-1 -1 -1 0 1 1 1]; t = -3:.01:3; s = spline(x,y,t);%spline多項式 p = pchip(x,y,t);%埃爾米特多項式 hold on; plot(x,y,'ro','MarkerFaceColor','r'); plot(t,s,':g','LineWidth',2); plot(t,p,'--b','LineWidth',2); hold off; box on; set(gca,'FontSize',16); h = legend('Original','Spline','Hermite','Location','northwest'); %注意,標的順序與繪圖的先后順序相同輸出結果:
(八)2D Interpolation:interp2()(二維插值)
示例代碼:
%% 原本的數據圖 subplot(1,2,1); xx = -2:.5:2; yy = -2:.5:3; [X,Y] = meshgrid(xx,yy); Z = X .* exp(-X .^ 2 - Y .^ 2); surf(X,Y,Z); hold on; plot3(X,Y,Z+0.01,'ok',...'MarkerFaceColor','r') title('Origin');%% 線性內插 subplot(1,2,2); xx_i = -2:.1:2; yy_i = -2:.1:3; [X_i,Y_i] = meshgrid(xx_i,yy_i); Z_i = interp2(xx,yy,Z,X_i,Y_i); surf(X_i,Y_i,Z_i); hold on; plot3(X,Y,Z+0.01,'ok',...'MarkerFaceColor','r') title('Linear');輸出結果:
(九)2D Interpolation Using Spline(端點處圓潤很多)
示例代碼:
xx = -2:.5:2; yy = -2:.5:3; [X,Y] = meshgrid(xx,yy); Z = X .* exp(-X .^ 2 - Y .^ 2); xx_i = -2:.1:2; yy_i = -2:.1:3; [X_i,Y_i] = meshgrid(xx_i,yy_i); Z_e = interp2(xx,yy,Z,X_i,Y_i,'cubic'); surf(X_i,Y_i,Z_e); hold on; plot3(X,Y,Z+0.01,'ok',...'MarkerFaceColor','r') title('Spline');輸出結果:
第十四節結束
總結
以上是生活随笔為你收集整理的matlab练习_MATLAB教程-台大郭彦甫-第十四节,含练习答案的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 如何避免家里的厨房油烟机油腻?
- 下一篇: 50瓷砖背胶的价格是多少?贵的有哪些高端