機器學習筆記(五)過擬合問題及正則化
一、 過擬合問題
1. 引入
線性迴歸當中:
假設我們拿出房屋面積與房價的資料集,隨著面積的增大,房價曲線趨於平緩。第一個模型不能很好地擬合,具有高偏差(欠擬合)。我們加入二次項後曲線可以較好的擬合,用第三個模型去擬合時,它通過了所有的資料點,但它是一條扭曲的線條,不停上下波動,我們並不認為它是一個預測房價的好模型。這個現象我們稱為過度擬合。
(概括:過擬合現象常在變數過多的時候出現,能非常好的擬合訓練資料,但無法泛化到新樣本中。)
同樣地,Logistic迴歸當中:
解決過擬合問題:
1) 減少特徵數量
2) 正則化方法
二、正則化
上圖第二個模型不是一個好的擬合模型,現在我們在三次項和四次項上面加上懲罰項(penalize)如1000,我們要最小化這個新函式,就是 和 要儘可能小,他們會趨近於0,最後我們擬合得到的函式實際上是一個二次函式。總體來說我們在一些項上面加上懲罰項就相當於簡化這個函式,使之更不容易出現過擬合的問題。
在實際問題中,如一個問題有100個引數,我們不知道該選擇哪個它和標籤相關度較低,此時我們修改代價函式來縮小所有的引數。
在代價函式中新增一個額外的正則化項,來縮小每個引數的值。
1. 線性迴歸的正則化
在usual linear regression基礎上加上一個額外的正則化項,其中
梯度下降法:
我們將與其他引數的更新過程分開,在此基礎上求偏導數,這樣就可以對正則化代價函式 使用梯度下降的方法進行最小化。
課堂記錄:
其中由於學習率很小,m很大,是一個略小於1的數,舉例可能是0.99,這一項乘上相當於每次更新將向0方向縮小一點點。
正規方程法:
這就是正則化後的正規方程法公式。
PS:關於矩陣不可逆問題,如果正則化引數 我們就可以保證括號中的矩陣一定是可逆的,因為正則化正好可以解決一些 不可逆的問題。
2. Logistic迴歸的正則化
加上一個額外的正則化項之後,即使我們有很多的特徵和引數,也可以得到一個較好的擬合模型,避免過擬合現象。
代價函式增加了一個正則化項,梯度也隨之相應改變。
下面是在上一篇筆記《Logistic迴歸模型實現》costFunction.m程式碼的基礎啊上我們修改過後,正則化後的costFunctionReg.m
function [J, grad] = costFunctionReg(theta, X, y, lambda) %COSTFUNCTIONREG Compute cost and gradient for logistic regression with regularization m = length(y); % number of training examples J = 0; grad = zeros(size(theta)); % ============================================================= J = 1/m * (-y' * log(sigmoid(X*theta)) - (1 - y') * log(1 - sigmoid(X * theta))) + lambda/2/m*sum(theta(2:end).^2); grad(1,:) = 1/m * (X(:, 1)' * (sigmoid(X*theta) - y)); grad(2:size(theta), :) = 1/m * (X(:, 2:size(theta))' * (sigmoid(X*theta) - y))... + lambda/m*theta(2:size(theta), :); end
下面是lambda取值為【0,1,10,100】時的擬合結果,從結果可以看出,lambda = 0時,可能存在過擬合現象,lambda = 1/10時,獲得較好模型。
%lambda = 0 Train Accuracy: 87.288136
%lambda = 1 Train Accuracy: 83.050847 Expected accuracy (with lambda = 1): 83.1 (approx)
%lambda = 10 Train Accuracy: 83.050847
%lambda = 100 Train Accuracy: 61.016949
過程程式碼:
%% Machine Learning Online Class - Exercise 2: Logistic Regression %% Initialization clear ; close all; clc %% Load Data % The first two columns contains the X values and the third column % contains the label (y). data = load('ex2data2.txt'); X = data(:, [1, 2]); y = data(:, 3); plotData(X, y); hold on; xlabel('Microchip Test 1') ylabel('Microchip Test 2') % Specified in plot order legend('y = 1', 'y = 0') hold off; %% =========== Part 1: Regularized Logistic Regression ============ % Add Polynomial Features % Note that mapFeature also adds a column of ones for us, so the intercept % term is handled X = mapFeature(X(:,1), X(:,2)); % Initialize fitting parameters initial_theta = zeros(size(X, 2), 1); % Set regularization parameter lambda to 1 lambda = 100; % Compute and display initial cost and gradient for regularized logistic % regression [cost, grad] = costFunctionReg(initial_theta, X, y, lambda); fprintf('Cost at initial theta (zeros): %f\n', cost); fprintf('Expected cost (approx): 0.693\n'); fprintf('Gradient at initial theta (zeros) - first five values only:\n'); fprintf(' %f \n', grad(1:5)); fprintf('Expected gradients (approx) - first five values only:\n'); fprintf(' 0.0085\n 0.0188\n 0.0001\n 0.0503\n 0.0115\n'); fprintf('\nProgram paused. Press enter to continue.\n'); pause; % Compute and display cost and gradient % with all-ones theta and lambda = 10 test_theta = ones(size(X,2),1); [cost, grad] = costFunctionReg(test_theta, X, y, 10); fprintf('\nCost at test theta (with lambda = 10): %f\n', cost); fprintf('Expected cost (approx): 3.16\n'); fprintf('Gradient at test theta - first five values only:\n'); fprintf(' %f \n', grad(1:5)); fprintf('Expected gradients (approx) - first five values only:\n'); fprintf(' 0.3460\n 0.1614\n 0.1948\n 0.2269\n 0.0922\n'); fprintf('\nProgram paused. Press enter to continue.\n'); pause; %% ============= Part 2: Regularization and Accuracies ============= % Optional Exercise: % In this part, you will get to try different values of lambda and % see how regularization affects the decision coundart % % Try the following values of lambda (0, 1, 10, 100). % % How does the decision boundary change when you vary lambda? How does % the training set accuracy vary? % Initialize fitting parameters initial_theta = zeros(size(X, 2), 1); % Set regularization parameter lambda to 1 (you should vary this) lambda = 0; % Set Options options = optimset('GradObj', 'on', 'MaxIter', 400); % Optimize [theta, J, exit_flag] = ... fminunc(@(t)(costFunctionReg(t, X, y, lambda)), initial_theta, options); % Plot Boundary plotDecisionBoundary(theta, X, y); hold on; title(sprintf('lambda = %g', lambda)) % Labels and Legend xlabel('Microchip Test 1') ylabel('Microchip Test 2') legend('y = 1', 'y = 0', 'Decision boundary') hold off; % Compute accuracy on our training set p = predict(theta, X); fprintf('Train Accuracy: %f\n', mean(double(p == y)) * 100); fprintf('Expected accuracy (with lambda = 0): (approx)\n');