斯坦福ML(Matlab)公开课,本次练习将实现正则化线性回归、多项式回归,并且在不同的参数下拟合数据、绘制学习曲线。
正则化线性回归
利用水库水位预测流量。
可视化数据集
数据集被拆分为3部分:
-
训练集
-
交叉验证集,用来决定正则化参数
-
测试集
可视化代码没什么稀奇的部分:
%% =========== Part 1: Loading and Visualizing Data ============= % We start the exercise by first loading and visualizing the dataset. % The following code will load the dataset into your environment and plot % the data. % % Load Training Data fprintf('Loading and Visualizing Data ...\n') % Load from ex5data1: % You will have X, y, Xval, yval, Xtest, ytest in your environment load ('ex5data1.mat'); % m = Number of examples m = size(X, 1); % Plot training data plot(X, y, 'rx', 'MarkerSize', 10, 'LineWidth', 1.5); xlabel('Change in water level (x)'); ylabel('Water flowing out of the dam (y)'); fprintf('Program paused. Press enter to continue.\n'); pause;
得到:
这是非线性的数据,可以预计线性回归不会得到多好的效果。
正则化损失函数和梯度
损失函数:
注意theta_0没有正则化项。
梯度
于是theta_0方向的梯度也是个例外。
跟逻辑斯谛回归的正则化损失函数很像,实现如下:
function [J, grad] = linearRegCostFunction(X, y, theta, lambda) %LINEARREGCOSTFUNCTION Compute cost and gradient for regularized linear %regression with multiple variables % [J, grad] = LINEARREGCOSTFUNCTION(X, y, theta, lambda) computes the % cost of using theta as the parameter for linear regression to fit the % data points in X and y. Returns the cost in J and the gradient in grad % Initialize some useful values m = length(y); % number of training examples % You need to return the following variables correctly J = 0; grad = zeros(size(theta)); % ====================== YOUR CODE HERE ====================== % Instructions: Compute the cost and gradient of regularized linear % regression for a particular choice of theta. % % You should set J to the cost and grad to the gradient. % Z = (X * theta - y).^2; J = sum(Z(:,1)) / (2 * m) + ... lambda / (2 * m) * (theta' * theta - theta(1)^2); grad = 1 / m * X' * (X * theta - y) ... + lambda / m * theta; grad(1) = grad(1) - lambda / m * theta(1); % ========================================================================= grad = grad(:); end
拟合线性回归
在如此低维的空间中,正则化项其实作用不大。将lambda设为0,利用无约束非线性规划函数fmincg最优化损失函数即可。
function [theta] = trainLinearReg(X, y, lambda) %TRAINLINEARREG Trains linear regression given a dataset (X, y) and a %regularization parameter lambda % [theta] = TRAINLINEARREG (X, y, lambda) trains linear regression using % the dataset (X, y) and regularization parameter lambda. Returns the % trained parameters theta. % % Initialize Theta initial_theta = zeros(size(X, 2), 1); % Create "short hand" for the cost function to be minimized costFunction = @(t) linearRegCostFunction(X, y, t, lambda); % Now, costFunction is a function that takes in only one argument options = optimset('MaxIter', 200, 'GradObj', 'on'); % Minimize using fmincg theta = fmincg(costFunction, initial_theta, options); end
上面创建了个costFunction函数句柄。调用方法:
%% =========== Part 4: Train Linear Regression ============= % Once you have implemented the cost and gradient correctly, the % trainLinearReg function will use your cost function to train % regularized linear regression. % % Write Up Note: The data is non-linear, so this will not give a great % fit. % % Train linear regression with lambda = 0 lambda = 0; [theta] = trainLinearReg([ones(m, 1) X], y, lambda); % Plot fit over the data plot(X, y, 'rx', 'MarkerSize', 10, 'LineWidth', 1.5); xlabel('Change in water level (x)'); ylabel('Water flowing out of the dam (y)'); hold on; plot(X, [ones(m, 1) X]*theta, '--', 'LineWidth', 2) hold off; fprintf('Program paused. Press enter to continue.\n'); pause;
得到:
的确拟合得不怎么样。
方差偏差权衡
机器学习中一个重要的概念就是方差偏差权衡,高偏差的模型称作欠拟合,高方差的模型则为过拟合。这一章通过训练误差和测试误差来诊断模型的方差偏差问题。
学习曲线
这部分通过不同大小的训练集训练模型,在训练集和交叉验证集得到两者的误差,并将其绘制成学习曲线。
训练误差的定义为:
注意训练误差并不是损失函数,前者并没有正则化项,实现的时候可以将损失函数的lambda设为0即可。
实现如下:
function [error_train, error_val] = ... learningCurve(X, y, Xval, yval, lambda) %LEARNINGCURVE Generates the train and cross validation set errors needed %to plot a learning curve % [error_train, error_val] = ... % LEARNINGCURVE(X, y, Xval, yval, lambda) returns the train and % cross validation set errors for a learning curve. In particular, % it returns two vectors of the same length - error_train and % error_val. Then, error_train(i) contains the training error for % i examples (and similarly for error_val(i)). % % In this function, you will compute the train and test errors for % dataset sizes from 1 up to m. In practice, when working with larger % datasets, you might want to do this in larger intervals. % % Number of training examples m = size(X, 1); % You need to return these values correctly error_train = zeros(m, 1); error_val = zeros(m, 1); % ====================== YOUR CODE HERE ====================== % Instructions: Fill in this function to return training errors in % error_train and the cross validation errors in error_val. % i.e., error_train(i) and % error_val(i) should give you the errors % obtained after training on i examples. % % Note: You should evaluate the training error on the first i training % examples (i.e., X(1:i, 🙂 and y(1:i)). % % For the cross-validation error, you should instead evaluate on % the _entire_ cross validation set (Xval and yval). % % Note: If you are using your cost function (linearRegCostFunction) % to compute the training and cross validation error, you should % call the function with the lambda argument set to 0. % Do note that you will still need to use lambda when running % the training to obtain the theta parameters. % % Hint: You can loop over the examples with the following: % % for i = 1:m % % Compute train/cross validation errors using training examples % % X(1:i, 🙂 and y(1:i), storing the result in % % error_train(i) and error_val(i) % .... % % end % % ---------------------- Sample Solution ---------------------- for i = 1:m [theta] = trainLinearReg(X(1:i, :), y(1:i), lambda); [error_train(i), grad] = linearRegCostFunction(X(1:i, :), y(1:i), theta, 0); [error_val(i), grad] = linearRegCostFunction(Xval, yval, theta, 0); end % ------------------------------------------------------------- % ========================================================================= end
很简单,调用方法如下:
%% =========== Part 5: Learning Curve for Linear Regression ============= % Next, you should implement the learningCurve function. % % Write Up Note: Since the model is underfitting the data, we expect to % see a graph with "high bias" -- slide 8 in ML-advice.pdf % lambda = 0; [error_train, error_val] = ... learningCurve([ones(m, 1) X], y, ... [ones(size(Xval, 1), 1) Xval], yval, ... lambda) plot(1:m, error_train, 1:m, error_val); title('Learning curve for linear regression') legend('Train', 'Cross Validation') xlabel('Number of training examples') ylabel('Error') axis([0 13 0 150]) fprintf('# Training Examples\tTrain Error\tCross Validation Error\n'); for i = 1:m fprintf(' \t%d\t\t%f\t%f\n', i, error_train(i), error_val(i)); end fprintf('Program paused. Press enter to continue.\n'); pause;
得到
可以看出,随着训练集的增大,训练误差增大,交叉验证误差下降不明显,两者都很大。这被称为高偏差,即线性回归模型太简单,不足以拟合如此复杂的数据。下一节通过多项式回归拟合一个更好的模型。
多项式回归
多项式回归的假设函数为:
特征映射
这种取n次方的方法其实跟逻辑斯谛回归模型中mapfeature是一个意思:
function [X_poly] = polyFeatures(X, p) %POLYFEATURES Maps X (1D vector) into the p-th power % [X_poly] = POLYFEATURES(X, p) takes a data matrix X (size m x 1) and % maps each example into its polynomial features where % X_poly(i, 🙂 = [X(i) X(i).^2 X(i).^3 ... X(i).^p]; % % You need to return the following variables correctly. X_poly = zeros(numel(X), p); % ====================== YOUR CODE HERE ====================== % Instructions: Given a vector X, return a matrix X_poly where the p-th % column of X contains the values of X to the p-th power. % % for i = 1:p X_poly(:,i) = X .^i; end % ========================================================================= end
由于特征映射,其数量级变得差异巨大,所以需要先进行标准化:
function [X_norm, mu, sigma] = featureNormalize(X) %FEATURENORMALIZE Normalizes the features in X % FEATURENORMALIZE(X) returns a normalized version of X where % the mean value of each feature is 0 and the standard deviation % is 1. This is often a good preprocessing step to do when % working with learning algorithms. mu = mean(X); X_norm = bsxfun(@minus, X, mu); sigma = std(X_norm); X_norm = bsxfun(@rdivide, X_norm, sigma); % ============================================================ end
bsxfun将两个数组作为参数调用某个指定的函数,上面将每个特征减去均值,除以标准差,于是整个数据集将标准化为均值=0,标准差=1。还记得在线性回归中,我们写了个傻乎乎的循环:
for i = 1 : features mu(i) = mean(X(:,i)); sigma(i) = std(X(:,i)); X_norm(:,i) = (X(:,i) - mu(i)) / sigma(i); end
现在两句话搞定。
调用方法:
%% =========== Part 6: Feature Mapping for Polynomial Regression ============= % One solution to this is to use polynomial regression. You should now % complete polyFeatures to map each example into its powers % p = 8; % Map X onto Polynomial Features and Normalize X_poly = polyFeatures(X, p); [X_poly, mu, sigma] = featureNormalize(X_poly); % Normalize X_poly = [ones(m, 1), X_poly]; % Add Ones % Map X_poly_test and normalize (using mu and sigma) X_poly_test = polyFeatures(Xtest, p); X_poly_test = bsxfun(@minus, X_poly_test, mu); X_poly_test = bsxfun(@rdivide, X_poly_test, sigma); X_poly_test = [ones(size(X_poly_test, 1), 1), X_poly_test]; % Add Ones % Map X_poly_val and normalize (using mu and sigma) X_poly_val = polyFeatures(Xval, p); X_poly_val = bsxfun(@minus, X_poly_val, mu); X_poly_val = bsxfun(@rdivide, X_poly_val, sigma); X_poly_val = [ones(size(X_poly_val, 1), 1), X_poly_val]; % Add Ones fprintf('Normalized Training Example 1:\n'); fprintf(' %f \n', X_poly(1, :)); fprintf('\nProgram paused. Press enter to continue.\n'); pause;
训练多项式回归
所谓多项式回归只不过是将参数映射到高维而已,其核心依然是线性回归,训练代码一模一样。如果我们不加正则化项:
%% =========== Part 7: Learning Curve for Polynomial Regression ============= % Now, you will get to experiment with polynomial regression with multiple % values of lambda. The code below runs polynomial regression with % lambda = 0. You should try running the code with different values of % lambda to see how the fit and learning curve change. % lambda = 0;%changed from 0 to 1; [theta] = trainLinearReg(X_poly, y, lambda); % Plot training data and fit figure(1); plot(X, y, 'rx', 'MarkerSize', 10, 'LineWidth', 1.5); plotFit(min(X), max(X), mu, sigma, theta, p); xlabel('Change in water level (x)'); ylabel('Water flowing out of the dam (y)'); title (sprintf('Polynomial Regression Fit (lambda = %f)', lambda)); figure(2); [error_train, error_val] = ... learningCurve(X_poly, y, X_poly_val, yval, lambda); plot(1:m, error_train, 1:m, error_val); title(sprintf('Polynomial Regression Learning Curve (lambda = %f)', lambda)); xlabel('Number of training examples') ylabel('Error') axis([0 13 0 100]) legend('Train', 'Cross Validation') fprintf('Polynomial Regression (lambda = %f)\n\n', lambda); fprintf('# Training Examples\tTrain Error\tCross Validation Error\n'); for i = 1:m fprintf(' \t%d\t\t%f\t%f\n', i, error_train(i), error_val(i)); end fprintf('Program paused. Press enter to continue.\n'); pause;
这里写了个可视化多项式回归的函数:
function plotFit(min_x, max_x, mu, sigma, theta, p) %PLOTFIT Plots a learned polynomial regression fit over an existing figure. %Also works with linear regression. % PLOTFIT(min_x, max_x, mu, sigma, theta, p) plots the learned polynomial % fit with power p and feature normalization (mu, sigma). % Hold on to the current figure hold on; % We plot a range slightly bigger than the min and max values to get % an idea of how the fit will vary outside the range of the data points x = (min_x - 15: 0.05 : max_x + 25)'; % Map the X values X_poly = polyFeatures(x, p); X_poly = bsxfun(@minus, X_poly, mu); X_poly = bsxfun(@rdivide, X_poly, sigma); % Add ones X_poly = [ones(size(x, 1), 1) X_poly]; % Plot plot(x, X_poly * theta, '--', 'LineWidth', 2) % Hold off to the current figure hold off end
得到:
似乎不是个好模型,前面甚至打破物理定律出现负流量,后面有点像指数级增长,而非多项式了。
其学习曲线如下:
这幅图最大的不自然之处在于,训练误差很低接近0,而交叉验证误差较高,两者之间有较大鸿沟。
调整lambda
试试lambda=1:
似乎好一些。
自动调参
lambda到底该取多少呢?写个脚本自动化计算不同lambda下的误差吧:
function [lambda_vec, error_train, error_val] = ... validationCurve(X, y, Xval, yval) %VALIDATIONCURVE Generate the train and validation errors needed to %plot a validation curve that we can use to select lambda % [lambda_vec, error_train, error_val] = ... % VALIDATIONCURVE(X, y, Xval, yval) returns the train % and validation errors (in error_train, error_val) % for different values of lambda. You are given the training set (X, % y) and validation set (Xval, yval). % % Selected values of lambda (you should not change this) lambda_vec = [0 0.001 0.003 0.01 0.03 0.1 0.3 1 3 10]'; % You need to return these variables correctly. error_train = zeros(length(lambda_vec), 1); error_val = zeros(length(lambda_vec), 1); % ====================== YOUR CODE HERE ====================== % Instructions: Fill in this function to return training errors in % error_train and the validation errors in error_val. The % vector lambda_vec contains the different lambda parameters % to use for each calculation of the errors, i.e, % error_train(i), and error_val(i) should give % you the errors obtained after training with % lambda = lambda_vec(i) % % Note: You can loop over lambda_vec with the following: % % for i = 1:length(lambda_vec) % lambda = lambda_vec(i); % % Compute train / val errors when training linear % % regression with regularization parameter lambda % % You should store the result in error_train(i) % % and error_val(i) % .... % % end % % for i = 1:length(lambda_vec) lambda = lambda_vec(i); [theta] = trainLinearReg(X, y, lambda); [error_train(i), grad] = linearRegCostFunction(X, y, theta, 0); [error_val(i), grad] = linearRegCostFunction(Xval, yval, theta, 0); end % ========================================================================= end
这段代码检查了下列lambda取值:
[0 0.001 0.003 0.01 0.03 0.1 0.3 1 3 10]
将误差与lambda的关系可视化出来:
%% =========== Part 8: Validation for Selecting Lambda ============= % You will now implement validationCurve to test various values of % lambda on a validation set. You will then use this to select the % "best" lambda value. % [lambda_vec, error_train, error_val] = ... validationCurve(X_poly, y, X_poly_val, yval); close all; plot(lambda_vec, error_train, lambda_vec, error_val); legend('Train', 'Cross Validation'); xlabel('lambda'); ylabel('Error'); fprintf('lambda\t\tTrain Error\tValidation Error\n'); for i = 1:length(lambda_vec) fprintf(' %f\t%f\t%f\n', ... lambda_vec(i), error_train(i), error_val(i)); end fprintf('Program paused. Press enter to continue.\n'); pause;
得到:
在lambda=3的时候验证集误差最小,是最理想的值。