matlab - 使用批量梯度下降的错误权重

标签 matlab machine-learning linear-regression gradient-descent

我正在使用二维数据进行线性回归,但无法获得回归线的正确权重。 下面的代码似乎有问题,因为 回归线的计算权重不正确。 使用太大的数据值(x 约为 80000)会导致权重为 NaN。将数据从 0 缩放到 1,会导致权重错误,因为 回归线与数据不匹配。

function [w, epoch_batch, error_batch] = batch_gradient_descent(x, y)

% number of examples
q = size(x,1);

% learning rate
alpha = 1e-10;

w0 = rand(1);
w1 = rand(1);

curr_error = inf;
eps = 1e-7;

epochs = 1e100;
epoch_batch = 1;
error_batch = inf;
for epoch = 1:epochs
    prev_error = curr_error;
    curr_error = sum((y - (w1.*x + w0)).^2);
    w0 = w0 + alpha/q * sum(y - (w1.*x + w0));
    w1 = w1 + alpha/q * sum((y - (w1.*x + w0)).*x);
    if ((abs(prev_error - curr_error) < eps))
        epoch_batch = epoch;
        error_batch = abs(prev_error - curr_error);
        break;
    end
end

w = [w0, w1];

你能告诉我我在哪里犯了错误吗,因为对我来说,经过数小时的尝试,它似乎是正确的。

数据:

x
   35680
   42514
   15162
   35298
   29800
   40255
   74532
   37464
   31030
   24843
   36172
   39552
   72545
   75352
   18031

y
    2217
    2761
     990
    2274
    1865
    2606
    4805
    2396
    1993
    1627
    2375
    2560
    4597
    4871
    1119

这是绘制数据的代码:

figure(1)
% plot data points
plot(x, y, 'ro');
hold on;
xlabel('x value');
ylabel('y value');
grid on;

% x vector from min to max data point
x = min(x):max(x);
% calculate y with weights from batch gradient descent
y = (w(1) + w(2)*x);
% plot the regression line
plot(x,y,'r');

可以使用较小的学习率 alpha = 1e-10 找到未缩放数据集的权重。 但是,当将数据从 0 缩放到 1 时,我仍然无法获得匹配的权重。

缩放_x =

0.4735
0.5642
0.2012
0.4684
0.3955
0.5342
0.9891
0.4972
0.4118
0.3297
0.4800
0.5249
0.9627
1.0000
0.2393

缩放_y_zh =

0.0294
0.0366
0.0131
0.0302
0.0248
0.0346
0.0638
0.0318
0.0264
0.0216
0.0315
0.0340
0.0610
0.0646
0.0149

最佳答案

问题出在 w1 上,因为您赋予它的权重过大。你不应该给 w0w1 相同的学习步骤,因为一个不乘以 x

如果我将 alpha/q 替换为 alpha^4/q(因为是随机选择),那么它会收敛:

enter image description here

关于matlab - 使用批量梯度下降的错误权重,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35844956/

相关文章:

machine-learning - 连接无输出的 Keras 模型

machine-learning - 需要取多少个主成分?

r - 如何使用 R 对两个回归的斜率进行韦尔奇 t 检验?

arrays - 如何找到矩阵中的唯一行,每行中没有元素顺序?

matlab - 整个循环完成后,在循环中绘制并保存绘图

matlab - 无法更改 Matlab 子图中的 xtick 字体大小

machine-learning - 包装方法中的特征选择和信息过滤?

matlab - 使用循环将元素添加到 MATLAB 中的现有向量

r - 几何段: Removed 1 rows containing missing values

python - 求解稀疏矩阵的线性回归方程