鲁棒学习:Huber损失最小化
程序员文章站
2024-02-13 14:34:04
...
clear; clc;
n = 10;
N = 1000;
x = linspace(-3, 3, n)';
X = linspace(-4, 4, N)';
rng('default');
y = x + 0.1*randn(n,1);
y(n) = -4; % 异常值
p(:, 1) = ones(n, 1);
p(:, 2) = x;
t0 = p\y; % 计算拟合系数
e = 1; % 阈值设定
for o = 1 : 1000
r = abs(p*t0 - y); % 残差
w = ones(n, 1);
w(r > e) = e ./ r(r > e); % 残差大于阈值的情况
t = (p'*(repmat(w, 1, 2) .* p)) \ (p'*(w.*y));
if norm(t - t0) < 1e-3
break
end
t0 = t;
end
P(:, 1) = ones(N, 1);
P(:, 2) = X;
F = P*t;
hold on;
axis([-4 4 -4.5 3.5]);
plot(X, F, 'g', 'LineWidth', 2);
plot(x, y, 'ob', 'LineWidth', 2);