吴恩达机器学习作业讲解(含代码)——ex1(线性回归)

详细代码链接:h5ww


Programming Exercise 1: Linear Regression


Files included in this exercise

 你必须要完成以下的函数:

  •  warmUpExercise.m - 简单的样例函数
  •  plotData.m  - 显示数据集的函数
  •  computeCost.m - 线性回归的代价函数
  •  gradientDescent.m - 执行梯度下降算法

你可以额外完成以下函数:

  • computeCostMulti.m - 多元变量的代价函数
  • gradientDescentMulti.m - 多元变量的梯度下降
  • featureNormalize.m - 变量正规化
  • normalEqn.m - 计算正规方程

warmUpExercise.m

要求返回一个5x5的单位向量,文档里给了代码.


% ============= YOUR CODE HERE ==============
% Instructions: Return the 5x5 identity matrix 
%               In octave, we return values by defining which variables
%               represent the return values (at the top of the file)
%               and then set them accordingly. 

A = eye(5);

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

 plotData.m

要求在坐标图上画出每个数据点,文档中也同样给出了代码

figure; % 打开新的窗口
% ====================== 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);
% plot(x,y,点的样式(r=red,x为叉型),标记大小,设置标记大小为10)
ylabel('Profit in $10,000s');
% 设置y轴标签
xlabel('Population of City in 10,000s');
% 设置x轴标签
% ============================================================

效果:

吴恩达机器学习作业讲解(含代码)——ex1(线性回归)_第1张图片


computeCost.m

复习一下线性回归的函数:

\small h_{\theta}(x)=\theta^{T} x=\theta_{0}+\theta_{1} x_{1}

J(\theta)=\frac{1}{2 m} \sum_{i=1}^{m}\left(h_{\theta}\left(x^{(i)}\right)-y^{(i)}\right)^{2}

data = load('ex1data1.txt');
X = data(:, 1); y = data(:, 2);
m = length(y); % number of training examples
...
X = [ones(m, 1), data(:,1)]; % Add a column of ones to x
theta = zeros(2, 1); % initialize fitting parameters
...
% compute and display initial cost
J = computeCost(X, y, theta);

从代码中看出X作为数据矩阵,大小为m \times(n+1),y矩阵大小为m \times 1,theta(\theta)大小为(n+1) \times 1.

我们直接利用线性代数只通过一次矩阵运算直接获得J(\theta)的值。

h_{\theta}\left(x^{(i)}\right)-y^{(i)},直接一步到位等于 X^{*} \theta^{T}-y   (m \times 1)

\small \sum_{i=1}^{m}\left(h_{\theta}\left(x^{(i)}\right)-y^{(i)}\right)^{2} 等于\small \small \left(X* \theta^{T}-y\right)^{T }*\left(X* \theta^{T}-y\right)

\small (1 \times m) *(m \times 1)=1 \times 1这是矩阵的乘法运算规律,得到的是一个数。

最后这个数除2*m即可。

% ====================== YOUR CODE HERE ======================
% Instructions: Compute the cost of a particular choice of theta
%               You should set J to the cost.
% x*theta get Matrix m*1
x= X*theta-y;
J=(x'*x)/(2*m);
% =========================================================================

gradientDescent.m

梯度下降的更新公式:\small \theta_{j} :=\theta_{j}-\alpha \frac{1}{m} \sum_{i=1}^{m}\left(h_{\theta}\left(x^{(i)}\right)-y^{(i)}\right) x_{j}^{(i)} \quad\left(\text { simultaneously update } \theta_{j} \text { for all } j\right)

\small \alpha是学习率(一般取小数),\small \frac{1}{m} \sum_{i=1}^{m}\left(h_{\theta}\left(x^{(i)}\right)-y^{(i)}\right) x_{j}^{(i)}是对\small J(\theta)求偏导后的结果。

注意的是所有的\small \theta_{j}需要同时更新,同一次迭代中的\small \theta_{j}是不相互影响的。

同样为了运算的直观和方便,也可直接使用矩阵运算,一次运算的到结果。

\small \left(h_{\theta}\left(x^{(i)}\right)-y^{(i)}\right)  是X* \theta^{T}-y (m \times 1)。

X^{*} \theta^{T}-y要对\small X中每一列都进行一次求内积。然而\small \theta是一个(n+1) \times 1的列向量,所以\small X先对转置[m \times(n+1)--(n+1) \times m],在和X^{*} \theta^{T}-y相乘。

结果是\small \theta=\theta-\alpha \frac{1}{m}\left(X^{T}*\left(X*\theta^{T}-y\right)\right)

for iter = 1:num_iters

    % ====================== YOUR CODE HERE ======================
    % Instructions: Perform a single gradient step on the parameter vector
    %               theta. 
    %
    % Hint: While debugging, it can be useful to print out the values
    %       of the cost function (computeCost) and gradient here.
    %
 
    x=(alpha*(1/m))*(X'*((X*theta)-y));
    theta=theta-x;
    % ============================================================

    % Save the cost J in every iteration    
    J_history(iter) = computeCost(X, y, theta);

end

computeCostMulti.m

多元线性回归的代价函数计算与2元的计算公式 一样。我是利用矩阵运算的,所以不管是多少位变量,都可以一次计算成功。

代码和 computeCost.m 中一样。

% ====================== YOUR CODE HERE ======================
% Instructions: Compute the cost of a particular choice of theta
%               You should set J to the cost.
% x*theta get Matrix m*1
x= X*theta-y;
J=(x'*x)/(2*m);
% =========================================================================

gradientDescentMulti.m

矩阵运算优越性就是这样,代码还是一样。

  x=(alpha*(1/m))*(X'*((X*theta)-y));
  theta=theta-x;

featureNormalize.m

变量过多也带来了很多问题,不同变量的大小范围是不同的。比如\begin{array}{l}{x_{1}\left(0<x_{1}<1\right)} \\ {x_{2}\left(1000<x_{2}<10000\right)}\end{array} ,但是在梯度下降更新中学习率\small \alpha一般都是0<\small \alpha<1的,这个导致了在x_{2}对应的\theta_{2}更新很慢。这个导致了整体效率的降低。于是,我们引入变量归一化。归一化的目的是把数变为(0,1)之间的小数。这样我们的更新效率会有所提高。

归一化的公式是:t=\frac{x-\mu}{\sigma}x是被归一化的变量集合,\mux的平均值,\sigmax的标准差或偏差。

这里我们使用标准差。MATLAB中使用mean(x),std(x)分别求均值\mu和标准差\sigma

%遍历X的每一列,对每一列求均值和标准差
%均值存在mu中,标准差存在sigma中,归一化结果存在X_norm中
for i=1:size(X,2)
	mu(i)=mean(X(:,i));
	sigma(i)=std(X(:,i));
	X_norm(:,i)=(X(:,i)-mu(i))/sigma(i);
end

normalEqn.m

吴恩达在课程中讲过正规方程一步求解最有解的方法。

\theta=\left(X^{T} X\right)^{-1} X^{T} y

这个方法通常在X大小适中的时候使用,否在效率会比梯度下降低。

n是指变量的个数。

吴恩达机器学习作业讲解(含代码)——ex1(线性回归)_第2张图片

% ---------------------- Sample Solution ----------------------
theta=pinv((X'*X))*X'*y;
% -------------------------------------------------------------

吴恩达机器学习作业讲解(含代码)——ex1(线性回归)_第3张图片

你可能感兴趣的:(机器学习,吴恩达机器学习作业讲解)