Ng机器学习课程.docx
《Ng机器学习课程.docx》由会员分享,可在线阅读,更多相关《Ng机器学习课程.docx(25页珍藏版)》请在冰豆网上搜索。
Ng机器学习课程
Ng机器学习课程(http:
//cs229.stanford.edu/materials.html)Notes理论要点,并且给出所有课程exercise的作业code和实验结果分析。
”游泳是游会的“,希望通过这个系列可以深刻理解机器学习算法,并且自己动手写出work高效的机器学习算法code应用到真实数据集做实验,理论和实战兼备。
Part1LinearRegression
1.SupervisedLearning
在SuperviseLearning的Setting中,我们有若干训练数据(x^(i),y^(i))i=1,...,m,这里i用于indextrainingexample。
监督学习的任务就是要找到一个函数(又称为模型或者假设hypothesis)H:
X->Y,使得h(x)是相应值y的好的预测。
整个过程可以描述为下图
当待预测的目标变量是连续型数据时,我们称之为回归(regression)问题;当待预测的目标变量是离散型数据时,我们称之为分类(classification)问题。
因此回归问题和分类问题是监督学习针对连续型数据预测和离散型数据预测的两种典型学习问题。
2LinearRegression
一般而言,我们会用feature向量来描述训练数据X,我们用x_j^i来表示,其中j用于indexfeature,i用于index训练样本。
在监督学习里面,我们需要找到一个最佳的预测函数h(x),比如我们可以选取feature的线性组合函数
那么我们的问题就变成了要寻找最优的参数\theta可以使得预测的error最小。
把这个函数用向量表示
机器学习里面一般默认变量为列向量,因此这里是参数向量\theta的转置矩阵。
同时我们还加上了”feature0“即x_0=1以便方便表示成为向量乘积的形式。
为了寻找最优的参数\theta,我们可以最小化errorfunction即costfunction
这个就是least-squarescostfunction,通过最小化这个函数来寻找最优参数。
3LMS算法
为了寻找最优参数,我们可以随机初始化,然后沿着梯度慢慢改变参数值(需要改变\theta所有维),观察costfunction值的变化,这就是梯度下降法的思想。
假设我们只有一个训练样本(x,y),对参数\theta_j求偏导数有
我们可以得到下面的参数updaterule
其中\alpha叫learningrate,用于调节每次迭代参数变化的大小,这就是LMS(leastmeansquares)算法。
用直观的角度去理解,如果我们看到一个训练样本满足y^(i)-h(x(i))等于0,那么说明参数就不必再更新;反之,如果预测值error较大,那么参数的变化也需要比较大。
如果我们有多个训练样本,比如有m个样本,每个样本用n个feature来描述,那么GD的updaterule需要对n个feature对应的n个参数都做更新,有两种更新方式:
batchgradientdescent和stochastic/incrementalgradientdescent。
对于前者,每次更新一轮参数\theta_j(注意n个参数需要同步更新才算完成一轮)需要都需要考虑所有的m个训练样本,即
也就是每更新一个\theta_j我们需要计算所有m个训练样本的predictionerror然后求和。
而后者更新一轮参数\theta_j我们只需要考虑一个训练样本,然后逐个考虑完所有样本(因此是incremental的)即
当训练样本sizem非常大时,显然stochastic/incrementalgradientdescent会更有优势,因为每更新一轮参数不需要扫描所有的训练样本。
我们也可以把costfunction写出矩阵相乘的形式,即令
则有
因此代价函数J可以写成
我们将J(\theta)对向量\theta求梯度(对于向量求导,得到的是梯度,是有方向的,这里需要用到matrixcalculus,比标量形式下求导麻烦一些,详见NG课程notes),令梯度为0可以直接得到极值点,也就是唯一全局最优解情形下的最值点(normalequations)
这样可以避免迭代求解,直接得到最优的参数\theta值。
3编程实战
(注:
本部分编程习题全部来自AndrewNg机器学习网上公开课)
3.1单变量的LinearRegression
在单变量的LinearRegression中,每个训练样本只用一个feature来描述,例如某个卡车租赁公司分店的利润和当地人口总量的关系,给定若干人口总量和利润的训练样本,要求进行LinearRegression得到一条曲线,然后根据曲线对新的城市人口总量条件下进行利润的预测。
主程序如下
[plain] viewplaincopy
1.%% Initialization
2.clear ; close all; clc
3.
4.%% ==================== Part 1:
Basic Function ====================
5.% Complete warmUpExercise.m
6.fprintf('Running warmUpExercise ... \n');
7.fprintf('5x5 Identity Matrix:
\n');
8.warmUpExercise()
9.
10.fprintf('Program paused. Press enter to continue.\n');
11.pause;
12.
13.
14.%% ======================= Part 2:
Plotting =======================
15.fprintf('Plotting Data ...\n')
16.data = load('ex1data1.txt');
17.X = data(:
1); y = data(:
2);
18.m = length(y); % number of training examples
19.
20.% Plot Data
21.% Note:
You have to complete the code in plotData.m
22.plotData(X, y);
23.
24.fprintf('Program paused. Press enter to continue.\n');
25.pause;
26.
27.%% =================== Part 3:
Gradient descent ===================
28.fprintf('Running Gradient Descent ...\n')
29.
30.X = [ones(m, 1), data(:
1)]; % Add a column of ones to x
31.theta = zeros(2, 1); % initialize fitting parameters
32.
33.% Some gradient descent settings
34.iterations = 1500;
35.alpha = 0.01;
36.
37.% compute and display initial cost
38.computeCost(X, y, theta)
39.
40.% run gradient descent
41.theta = gradientDescent(X, y, theta, alpha, iterations);
42.
43.% print theta to screen
44.fprintf('Theta found by gradient descent:
');
45.fprintf('%f %f \n', theta
(1), theta
(2));
46.
47.% Plot the linear fit
48.hold on; % keep previous plot visible
49.plot(X(:
2), X*theta, '-')
50.legend('Training data', 'Linear regression')
51.hold off % don't overlay any more plots on this figure
52.
53.% Predict values for population sizes of 35,000 and 70,000
54.predict1 = [1, 3.5] *theta;
55.fprintf('For population = 35,000, we predict a profit of %f\n',...
56. predict1*10000);
57.predict2 = [1, 7] * theta;
58.fprintf('For population = 70,000, we predict a profit of %f\n',...
59. predict2*10000);
60.
61.fprintf('Program paused. Press enter to continue.\n');
62.pause;
63.
64.%% ============= Part 4:
Visualizing J(theta_0, theta_1) =============
65.fprintf('Visualizing J(theta_0, theta_1) ...\n')
66.
67.% Grid over which we will calculate J
68.theta0_vals = linspace(-10, 10, 100);
69.theta1_vals = linspace(-1, 4, 100);
70.
71.% initialize J_vals to a matrix of 0's
72.J_vals = zeros(length(theta0_vals), length(theta1_vals));
73.
74.% Fill out J_vals
75.for i = 1:
length(theta0_vals)
76. for j = 1:
length(theta1_vals)
77. t = [theta0_vals(i); theta1_vals(j)];
78. J_vals(i,j) = computeCost(X, y, t);
79. end
80.end
81.
82.
83.% Because of the way meshgrids work in the surf command, we need to
84.% transpose J_vals before calling surf, or else the axes will be flipped
85.J_vals = J_vals';
86.% Surface plot
87.figure;
88.surf(theta0_vals, theta1_vals, J_vals)
89.xlabel('\theta_0'); ylabel('\theta_1');
90.
91.% Contour plot
92.figure;
93.% Plot J_vals as 15 contours spaced logarithmically between 0.01 and 100
94.contour(theta0_vals, theta1_vals, J_vals, logspace(-2, 3, 20))
95.xlabel('\theta_0'); ylabel('\theta_1');
96.hold on;
97.plot(theta
(1), theta
(2), 'rx', 'MarkerSize', 10, 'LineWidth', 2);
首先load进训练数据,并且visualize出来
然后需要实现两个函数computeCost和graientDescent,分别计算代价函数和对参数按照梯度方向进行更新,结合LinearRegression代价函数计算公式和参数更新Rule,我们可以实现如下
[plain] viewplaincopy
1.function J = computeCost(X, y, theta)
2.%COMPUTECOST Compute cost for linear regression
3.% J = COMPUTECOST(X, y, theta) computes the cost of using theta as the
4.% parameter for linear regression to fit the data points in X and y
5.
6.% Initialize some useful values
7.m = length(y); % number of training examples
8.
9.% You need to return the following variables correctly
10.J = 0;
11.
12.% ====================== YOUR CODE HERE ======================
13.% Instructions:
Compute the cost of a particular choice of theta
14.% You should set J to the cost.
15.
16.J = 1/(2 * m) * (X * theta - y)' * (X * theta - y);
17.
18.% =========================================================================
19.
20.end
实现的时候要注意X是m行2列,theta是2行1列,y是m行1列。
由于matlab默认矩阵是叉乘,要注意保证相乘的矩阵的维数满足叉乘的要求。
参数更新函数如下
[plain] viewplaincopy
1.function [theta, J_history] = gradientDescent(X, y, theta, alpha, num_iters)
2.%GRADIENTDESCENT Performs gradient descent to learn theta
3.% theta = GRADIENTDESENT(X, y, theta, alpha, num_iters) updates theta by
4.% taking num_iters gradient steps with learning rate alpha
5.
6.% Initialize some useful values
7.m = length(y); % number of training examples
8.J_history = zeros(num_iters, 1);
9.
10.for iter = 1:
num_iters
11.
12. % ====================== YOUR CODE HERE ======================
13. % Instructions:
Perform a single gradient step on the parameter vector
14. % theta.
15. %
16. % Hint:
While debugging, it can be useful to print out the values
17. % of the cost function (computeCost) and gradient here.
18. %
19. % Batch gradient descent
20. Update = 0;
21. for i = 1:
m
22. Update = Update + alpha/m * (y(i) - X(i,:
) * theta) * X(i, :
)';
23. end
24. theta = theta + Update;
25.
26. % ============================================================
27.
28. % Save the cost J in every iteration
29. J_history(iter) = computeCost(X, y, theta);
30.
31.end
32.
33.end
这里用的是BatchGradientDescent,也就是每更新一次参数都需要扫描所有m个训练样本。
Update就是每次参数的变化量,需要对所有trainingexample的训练误差进行求和。
每次更新参数后重新计算代价函数,把所有历史的cost记录保存在J_history中。
经过1500次迭代,我们可以输出求的的参数theta,画出拟合的曲线,并且对新的人口来预测利润值,即
[plain] viewplaincopy
1.Running Gradient Descent ...
2.
3.ans =
4.
5. 32.0727
6.
7.Theta found by gradient descent:
-3.630291 1.166362
8.For population = 35,000, we predict a profit of 4519.767868
9.For population = 70,000, we predict a profit of 45342.450129
10.Program paused. Press enter to continue.
11.Visualizing J(theta_0, theta_1) ...
拟合出的曲线如下图
我们把costfunctionJ的值在(theta_0,theta_1)上进行visualization可以得到
下面这张图是在(theta_0,theta_1)上的投影等高线图,红叉处就是GD收敛到的最小值处。
对于linearregression只有全局最优解,所以这个也是我们想要的最优参数。
3.2多变量的LinearRegression
如果每个训练样本用多个feature来描述,这就是多变量的LinearRegression问题。
比如我们想根据房子的面积和卧室个数来预测房子的价格,那么现在每个训练样本就是用2个feature来描述。
主程序如下
[plain] viewplaincopy
1.%% Initialization
2.
3.%% ================ Part 1:
Feature Normalization ================
4.
5.%% Clear and Close Figures
6.clear ; close all; clc
7.
8.fprintf('Loading data ...\n');
9.
10.%% Load Data
11.data = load('ex1data2.txt');
12.X = data(:
1:
2);
13.y = data(:
3);
14.m = length(y);
15.
16.% Print out some data points
17.fprintf('First 10 examples from the dataset:
\n');
18.fprintf(' x = [%.0f %.0f], y = %.0f \n', [X(1:
10,:
) y(1:
10,:
)]');
19.
20.fprintf('Program paused. Press enter to continue.\n');
21.pause;
22.
23.% Scale features and set them to zero mean
24.fprintf('Normalizing Features ...\n');
25.
26.[X mu sigma] = featureNormalize(X);
27.
28.% Add intercept term to X
29.X = [ones(m, 1) X];
30.
31.
32.%% ================ Part 2:
Gradient Descent ================
33.
34.% ====================== YOUR CODE HERE ======================
35.% Instructions:
We have provided you with the following starter
36.% c