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

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

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

  1. 在for循环之前随机打乱训练集中的数据
  2. 每次选择一个样本

这是我的MATLAB代码:

生成数据

alpha = 0.001;num_iters = 10;xrange =(-10:0.1:10); % data lenghtydata  = 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 dataf1 = figuresubplot(2,2,1);scatter(xrange,target); grid on; hold on; % plot a scttaertitle('Linear Regression')xlabel('xrange')ylabel('ydata')tita0 = randn(1,1); %intercept (randomised)tita1 = randn(1,1); %gradient  (randomised)% Initialize Objective Function HistoryJ_history = zeros(num_iters, 1);% Number of training examplesm = (length(xrange));

打乱数据、梯度下降和成本函数

% STEP1 : we shuffle the datadata = [ 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

在绘制成本与迭代次数以及线性回归图时,均方误差稳定在约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的成本。


回答:

首先我们需要正确地打乱数据:

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]。

Related Posts

使用LSTM在Python中预测未来值

这段代码可以预测指定股票的当前日期之前的值,但不能预测…

如何在gensim的word2vec模型中查找双词组的相似性

我有一个word2vec模型,假设我使用的是googl…

dask_xgboost.predict 可以工作但无法显示 – 数据必须是一维的

我试图使用 XGBoost 创建模型。 看起来我成功地…

ML Tuning – Cross Validation in Spark

我在https://spark.apache.org/…

如何在React JS中使用fetch从REST API获取预测

我正在开发一个应用程序,其中Flask REST AP…

如何分析ML.NET中多类分类预测得分数组?

我在ML.NET中创建了一个多类分类项目。该项目可以对…

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注