Coursera吴恩达machine-learning第一次作业回顾

每个项目老师都给我们写好了大致模板,我们需要完成的就是打开老师的文件然后在函数文件中写出函数
作业内容:根据目前已知的城市人口以及收益推断出在别的城市开餐馆能否盈利
作业目的:根据给出的数据集来训练一个算法模型,用来计算新给出的数据
%% ==================== Part 1: Basic Function ====================
% Complete warmUpExercise.m
比方说老师给的part1说的就是让我们打开warmUpExercise.m这个文件,写一个5*5的方阵并输出,主要目的应该是看看我们文件的本地运行有没有问题
%% ======================= Part 2: Plotting =======================
fprintf(‘Plotting Data …\n’)
data = load(‘ex1data1.txt’);% 下载数据
X = data(:, 1); y = data(:, 2);%导入X的值是数据data中的所有行第一列
m = length(y); % number of training examples求出m的值

% Plot Data
% Note: You have to complete the code in plotData.m
plotData(X, y);%调用函数plotData

fprintf(‘Program paused. Press enter to continue.\n’);
pause;%暂停

第二步是让我们完成画图函数,plotData.m就是我们要编写的文件

function plotData(x, y)
%PLOTDATA Plots the data points x and y into a new figure
% PLOTDATA(x,y) plots the data points and gives the figure axes labels of
% population and profit.

figure; % open a new figure window

% ====================== YOUR CODE HERE ======================
% Instructions: Plot the training data into a figure using the
% “figure” and “plot” commands. Set the axes labels using
% the “xlabel” and “ylabel” commands. Assume the
% population and revenue data have been passed in
% as the x and y arguments of this function.
%
% Hint: You can use the ‘rx’ option with plot to have the markers
% appear as red crosses. Furthermore, you can make the
% markers larger by using plot(…, ‘rx’, ‘MarkerSize’, 10);
plot(x, y, ‘rx’, ‘MarkerSize’, 10);%设置marker尺寸和颜色
ylabel(‘Profit in $10,000s’);%设置y坐标说明
xlabel(‘Population of City in 10,000s’);%设置x坐标说明

% ============================================================

end

这就是我们要编写的文件,因为在主函数中已经给了X,y赋值所以我们只需要在这里敲入:
plot(x, y, ‘rx’, ‘MarkerSize’, 10);%设置marker尺寸和颜色
ylabel(‘Profit in $10,000s’);%设置y坐标说明
xlabel(‘Population of City in 10,000s’);%设置x坐标说明
运行plotData函数会得到下图:
Coursera吴恩达machine-learning第一次作业回顾
图上的红叉代表的就是数据集的数据在图中的位置(横轴为人口,纵轴为收益额)
现在我们的目标就是写一个hypothesis(假设函数)去模拟数据的走向。我们只有一个特征量x,那么我们假定一个h(x)=θ0+θ1x
那么要怎么模拟数据的走向呢,简单的说就是我们假设函数的值与y值比较,它们之间的差值越小,那么就越接近真实值 代价函数J就是将所有的假设函数的值与y的差值相加,这个代价函数越小,数据就越拟合。
这里还有一个变量就是θ0和θ1,我们假设他们的初值为0,然后开始进行迭代,每次迭代我们会更新一个新的θ0和θ1的值,直至到达全局最优点。
接下来是代码部分,在computeCost.m文件中添加代价函数J
J=sum((X
theta-y).^2)/(2m);
在gradientDescent.m(梯度下降)函数中计算每个更新后的θ0和θ1的值重新赋值给θ0和θ1
Errors=X
theta-y;
delta=(X’Errors)/m;
theta=theta-delta
alpha;
这段不懂的可以看看他的博

然后画折线图
plot(X(:,2), X*theta, ‘-’) 横坐标就是X的值,纵坐标是计算后的值
图长这样
Coursera吴恩达machine-learning第一次作业回顾
得到这个图线性回归就差不多结束了。。。