如何正确实现随机梯度下降?

时间:2019-04-19 06:02:29

标签: matlab machine-learning artificial-intelligence linear-regression

我正在尝试在MATLAB中实现随机梯度下降,但是我没有看到任何收敛。小批量梯度下降按预期方式工作,因此我认为成本函数和梯度步长是正确的。

我遇到的两个主要问题是:

  1. 在训练集之前随机对数据进行改组 for循环
  2. 一次选择一个示例

这是我的MATLAB代码:

生成数据

alpha = 0.001;
num_iters = 10;

xrange =(-10:0.1:10); % data lenght
ydata  = 5*(xrange)+30; % data with gradient 2, intercept 5

% plot(xrange,ydata); grid on;
noise  = (2*randn(1,length(xrange))); % generating noise 
target = ydata + noise; % adding noise to data

f1 = figure
subplot(2,2,1);
scatter(xrange,target); grid on; hold on; % plot a scttaer
title('Linear Regression')
xlabel('xrange')
ylabel('ydata')

tita0 = randn(1,1); %intercept (randomised)
tita1 = randn(1,1); %gradient  (randomised)

% Initialize Objective Function History
J_history = zeros(num_iters, 1);

% Number of training examples
m = (length(xrange));

混排数据,梯度下降和成本函数

% STEP1 : we shuffle the data
data = [ xrange, ydata];
data = data(randperm(size(data,1)),:);
y = data(:,1);
X = data(:,2:end);

for iter = 1:num_iters

    for i = 1:m

        x = X(:,i); % STEP2 Select one example

        h = tita0 + tita1.*x; % building the estimated     %Changed to xrange in BGD

        %c = (1/(2*length(xrange)))*sum((h-target).^2)

        temp0 = tita0 - alpha*((1/m)*sum((h-target)));
        temp1 = tita1 - alpha*((1/m)*sum((h-target).*x));  %Changed to xrange in BGD
        tita0 = temp0;
        tita1 = temp1;

        fprintf("here\n %d; %d", i, x)

    end

        J_history(iter) = (1/(2*m))*sum((h-target).^2); % Calculating cost from data to estimate

        fprintf('Iteration #%d - Cost = %d... \r\n',iter, J_history(iter));

end

在绘制成本与迭代的关系图和线性回归图时,MSE在420左右稳定(局部最小值?)。

enter image description here

另一方面,如果我重新运行完全相同的代码,但是使用批处理梯度下降法则可以获得可接受的结果。在批量梯度下降中,我将x更改为xrange

enter image description here

关于我在做什么错的任何建议?


编辑:

我还尝试使用以下方法选择随机索引:

f = round(1+rand(1,1)*201);        %generating random indexes 

然后选择一个示例:

x = xrange(f); % STEP2 Select one example

在假设和GD步骤中继续使用x也会产生420的费用。

1 个答案:

答案 0 :(得分:0)

首先,我们需要正确地随机整理数据:

data = [ xrange', target']; 
data = data(randperm(size(data,1)),:);

接下来,我们需要正确索引X和y:

y = data(:,2);
X = data(:,1);

然后在梯度下降期间,我需要基于不在target上的单个值进行更新,如下所示:

tita0 = tita0 - alpha*((1/m)*((h-y(i))));
tita1 = tita1 - alpha*((1/m)*((h-y(i)).*x));

上述变化使Theta收敛到[5,30]。