前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
社区首页 >专栏 >正则化线性回归,来研究具有不同偏差方差特性的模型。

正则化线性回归,来研究具有不同偏差方差特性的模型。

作者头像
裴来凡
发布于 2022-05-28 07:17:19
发布于 2022-05-28 07:17:19
55000
代码可运行
举报
运行总次数:0
代码可运行

ex5.m

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
%% Machine Learning Online Class
%  Exercise 5 | Regularized Linear Regression and Bias-Variance
%
%  Instructions
%  ------------
% 
%  This file contains code that helps you get started on the
%  exercise. You will need to complete the following functions:
%
%     linearRegCostFunction.m
%     learningCurve.m
%     validationCurve.m
%
%  For this exercise, you will not need to change any code in this file,
%  or any other files other than those mentioned above.
%

%% Initialization
clear ; close all; clc

%% =========== 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;

%% =========== Part 2: Regularized Linear Regression Cost =============
%  You should now implement the cost function for regularized linear 
%  regression. 
%

theta = [1 ; 1];
J = linearRegCostFunction([ones(m, 1) X], y, theta, 1);

fprintf(['Cost at theta = [1 ; 1]: %f '...
         '\n(this value should be about 303.993192)\n'], J);

fprintf('Program paused. Press enter to continue.\n');
pause;

%% =========== Part 3: Regularized Linear Regression Gradient =============
%  You should now implement the gradient for regularized linear 
%  regression.
%

theta = [1 ; 1];
[J, grad] = linearRegCostFunction([ones(m, 1) X], y, theta, 1);

fprintf(['Gradient at theta = [1 ; 1]:  [%f; %f] '...
         '\n(this value should be about [-15.303016; 598.250744])\n'], ...
         grad(1), grad(2));

fprintf('Program paused. Press enter to continue.\n');
pause;


%% =========== 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;


%% =========== 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" -- Figure 3 in ex5.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;

