Coursera机器学习-吴恩达
线性回归和逻辑回归解决过拟合:
1.减少特征数量:
1.手动选择要保留的特征,剔除一些特征
2.使用模型选择算法
2.正则化(Regularization):
1.保留所有特征,但减少参数 theta 的大小;
2.有许多稍微有用的特征时,正则化很有效。
% 1.读取训练集,并打印正负样本
data = load('ex2data2.txt');
X = data(:, [1, 2]);
y = data(:, 3);
plotData(X, y);
hold on;
xlabel('Microchip Test 1')
ylabel('Microchip Test 2')
legend('y = 1', 'y = 0')
hold off;
% 函数plotData:
function plotData(X, y)
figure;
hold on;
% 打印正样本和负样本
positive = find(y == 1);
negative = find(y == 0);
plot(X(positive, 1), X(positive, 2), 'k+', 'LineWidth', 2, 'MarkerSize', 7);
plot(X(negative, 1), X(negative, 2), 'ko', 'MarkerFaceColor', 'y', 'MarkerSize', 7);
hold off;
end
% 2.逻辑回归正则化:(原理见3)
% 特征映射,(Feature Mapping):
% 使用两个特征(x1,x2)组合出更多的特征如x1x2, x1^2, x2^2, x1*x2^3等
X = mapFeature(X(:,1), X(:,2));
% 函数 mapFeature:
function out = mapFeature(X1, X2)
degree = 6;
out = ones(size(X1(:,1)));
for i = 1:degree
for j = 0:i
out(:, end+1) = (X1.^(i-j)).*(X2.^j);
end
end
end
% 初始化拟合参数
initial_theta = zeros(size(X, 2), 1);
% 设置正则化参数为1
lambda = 1;
% 计算初始 theta 的代价函数和梯度
[cost, grad] = costFunctionReg(initial_theta, X, y, lambda);
fprintf('Cost at initial theta (zeros): %f\n', cost);
fprintf(' %f \n', grad(1:5));
% with all-ones theta and lambda = 10
test_theta = ones(size(X,2),1);
% 计算全1 theta 的代价函数和梯度
[cost, grad] = costFunctionReg(test_theta, X, y, 10);
fprintf('Cost at initial theta (zeros): %f\n', cost);
fprintf(' %f \n', grad(1:5));
% 函数 costFunctionReg:
function [J, grad] = costFunctionReg(theta, X, y, lambda)
m = length(y);
J = 0;
grad = zeros(size(theta));
[J, grad] = costFunction(theta, X, y);
% 经过正规化的代价函数
J = J + lambda / (2 * m) * (sum(theta .^ 2) - theta(1) ^ 2);
grad = grad + lambda / m * theta;
grad(1) = grad(1) - lambda / m * theta(1);
end
% 3.正规化原理:
% 3.1 为何需要正规化:解决过拟合
前面我们使用 mapFeature 函数生成了很多特征项,有 x1^2, x2^4, x1^2 * x2^5等等
那么这些高次幂的特征会导致函数过拟合
而太少特征项的次幂则导致欠拟合:
% 3.1 正规化原理:
原理是要把后面这些高次幂的 theta 对函数的影响消除掉,在不去掉它的情况下;
如何消除,因为代价函数我们需要求它的最小值,
因此我们只需在代价函数后加上一个常数 * 需要消除影响的theta;
在求代价函数最小值时,由于后面加了个 常数 * theta,
那么只有theta越小,常数 * theta 才会越小,才能求到 J 的最小值;
这就间接消除了theta在代价函数的作用,因为它很小了。
% 3.2 正规化的实际实现:
由于我们并不知道那个 theta 对函数影响,因此我们对所有 theta 均采取正规化,
除了 theta0 。
前面乘的常数就是 lambda
lambda 太大,theta 对 J 的影响就很小,导致欠拟合;
lambda 太小,theta 对 J 的影响就很大,导致过拟合;
逻辑回归:
线性回归:
% 4.使用高级优化算法求最小 theta ,并在训练集上验证准确率
initial_theta = zeros(size(X, 2), 1);
% 设置lambda,需手动调整
lambda = 1;
options = optimset('GradObj', 'on', 'MaxIter', 400);
%求 theta
[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))
xlabel('Microchip Test 1')
ylabel('Microchip Test 2')
legend('y = 1', 'y = 0', 'Decision boundary')
hold off;
% 验证准确率
p = predict(theta, X);
fprintf('Train Accuracy: %f\n', mean(double(p == y)) * 100);