基于MATLAB的人工神经网络ANN回归代码
wptr33 2025-06-09 00:39 9 浏览
在之前的文章基于MATLAB的随机森林RF回归与变量重要性影响程度排序代码中,我们对基于MATLAB的随机森林(RF)回归与变量影响程度(重要性)排序的代码加以详细讲解与实践。本次我们继续基于MATLAB,对另一种常用的机器学习方法——神经网络方法加以代码实战。
首先需要注明的是,在MATLAB中,我们可以直接基于“APP”中的“Neural Net Fitting”工具箱实现在无需代码的情况下,对神经网络算法加以运行:
基于工具箱的神经网络方法虽然方便,但是一些参数不能调整;同时也不利于我们对算法、代码的理解。因此,本文不利用“Neural Net Fitting”工具箱,而是直接通过代码将神经网络方法加以运行——但是,本文的代码其实也是通过上述工具箱运行后生成的;而这种生成神经网络代码的方法也是MATLAB官方推荐的方式。
另外,需要注意的是,本文直接进行神经网络算法的执行,省略了前期数据处理、训练集与测试集划分、精度衡量指标选取等。因此建议大家先将本文开头提及的那篇文章阅读后,再阅读本文。
本文分为两部分,首先是将代码分段、详细讲解,方便大家理解;随后是完整代码,方便大家自行尝试。
1 分解代码
1.1 循环准备
由于机器学习往往需要多次执行,我们就在此先定义循环。
%% ANN Cycle Preparation
ANNRMSE=9999;
ANNRunNum=0;
ANNRMSEMatrix=[];
ANNrAllMatrix=[];
while ANNRMSE>400
其中,ANNRMSE是初始的RMSE;ANNRunNum是神经网络算法当前运行的次数;ANNRMSEMatrix用来存储每一次神经网络运行后所得到的RMSE结果;ANNrAllMatrix用来存储每一次神经网络运行后所得到的皮尔逊相关系数结果;最后一句表示当所得到的模型RMSE>400时,则停止循环。
1.2 神经网络构建
接下来,我们对神经网络的整体结构加以定义。
%% ANN
x=TrainVARI';
t=TrainYield';
trainFcn = 'trainlm';
hiddenLayerSize = [10 10 10];
ANNnet = fitnet(hiddenLayerSize,trainFcn);
其中,TrainVARI、TrainYield分别是我这里训练数据的自变量(特征)与因变量(标签);trainFcn为神经网络所选用的训练函数方法名称,其名称与对应的方法对照如下表:
hiddenLayerSize为神经网络所用隐层与各层神经元个数,[10 10 10]代表共有三层隐层,各层神经元个数分别为10,10,10。
1.3 数据处理
接下来,对输入神经网络模型的数据加以处理。
ANNnet.input.processFcns = {'removeconstantrows','mapminmax'};
ANNnet.output.processFcns = {'removeconstantrows','mapminmax'};
ANNnet.divideFcn = 'dividerand';
ANNnet.divideMode = 'sample';
ANNnet.divideParam.trainRatio = 0.6;
ANNnet.divideParam.valRatio = 0.4;
ANNnet.divideParam.testRatio = 0.0;
其中,ANNnet.input.processFcns与ANNnet.output.processFcns分别代表输入模型数据的处理方法,'removeconstantrows'表示删除在各样本中数值始终一致的特征列,'mapminmax'表示将数据归一化处理;divideFcn表示划分数据训练集、验证集与测试集的方法,'dividerand'表示依据所给定的比例随机划分;divideMode表示对数据划分的维度,我们这里选择'sample',也就是对样本进行划分;divideParam表示训练集、验证集与测试集所占比例,那么在这里,因为是直接用了先前随机森林方法(可以看这篇博客)中的数据划分方式,那么为了保证训练集、测试集的固定,我们就将divideParam.testRatio设置为0.0,然后将训练集与验证集比例划分为0.6与0.4。
1.4 模型训练参数配置
接下来对模型运行过程中的主要参数加以配置。
ANNnet.performFcn = 'mse';
ANNnet.trainParam.epochs=5000;
ANNnet.trainParam.goal=0.01;
其中,performFcn为模型误差衡量函数,'mse'表示均方误差;trainParam.epochs表示训练时Epoch次数,trainParam.goal表示模型所要达到的精度要求(即模型运行到trainParam.epochs次时或误差小于trainParam.goal时将会停止运行。
1.5 神经网络实现
这一部分代码大多数与绘图、代码与GUI生成等相关,因此就不再一一解释了,大家可以直接运行。需要注意的是,train是模型训练函数。
% For a list of all plot functions type: help nnplot
ANNnet.plotFcns = {'plotperform','plottrainstate','ploterrhist','plotregression','plotfit'};
[ANNnet,tr] = train(ANNnet,x,t);
y = ANNnet(x);
e = gsubtract(t,y);
performance = perform(ANNnet,t,y);
% Recalculate Training, Validation and Test Performance
trainTargets = t .* tr.trainMask{1};
valTargets = t .* tr.valMask{1};
testTargets = t .* tr.testMask{1};
trainPerformance = perform(ANNnet,trainTargets,y);
valPerformance = perform(ANNnet,valTargets,y);
testPerformance = perform(ANNnet,testTargets,y);
% view(net)
% Plots
%figure, plotperform(tr)
%figure, plottrainstate(tr)
%figure, ploterrhist(e)
%figure, plotregression(t,y)
%figure, plotfit(net,x,t)
% Deployment
% See the help for each generation function for more information.
if (false)
% Generate MATLAB function for neural network for application
% deployment in MATLAB scripts or with MATLAB Compiler and Builder
% tools, or simply to examine the calculations your trained neural
% network performs.
genFunction(ANNnet,'myNeuralNetworkFunction');
y = myNeuralNetworkFunction(x);
end
if (false)
% Generate a matrix-only MATLAB function for neural network code
% generation with MATLAB Coder tools.
genFunction(ANNnet,'myNeuralNetworkFunction','MatrixOnly','yes');
y = myNeuralNetworkFunction(x);
end
if (false)
% Generate a Simulink diagram for simulation or deployment with.
% Simulink Coder tools.
gensim(ANNnet);
end
1.6 精度衡量
%% Accuracy of ANN
ANNPredictYield=sim(ANNnet,TestVARI')';
ANNRMSE=sqrt(sum(sum((ANNPredictYield-TestYield).^2))/size(TestYield,1));
ANNrMatrix=corrcoef(ANNPredictYield,TestYield);
ANNr=ANNrMatrix(1,2);
ANNRunNum=ANNRunNum+1;
ANNRMSEMatrix=[ANNRMSEMatrix,ANNRMSE];
ANNrAllMatrix=[ANNrAllMatrix,ANNr];
disp(ANNRunNum);
end
disp(ANNRMSE);
其中,ANNPredictYield为预测结果;ANNRMSE、ANNrMatrix分别为模型精度衡量指标RMSE与皮尔逊相关系数。结合本文1.1部分可知,我这里设置为当所得神经网络模型RMSE在400以内时,将会停止循环;否则继续开始执行本文1.2部分至1.6部分的代码。
1.7 保存模型
这一部分就不再赘述了,大家可以参考这篇博客(
https://blog.csdn.net/zhebushibiaoshifu/article/details/114806478)。
%% ANN Model Storage
ANNModelSavePath='G:\CropYield\02_CodeAndMap\00_SavedModel\';
save(sprintf('%sRF0417ANN0399.mat',ANNModelSavePath),'TestVARI','TestYield','TrainVARI','TrainYield','ANNnet','ANNPredictYield','ANNr','ANNRMSE',...
'hiddenLayerSize');
2 完整代码
完整代码如下:
%% ANN Cycle Preparation
ANNRMSE=9999;
ANNRunNum=0;
ANNRMSEMatrix=[];
ANNrAllMatrix=[];
while ANNRMSE>1000
%% ANN
x=TrainVARI';
t=TrainYield';
trainFcn = 'trainlm';
hiddenLayerSize = [10 10 10];
ANNnet = fitnet(hiddenLayerSize,trainFcn);
ANNnet.input.processFcns = {'removeconstantrows','mapminmax'};
ANNnet.output.processFcns = {'removeconstantrows','mapminmax'};
ANNnet.divideFcn = 'dividerand';
ANNnet.divideMode = 'sample';
ANNnet.divideParam.trainRatio = 0.6;
ANNnet.divideParam.valRatio = 0.4;
ANNnet.divideParam.testRatio = 0.0;
ANNnet.performFcn = 'mse';
ANNnet.trainParam.epochs=5000;
ANNnet.trainParam.goal=0.01;
% For a list of all plot functions type: help nnplot
ANNnet.plotFcns = {'plotperform','plottrainstate','ploterrhist','plotregression','plotfit'};
[ANNnet,tr] = train(ANNnet,x,t);
y = ANNnet(x);
e = gsubtract(t,y);
performance = perform(ANNnet,t,y);
% Recalculate Training, Validation and Test Performance
trainTargets = t .* tr.trainMask{1};
valTargets = t .* tr.valMask{1};
testTargets = t .* tr.testMask{1};
trainPerformance = perform(ANNnet,trainTargets,y);
valPerformance = perform(ANNnet,valTargets,y);
testPerformance = perform(ANNnet,testTargets,y);
% view(net)
% Plots
%figure, plotperform(tr)
%figure, plottrainstate(tr)
%figure, ploterrhist(e)
%figure, plotregression(t,y)
%figure, plotfit(net,x,t)
% Deployment
% See the help for each generation function for more information.
if (false)
% Generate MATLAB function for neural network for application
% deployment in MATLAB scripts or with MATLAB Compiler and Builder
% tools, or simply to examine the calculations your trained neural
% network performs.
genFunction(ANNnet,'myNeuralNetworkFunction');
y = myNeuralNetworkFunction(x);
end
if (false)
% Generate a matrix-only MATLAB function for neural network code
% generation with MATLAB Coder tools.
genFunction(ANNnet,'myNeuralNetworkFunction','MatrixOnly','yes');
y = myNeuralNetworkFunction(x);
end
if (false)
% Generate a Simulink diagram for simulation or deployment with.
% Simulink Coder tools.
gensim(ANNnet);
end
%% Accuracy of ANN
ANNPredictYield=sim(ANNnet,TestVARI')';
ANNRMSE=sqrt(sum(sum((ANNPredictYield-TestYield).^2))/size(TestYield,1));
ANNrMatrix=corrcoef(ANNPredictYield,TestYield);
ANNr=ANNrMatrix(1,2);
ANNRunNum=ANNRunNum+1;
ANNRMSEMatrix=[ANNRMSEMatrix,ANNRMSE];
ANNrAllMatrix=[ANNrAllMatrix,ANNr];
disp(ANNRunNum);
end
disp(ANNRMSE);
%% ANN Model Storage
ANNModelSavePath='G:\CropYield\02_CodeAndMap\00_SavedModel\';
save(sprintf('%sRF0417ANN0399.mat',ANNModelSavePath),'AreaPercent','InputOutput','nLeaf','nTree',...
'RandomNumber','RFModel','RFPredictConfidenceInterval','RFPredictYield','RFr','RFRMSE',...
'TestVARI','TestYield','TrainVARI','TrainYield','ANNnet','ANNPredictYield','ANNr','ANNRMSE',...
'hiddenLayerSize');
相关推荐
- redis的八种使用场景
-
前言:redis是我们工作开发中,经常要打交道的,下面对redis的使用场景做总结介绍也是对redis举报的功能做梳理。缓存Redis最常见的用途是作为缓存,用于加速应用程序的响应速度。...
- 基于Redis的3种分布式ID生成策略
-
在分布式系统设计中,全局唯一ID是一个基础而关键的组件。随着业务规模扩大和系统架构向微服务演进,传统的单机自增ID已无法满足需求。高并发、高可用的分布式ID生成方案成为构建可靠分布式系统的必要条件。R...
- 基于OpenWrt系统路由器的模式切换与网页设计
-
摘要:目前商用WiFi路由器已应用到多个领域,商家通过给用户提供一个稳定免费WiFi热点达到吸引客户、提升服务的目标。传统路由器自带的Luci界面提供了工厂模式的Web界面,用户可通过该界面配置路...
- 这篇文章教你看明白 nginx-ingress 控制器
-
主机nginx一般nginx做主机反向代理(网关)有以下配置...
- 如何用redis实现注册中心
-
一句话总结使用Redis实现注册中心:服务注册...
- 爱可可老师24小时热门分享(2020.5.10)
-
No1.看自己以前写的代码是种什么体验?No2.DooM-chip!国外网友SylvainLefebvre自制的无CPU、无操作码、无指令计数器...No3.我认为CS学位可以更好,如...
- Apportable:拯救程序员,IOS一秒变安卓
-
摘要:还在为了跨平台使用cocos2d-x吗,拯救objc程序员的奇葩来了,ApportableSDK:FreeAndroidsupportforcocos2d-iPhone。App...
- JAVA实现超买超卖方案汇总,那个最适合你,一篇文章彻底讲透
-
以下是几种Java实现超买超卖问题的核心解决方案及代码示例,针对高并发场景下的库存扣减问题:方案一:Redis原子操作+Lua脚本(推荐)//使用Redis+Lua保证原子性publicbo...
- 3月26日更新 快速施法自动施法可独立设置
-
2016年3月26日DOTA2有一个79.6MB的更新主要是针对自动施法和快速施法的调整本来内容不多不少朋友都有自动施法和快速施法的困扰英文更新日志一些视觉BUG修复就不翻译了主要翻译自动施...
- Redis 是如何提供服务的
-
在刚刚接触Redis的时候,最想要知道的是一个’setnameJhon’命令到达Redis服务器的时候,它是如何返回’OK’的?里面命令处理的流程如何,具体细节怎么样?你一定有问过自己...
- lua _G、_VERSION使用
-
到这里我们已经把lua基础库中的函数介绍完了,除了函数外基础库中还有两个常量,一个是_G,另一个是_VERSION。_G是基础库本身,指向自己,这个变量很有意思,可以无限引用自己,最后得到的还是自己,...
- China's top diplomat to chair third China-Pacific Island countries foreign ministers' meeting
-
BEIJING,May21(Xinhua)--ChineseForeignMinisterWangYi,alsoamemberofthePoliticalBureau...
- 移动工作交流工具Lua推出Insights数据分析产品
-
Lua是一个适用于各种职业人士的移动交流平台,它在今天推出了一项叫做Insights的全新功能。Insights是一个数据平台,客户可以在上面实时看到员工之间的交流情况,并分析这些情况对公司发展的影响...
- Redis 7新武器:用Redis Stack实现向量搜索的极限压测
-
当传统关系型数据库还在为向量相似度搜索的性能挣扎时,Redis7的RedisStack...
- Nginx/OpenResty详解,Nginx Lua编程,重定向与内部子请求
-
重定向与内部子请求Nginx的rewrite指令不仅可以在Nginx内部的server、location之间进行跳转,还可以进行外部链接的重定向。通过ngx_lua模块的Lua函数除了能实现Nginx...
- 一周热门
-
-
C# 13 和 .NET 9 全知道 :13 使用 ASP.NET Core 构建网站 (1)
-
因果推断Matching方式实现代码 因果推断模型
-
git pull命令使用实例 git pull--rebase
-
git pull 和git fetch 命令分别有什么作用?二者有什么区别?
-
面试官:git pull是哪两个指令的组合?
-
git 执行pull错误如何撤销 git pull fail
-
git fetch 和git pull 的异同 git中fetch和pull的区别
-
git pull 之后本地代码被覆盖 解决方案
-
还可以这样玩?Git基本原理及各种骚操作,涨知识了
-
git命令之pull git.pull
-
- 最近发表
- 标签列表
-
- git pull (33)
- git fetch (35)
- mysql insert (35)
- mysql distinct (37)
- concat_ws (36)
- java continue (36)
- jenkins官网 (37)
- mysql 子查询 (37)
- python元组 (33)
- mybatis 分页 (35)
- vba split (37)
- redis watch (34)
- python list sort (37)
- nvarchar2 (34)
- mysql not null (36)
- hmset (35)
- python telnet (35)
- python readlines() 方法 (36)
- munmap (35)
- docker network create (35)
- redis 集合 (37)
- python sftp (37)
- setpriority (34)
- c语言 switch (34)
- git commit (34)