我设法创建了一种算法,该算法使用了Matlab支持的更多矢量化属性。我的算法与您的算法有些不同,但是您可以按照要求进行梯度下降过程。经过我的执行和验证(使用polyfit函数)后,我认为变量θ(0.0)= 0.0745和θ(1)= 0.3800所期望的openclassroom(练习2)中的值在经过1500次迭代后是错误的0.07(我不对此做出回应)。这就是为什么我用一个绘图中的数据绘制我的结果,而用另一绘图中的数据绘制您的结果的原因,并且我发现数据拟合过程存在很大差异。
首先看一下代码:
% Machine Learning : Linear Regression
clear all; close all; clc;
%% ======================= Plotting Training Data =======================
fprintf('Plotting Data ...\n')
x = load('ex2x.dat');
y = load('ex2y.dat');
% Plot Data
plot(x,y,'rx');
xlabel('X -> Input') % x-axis label
ylabel('Y -> Output') % y-axis label
%% =================== Initialize Linear regression parameters ===================
m = length(y); % number of training examples
% initialize fitting parameters - all zeros
theta=zeros(2,1);%theta 0,1
% Some gradient descent settings
iterations = 1500;
Learning_step_a = 0.07; % step parameter
%% =================== Gradient descent ===================
fprintf('Running Gradient Descent ...\n')
%Compute Gradient descent
% Initialize Objective Function History
J_history = zeros(iterations, 1);
m = length(y); % number of training examples
% run gradient descent
for iter = 1:iterations
% In every iteration calculate hypothesis
hypothesis=theta(1).*x+theta(2);
% Update theta variables
temp0=theta(1) - Learning_step_a * (1/m)* sum((hypothesis-y).* x);
temp1=theta(2) - Learning_step_a * (1/m) *sum(hypothesis-y);
theta(1)=temp0;
theta(2)=temp1;
% Save objective function
J_history(iter)=(1/2*m)*sum(( hypothesis-y ).^2);
end
% print theta to screen
fprintf('Theta found by gradient descent: %f %f\n',theta(1), theta(2));
fprintf('Minimum of objective function is %f \n',J_history(iterations));
% Plot the linear fit
hold on; % keep previous plot visible
plot(x, theta(1)*x+theta(2), '-')
% Validate with polyfit fnc
poly_theta = polyfit(x,y,1);
plot(x, poly_theta(1)*x+poly_theta(2), 'y--');
legend('Training data', 'Linear regression','Linear regression with polyfit')
hold off
figure
% Plot Data
plot(x,y,'rx');
xlabel('X -> Input') % x-axis label
ylabel('Y -> Output') % y-axis label
hold on; % keep previous plot visible
% Validate with polyfit fnc
poly_theta = polyfit(x,y,1);
plot(x, poly_theta(1)*x+poly_theta(2), 'y--');
% for theta values that you are saying
theta(1)=0.0745; theta(2)=0.3800;
plot(x, theta(1)*x+theta(2), 'g--')
legend('Training data', 'Linear regression with polyfit','Your thetas')
hold off
好的结果如下:
结果,根据我的算法生成的theta(0)和theta(1),该行适合数据。
结果将theta(0)和theta(1)设为固定值,因此该行不适合数据。
0
我在堆栈溢出中经历了很多代码,并在同一行上编写了自己的代码。这段代码有些问题,我无法理解。我将存储值theta1和theta 2以及成本函数以进行分析。可以从此Openclassroom页面下载x和Y的数据。它具有.dat文件形式的x和Y数据,您可以在记事本中打开它们。
我得到的价值
这个值大约是我期望的两倍。