警告:本文為小白入門學習筆記
在機器學習的過程中我們常常會遇到過擬合和欠擬合的現象,就如西瓜書中一個例子:
如果訓練樣本是帶有鋸齒的樹葉,過擬合會認為樹葉一定要帶有鋸齒,否則就不是樹葉。而欠擬合則認為只要是綠色的就是樹葉,會把一棵數也誤認為樹葉。
過擬合:如果我們的數據集有很多的屬性,假設函數會對訓練集擬合的非常好,也就是說損失函數J(theta)趨近於零,但是對新的樣本卻不能較為精確的預測(也就是不能夠泛化到一般)。
所以要解決過擬合問題(addressing overfitting):
Options:
1 減少屬性的個數
對於那些關聯性比較弱的屬性可以去掉
2 Regularization(正則化)
過擬合現象的產生可能是我們用這樣一個多元方程去擬合實際上是一個一元或二元曲線
![]()
所以我們希望theta3,theta4,theta5竟可能的小,想想如果這樣的話曲線是不是會變得簡單很多,但是在實際情況下,我們不知道要去減小(penalty)哪一個theta,因此干脆去penalty每一個theta,所以在損失函數后面增加一個項來實現,而這一項就是正則化項

這里我們要記住的是,我們希望損失函數竟可能的小。
而 λ 這個正則化參數需要控制的是這兩者之間的平衡,即平衡擬合訓練的目標和保持參數值較小的目標。從而來保持假設的形式相對簡單,來避免過度的擬合。
首先解決線性回歸問題的過擬合:
數據下載:
使用正規方程去求解正規化線性回歸是:
![\begin{displaymath}
\theta=(X^{T}X+\lambda\left[\begin{array}{cccc}
0\\
& 1\\
& & \ddots\\
& & & 1\end{array}\right])^{-1}X^{T}\vec{y}\end{displaymath}](/image/aHR0cDovL29wZW5jbGFzc3Jvb20uc3RhbmZvcmQuZWR1L01haW5Gb2xkZXIvY291cnNlcy9EZWVwTGVhcm5pbmcvZXhlcmNpc2VzL2V4NS9pbWc3LnBuZw==.png)
跟隨
后面的是一個(n+1)*(n+1)矩陣,n表示屬性的個數
![\begin{displaymath}
\begin{array}{cc}
\par
\vec{y} = \left[
\begin{array}{c}
y...
...m)})^T\mbox{-}
\end{array}\right] \nonumber
\par
\end{array}\end{displaymath}](/image/aHR0cDovL29wZW5jbGFzc3Jvb20uc3RhbmZvcmQuZWR1L01haW5Gb2xkZXIvY291cnNlcy9EZWVwTGVhcm5pbmcvZXhlcmNpc2VzL2V4NS9pbWcxMi5wbmc=.png)
使用這個式子就可以計算出theta的值。
MATLAB代碼:
function [jVal] = regLinerReg(lamda) x = load('ex5Linx.dat'); y = load('ex5Liny.dat'); %顯示原始數據 plot(x,y,'o','MarkerEdgeColor','b','MarkerFaceColor','r');hold on; x = [ones(length(y), 1), x, x.^2, x.^3, x.^4, x.^5]; [m,n] = size(x); n = n - 1; rm = diag([0;ones(n,1)]);%lamda后面的矩陣 theta = inv(x'*x + lamda .* rm) * x' * y; disp(theta); x = load('ex5Linx.dat'); h = theta(1) + theta(2)*x + theta(3)*x.^2 + theta(4)*x.^3 + theta(5)*x.^4 + theta(6)*x.^5; plot(x(1:m),h,'g-');hold on; end
分別使正則化參數設置為以下值:
lamda = 0;
lamda = 1;
lamda = 10;

可以發現當lamda=0 時,相當於沒有加正則化項,函數經過每一個點,這就是過擬合。lamda = 1時稍微緩和,lamda=10 時函數平和,如果lamda再設置大些,函數曲線可能會成為一條直線。
Regularized logistic regression:
拿到數據集后,用MATLAB畫出圖形:

可以看出,這個圖並不像前面的可以直接線性分割,所以假設函數是二元,最高次為6次函數。
![\begin{displaymath}
x=\left[\begin{array}{c}
1\\
u\\
v\\
u^2\\
uv\\
v^2\\
u^3\\
\vdots\\
uv^5\\
v^6\end{array}\right]
\end{displaymath}](/image/aHR0cDovL29wZW5jbGFzc3Jvb20uc3RhbmZvcmQuZWR1L01haW5Gb2xkZXIvY291cnNlcy9EZWVwTGVhcm5pbmcvZXhlcmNpc2VzL2V4NS9pbWcyOS5wbmc=.png)
設u表示x1(也就是數據集ex5Log.dat的第一例數據),v為x2(是第二列數據)。
% Exercise 5 -- Regularized Logistic Regression clear all; close all; clc x = load('ex5Logx.dat'); y = load('ex5Logy.dat'); % Plot the training data % Use different markers for positives and negatives figure pos = find(y); neg = find(y == 0); plot(x(pos, 1), x(pos, 2), 'k+','LineWidth', 2, 'MarkerSize', 7) hold on plot(x(neg, 1), x(neg, 2), 'ko', 'MarkerFaceColor', 'y', 'MarkerSize', 7) % Add polynomial features to x by % calling the feature mapping function % provided in separate m-file x = map_feature(x(:,1), x(:,2)); %獲得一個117*28矩陣 117是數據的條數,28是x [m, n] = size(x); % Initialize fitting parameters theta = zeros(n, 1);%28*1 % Define the sigmoid function g = inline('1.0 ./ (1.0 + exp(-z))'); % setup for Newton's method MAX_ITR = 15; J = zeros(MAX_ITR, 1); % Lambda is the regularization parameter lambda = 0; % Newton's Method for i = 1:MAX_ITR % Calculate the hypothesis function z = x * theta; h = g(z); % Calculate J (for testing convergence) J(i) =(1/m)*sum(-y.*log(h) - (1-y).*log(1-h))+ ... (lambda/(2*m))*norm(theta([2:end]))^2; % Calculate gradient and hessian. G = (lambda/m).*theta; G(1) = 0; % extra term for gradient L = (lambda/m).*eye(n); L(1) = 0;% extra term for Hessian grad = ((1/m).*x' * (h-y)) + G; H = ((1/m).*x' * diag(h) * diag(1-h) * x) + L; % Here is the actual update theta = theta - H\grad; end % Show J to determine if algorithm has converged J % display the norm of our parameters norm_theta = norm(theta) % Plot the results % We will evaluate theta*x over a % grid of features and plot the contour % where theta*x equals zero % Here is the grid range u = linspace(-1, 1.5, 200); v = linspace(-1, 1.5, 200); z = zeros(length(u), length(v)); % Evaluate z = theta*x over the grid for i = 1:length(u) for j = 1:length(v) z(i,j) = map_feature(u(i), v(j))*theta; end end z = z'; % important to transpose z before calling contour % Plot z = 0 % Notice you need to specify the range [0, 0] contour(u, v, z, [0, 0], 'LineWidth', 2) legend('y = 1', 'y = 0', 'Decision boundary') title(sprintf('\\lambda = %g', lambda), 'FontSize', 14) hold off % Uncomment to plot J % figure % plot(0:MAX_ITR-1, J, 'o--', 'MarkerFaceColor', 'r', 'MarkerSize', 8) % xlabel('Iteration'); ylabel('J')
運行結果:

改變lambda = 1

lambda = 10;