%% =========== 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 = 3;
[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;

%% =========== 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;
本文参与 腾讯云自媒体同步曝光计划,分享自微信公众号。
原始发表:2020-05-10,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 图像处理与模式识别研究所 微信公众号,前往查看

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

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

评论
登录后参与评论
暂无评论
推荐阅读
编辑精选文章
换一批
审计思路学习笔记
比如有函数名 move_uploaded_file() ,接着看调用这个函数的代码是否存在为限制上传格式或者可以绕过
红客突击队
2022/09/28
1.3K0
审计思路学习笔记
PHP网络图片储存到服务器
相信有很多人有把网络图片保存到服务器的需求,那么如何把网络图片保存到服务器上呢?简单介绍一下我下面代码的原理,首先网络图片转化成base64格式,然后再把base64保存为jpg或者png等格式的图片即可,直接看代码吧
田小檬
2023/08/24
2270
Typecho 无插件获取必应每日壁纸、故事
在原来的基础上添加了自定义路径变量$pach_image;注释掉了每日删除之前图片和故事信息。因为要保存图片。
laoknas网络技术
2021/07/14
6440
php笔记
接口返回格式 数组包对象 空的话 返回空数组,同一各客户端数据格式 IdArr 删除空值(去重(获取某值变成一维数组)) $idArr = array_filter(array_unique(array_column($list, 'id'))); 复制代码 php 生成文件txt到指定目录 file_put_contents("c:/zll.txt","内容"); 复制代码 php.ini设置上传临时文件路径 upload_tmp_dir = D:\owen\lswj\ 复制代码 基于php实现
OwenZhang
2021/12/08
3290
php笔记
PHP如何上传文件和下载,你学会了吗?
​ 在 B/S 程序中文件上传已经成为一个常用功能。其目的是客户可以通过浏览器(Browser)将文件上传到服务器(Server)上的指定目录。
叫我可儿呀
2019/12/04
1.7K0
Yii2文件/图片上传实例
Yii 是一个高性能,基于组件的 PHP 框架,用于快速开发现代 Web 应用程序。 名字 Yii (读作 易)在中文里有“极致简单与不断演变”两重含义, 也可看作 Yes It Is! 的缩写。
OwenZhang
2022/05/26
1.4K0
Yii2文件/图片上传实例
WriteUp分享 | CTF-web
题目 各种绕过哦 TXT? 文件上传测试 本地包含 考细心 正则? PHP很烦人? 一道签到题 抽抽奖 never give up I have a jpg,i upload a txt lo
安恒网络空间安全讲武堂
2018/02/06
6.7K0
WriteUp分享 | CTF-web
利用laravel+ajax实现文件上传功能方法示例
前言 大家都知道,早期的XMLHttpRequest不支持文件上传,一般用第三方js插件或者flash,现在可以借助XMLHttpRequest Level 2 的FormData对象实现二进制文件上传,正好最近工作中遇到了这个需求,所以本文就来给大家下实现的方法,话不多说了,来一起看看详细的介绍吧。 示例代码
用户2323866
2021/06/29
7250
php生成唯一订单号的5种方法
这篇文章主要介绍了关于php生成唯一订单号的方法,有着一定的参考价值,现在分享给大家,有需要的朋友可以参考一下
紫旭Blog - blog.zixutech.cn
2020/01/01
3K0
维护一个输入自己的一言(Hitokoto)Api
首先,我们需要采集别人的,并保存到本地,所以说我这里写了一个通用采集的模板,代码如下:
用砖头敲代码
2022/06/17
4710
将WordPress文章中的外链图片自动下载到本地
WordPress很多插件或者代码都可以实现在编辑文章中自动将外链图片下载到本地,最终我选择了一个叫:Easy Copy Paste的插件。
小狐狸说事
2023/11/17
5780
将WordPress文章中的外链图片自动下载到本地
Geek Challenge 2022
(77条消息) CTF-WEB——HTTP Headers类型_WHOAMIAnony的博客-CSDN博客_ctf header
故里[TRUE]
2023/04/21
4750
Geek Challenge 2022
pHP生成唯一单号
这几天一直在写个人使用的用户中心,虽然期间遇到不少的问题,但还是一点点的都解决了,也从制作期间学到不少的知识,今天就说一说利用PHP生成订单单的方法。
全栈程序员站长
2022/07/08
1.7K0
pHP生成唯一单号
PHP常用函数前100排行榜
这两天在努力记单词,想着应该把最常使用的单词先记下来,从网上找了几篇文章之后分析了一批词汇,效果还算不错;
汤青松
2020/07/01
5680
基于 PHP 实现的微信小程序 pdf 文件的预览服务
前段时间文库类微信小程序开发中遇到个问题,就是要在小程序中预览阿里云 OSS 中的 pdf 文件。微信官方给的方案就一个,就是把文档缓存到本地然后用资源管理器打开。
PHP开发工程师
2022/05/25
2K0
基于 PHP 实现的微信小程序 pdf 文件的预览服务
PHP中WEB典型应用技术
      2)、在浏览器端提供能够进行文件上传的表单。其实就是给表单添加属性:enctype=”multipart/form-data”;
北国风光
2019/04/11
6900
PHP中WEB典型应用技术
PHP全栈学习笔记7
图形图像处理技术,gd库的强大支持,PHP的图像可以是PHP的强项,PHP图形化类库,jpgraph是一款非常好用的强大的图形处理工具。
达达前端
2019/07/03
1.5K0
php session基本原理解析
本文为仙士可原创文章,转载无需和我联系,但请注明来自仙士可博客www.php20.cn
仙士可
2019/12/19
3600
php中$argv解释以及使用
$argv?— 传递给脚本的参数数组,它被定义在$_SERVER全局数组中(当脚本以命令行方式运行时,argv 变量传递给程序 C 语言样式的命令行参数)。当通过 GET 方式调用时,该变量包含que
友儿
2022/07/27
8850
linux下php导入带图片的word文档转为html,图片保存下来生成路径。
如果出现异常,在页面上不一定表现出来,而是页面卡着一直没响应,通过apache日志看到相关错误
用户8824291
2021/07/13
1.5K0
相关推荐
审计思路学习笔记
更多 >
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档
查看详情【社区公告】 技术创作特训营有奖征文
本文部分代码块支持一键运行,欢迎体验
本文部分代码块支持一键运行,欢迎体验