# matlab练习程序（加权最小二乘）

'andrews'w = (abs(r)<pi) .* sin(r) ./ r1.339
'bisquare' (default)w = (abs(r)<1) .* (1 - r.^2).^24.685
'cauchy'w = 1 ./ (1 + r.^2)2.385
'fair'w = 1 ./ (1 + abs(r))1.400
'huber'w = 1 ./ max(1, abs(r))1.345
'logistic'w = tanh(r) ./ r1.205
'ols'传统最小二乘估计 (无权重函数)
'talwar'w = 1 * (abs(r)<1)2.795
'welsch'w = exp(-(r.^2))2.985

clear all;
close all;
clc;

a=2;b=2;c=-3;d=1;e=2;f=30;   %系数
n=1:0.2:20;
x=repmat(n,96,1);
y=repmat(n',1,96);
z=a*x.^2+b*y.^2+c*x.*y+d*x+e*y +f;      %原始模型
surf(x,y,z)

N=100;
ind=int8(rand(N,2)*95+1);

X=x(sub2ind(size(x),ind(:,1),ind(:,2)));
Y=y(sub2ind(size(y),ind(:,1),ind(:,2)));
Z=z(sub2ind(size(z),ind(:,1),ind(:,2)))+rand(N,1)*20;       %生成待拟合点，加个噪声

Z(1:10)=Z(1:10)+400;                    %加入离群点

hold on;
plot3(X,Y,Z,'o');

XX=[X.^2 Y.^2 X.*Y X Y ones(100,1)];
YY=Z;

C=inv(XX'*XX)*XX'*YY;                                          %最小二乘
z=C(1)*x.^2+C(2)*y.^2+C(3)*x.*y+C(4)*x+C(5)*y +C(6);           %拟合结果
Cm=C;
mesh(x,y,z)

z=C(1)*X.^2+C(2)*Y.^2+C(3)*X.*Y+C(4)*X+C(5)*Y +C(6);
C0=C;
while 1
r = z-Z;
w = tanh(r)./r;                                             %权重函数
W=diag(w);

C=inv(XX'*W*XX)*XX'*W*YY;                                   %加权最小二乘
z=C(1)*X.^2+C(2)*Y.^2+C(3)*X.*Y+C(4)*X+C(5)*Y +C(6);        %拟合结果

if norm(C-C0)<1e-10
break;
end
C0=C;
end

z=C(1)*x.^2+C(2)*y.^2+C(3)*x.*y+C(4)*x+C(5)*y +C(6);           %拟合结果
mesh(x,y,z)

https://www.cnblogs.com/xiongyunqi/p/3737323.html

https://blog.csdn.net/baidu_35570545/article/details/55212241

04-17
08-28

06-02
08-29 1万+
02-24
04-18 1万+
06-22
02-26 2万+