首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >专栏 >吴恩达机器学习 - 评估假设

吴恩达机器学习 - 评估假设

作者头像
FishWang
发布2025-08-27 12:35:03
发布2025-08-27 12:35:03
12900
代码可运行
举报
运行总次数:0
代码可运行

题目链接:点击打开链接


正则线性回归:

可视化数据:
Code:
代码语言:javascript
代码运行次数:0
运行
复制
load ('ex5data1.mat');
plot(X, y, 'rx', 'MarkerSize', 10, 'LineWidth', 1.5);
结果为:
这里写图片描述
这里写图片描述
代价函数:
公式(并正则化):
这里写图片描述
这里写图片描述
Code(填充在linearRegCostFunction.m中):
代码语言:javascript
代码运行次数:0
运行
复制
t = X*theta-y;
J = t'*t/(2.0*m) + lambda/(2.0*m)*theta(2:end)'*theta(2:end);
求正则线性回归梯度
公式:
这里写图片描述
这里写图片描述
Code:
代码语言:javascript
代码运行次数:0
运行
复制
grad(1) = (X(:,1)'*t)/m;
grad(2:end) = (X(:,2:end)'*t./m) + (lambda/m).*theta(2:end);
训练样本
效果如下:
这里写图片描述
这里写图片描述

偏差和方差

样本数与训练误差、交叉验证误差的关系
Code(learningCurve.m):
代码语言:javascript
代码运行次数: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), ~] = linearRegCostFunction(X(1:i,:),y(1:i),theta,0);

    [error_val(i), ~] = linearRegCostFunction(Xval,yval,theta,0);
end


% -------------------------------------------------------------

% =========================================================================

end
图示(高偏差):
这里写图片描述
这里写图片描述

多项式回归

特征扩张(将一次线性的特征扩张到p次)
Code(polyFeatures.m):
代码语言:javascript
代码运行次数:0
运行
复制
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
效果查看

这里说明一下接下来运行ex5的效果。因为我们把特征扩张到了8次方(本例中),所以最后一个特征的数值特别特别大,所以我们这里需要特征归一化。

程序是这么调用的(实际上我们可以自己写这个部分,也不是很麻烦)(featureNormalize.m):
代码语言:javascript
代码运行次数:0
运行
复制
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
然后就是利用我们之前写好的函数计算代价啦:
效果图如下:
这里写图片描述
这里写图片描述

从图上看来是高方差了(过拟合)

然后我们看一下不同的λ对结果有什么影响吧(这一步不计分,只是帮助我们来理解)~
Code(直接在控制台运行)(只需对第一行进行修改):
代码语言:javascript
代码运行次数:0
运行
复制
lambda = 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')
λ=1时(拟合的不错)
这里写图片描述
这里写图片描述
λ=32时(欠拟合啦)
这里写图片描述
这里写图片描述
那么我们改小一点:λ=0.1时(惩罚的力度不够,还是有点过拟合)
这里写图片描述
这里写图片描述
使用交叉验证集选择合适的λ(画出λ-Error曲线)
效果图:
这里写图片描述
这里写图片描述

发现λ大概在3的位置上比较好

我们来看看λ=3的曲线:
这里写图片描述
这里写图片描述
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2025-08-26,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 正则线性回归:
    • 可视化数据:
    • 代价函数:
    • 求正则线性回归梯度
    • 训练样本
  • 偏差和方差
    • 样本数与训练误差、交叉验证误差的关系
  • 多项式回归
    • 特征扩张(将一次线性的特征扩张到p次)
    • 效果查看
    • 然后就是利用我们之前写好的函数计算代价啦:
    • 然后我们看一下不同的λ对结果有什么影响吧(这一步不计分,只是帮助我们来理解)~
    • 使用交叉验证集选择合适的λ(画出λ-Error曲线)
    • 我们来看看λ=3的曲线:
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档