(MATLAB) Unary linear regression and multiple linear regression
1. Unary linear regression
Look directly at the code, the goal is to build yyy andxxThe functional relationship of x , that is,y = kx + by=kx+band=kx+b inkkk andbbb, k k k andbbb are all real numbers.
% 用regress函数进行回归
x=[23.80,27.60,31.60,32.40,33.70,34.90,43.20,52.80,63.80,73.40];
y=[41.4,51.8,61.70,67.90,68.70,77.50,95.90,137.40,155.0,175.0];
figure
plot(x,y,'r*') %作散点图(制定横纵坐标)
xlabel('x')
ylabel('y')
Y=y';
X=[ones(size(x,2),1),x'];
[b,bint,r,rint,s]=regress(Y,X);
hold on
plot(x,b(1)+b(2)*x)
title("预测结果")
figure
rcoplot(r,rint) % 残差分析
The output result b is the coefficient matrix, this question b=[-23.5493,2.791] , then the predicted result is y = -23.5493+2.7991x
The prediction results and scatter plot are as follows:
The residual analysis diagram is as follows. It can be seen that there is only one abnormal point and the fitting effect is good.
2. Multiple linear regression
2.1 Data description
Part of the data data is shown in the figure below:
Imported into MATLAB, the data is a matrix of 200 rows and 4 columns, where there are 3 variables x 1, x 2, x 3 x_1,x_2,x_3x1,x2,x3, Each variable has 200 data, the last column of data represents yyy , the goal of multiple linear regression is to establishyyy andx 1, x 2, x 3 x_1,x_2,x_3x1,x2,x3The relationship between k 0, k 1, k 2, k 3 k_0,k_1,k_2,k_3k0,k1,k2,k3, Such that y = k 0 + k 1 x 1 + k 2 x 2 + k 3 x 3 y=k_0+k_1x_1+k_2x_2+k_3x_3and=k0+k1x1+k2x2+k3x3。
% 多元线性回归
a = load('data.txt');
x1=a(:,[1]) ;
x2=a(:,[2]) ;
x3=a(:,[3]) ;
y=a(:,[4]);
X=[ones(length(y),1), x1,x2,x3];
[b,bint,r,rint,stats]=regress(y,X);
b
rcoplot(r,rint)
2.2 Program running results
The result of solving b is as follows, so y = 2.9389 + 0.0458 x 1 + 0.1885 x 2 − 0.001 x 3 y=2.9389+0.0458x_1+0.1885x_2-0.001x_3and=2.9389+0.0458x1+0.1885x2−0.001x3
The residual analysis is as follows: