如何使用matlab自带的NN tool 实现BPNN网络

如何使用matlab自带的NN tool 实现BPNN网络

附上一张图 你可以直接按钮点击操作也可以使用代码

附上一张图 你可以直接按钮点击操作也可以使用代码
% 清空环境变量
clc
clear all
%%第一步 读取数据
load('milkSpectrum.mat');  %自定义的data
input=NIR(2:251,2:126);   
output=NIR(2:251,end);
%% 第二步 设置训练数据和预测数据
temp = randperm(size(output,1));  %产生样本个数的随机数
%训练集 --176个样本
input_train = input(temp(1:176),:)';
output_train = output(temp(1:176),:)';
%测试集--75个样本 
input_test = input(temp(176:end),:)';
output_test = output(temp(176:end),:)'

% 训练数据集
% input_train = input(1:150,:)';
% output_train =output(1:150,:)';
% 测试数据集
% input_test=input(45:70,:)';
% input_test =output(45:70,:)';
%网络神经元节点个数
inputnum=125;
hiddennum=13;%隐含层节点数量经验公式p=sqrt(m+n)+a ,故分别取2~13进行试验125
outputnum=1;
%% 第三本 训练样本数据归一化
[inputn,inputps]=mapminmax(input_train);%归一化到[-1,1]之间,inputps用来作下一次同样的归一化
[outputn,outputps]=mapminmax(output_train);
%% 第四步 构建BP神经网络
net=newff(inputn,outputn,hiddennum,{'tansig','purelin'},'trainlm');% 建立模型,传递函数使用purelin,采用梯度下降法训练

W1= net. iw{1, 1};%输入层到中间层的权值

B1 = net.b{1};%中间各层神经元阈值

W2 = net.lw{2,1};%中间层到输出层的权值
B2 = net. b{2};%输出层各神经元阈值

%% 第五步 网络参数配置( 训练次数,学习速率,训练目标最小误差等)
net.trainParam.epochs=1000;         % 训练次数,这里设置为1000次
net.trainParam.lr=0.01;                   % 学习速率,这里设置为0.01
net.trainParam.goal=0.00001;                    % 训练目标最小误差,这里设置为0.00001

%% 第六步 BP神经网络训练
net=train(net,inputn,outputn);%开始训练,其中inputn,outputn分别为输入输出样本

%% 第七步 测试样本归一化
inputn_test=mapminmax('apply',input_test,inputps);% 对样本数据进行归一化

%% 第八步 BP神经网络预测
an=sim(net,inputn_test); %用训练好的模型进行仿真

%% 第九步 预测结果反归一化与误差计算     
test_simu=mapminmax('reverse',an,outputps); %把仿真得到的数据还原为原始的数量级
error=abs(test_simu-output_test);      %预测值和真实值的误差

%%第十步 真实值与预测值误差比较
figure(1)
plot(output_test(1,:),'bo-')
hold on
plot(test_simu(1,:),'r*-')
hold on
plot(error(1,:),'square','MarkerFaceColor','b')
legend('expectancy value','predicted value','error');
xlabel('data array');
ylabel('output value');
[c,l]=size(output_test);
MAE1=sum(abs(error(1,:)))/l;
MSE1=error(1,:)*error(1,:)'/l;
[r2, rmse] = rsquare(output_test,test_simu);%自定义函数

disp(['-----------------------误差计算--------------------------'])
disp(['隐含层节点数为',num2str(hiddennum),'时的误差结果如下:'])
disp(['平均绝对误差MAE为:',num2str(MAE1)])
disp(['均方误差MSE为:       ',num2str(MSE1)])
disp(['均方根误差RMSE为:  ',num2str(rmse)])
disp([' R2为 :  ',num2str(r2)])
function [r2 rmse] = rsquare(y,f,varargin)
% Compute coefficient of determination of data fit model and RMSE
%
% [r2 rmse] = rsquare(y,f)
% [r2 rmse] = rsquare(y,f,c)
%
% RSQUARE computes the coefficient of determination (R-square) value from
% actual data Y and model data F. The code uses a general version of 
% R-square, based on comparing the variability of the estimation errors 
% with the variability of the original values. RSQUARE also outputs the
% root mean squared error (RMSE) for the user's convenience.
%
% Note: RSQUARE ignores comparisons involving NaN values.
% 
% INPUTS
%   Y       : Actual data
%   F       : Model fit
%
% OPTION
%   C       : Constant term in model
%             R-square may be a questionable measure of fit when no
%             constant term is included in the model.
%   [DEFAULT] TRUE : Use traditional R-square computation
%            FALSE : Uses alternate R-square computation for model
%                    without constant term [R2 = 1 - NORM(Y-F)/NORM(Y)]
%
% OUTPUT 
%   R2      : Coefficient of determination
%   RMSE    : Root mean squared error
%
% EXAMPLE
%   x = 0:0.1:10;
%   y = 2.*x + 1 + randn(size(x));
%   p = polyfit(x,y,1);
%   f = polyval(p,x);
%   [r2 rmse] = rsquare(y,f);
%   figure; plot(x,y,'b-');
%   hold on; plot(x,f,'r-');
%   title(strcat(['R2 = ' num2str(r2) '; RMSE = ' num2str(rmse)]))
%   
% Jered R Wells
% 11/17/11
% jered [dot] wells [at] duke [dot] edu
%
% v1.2 (02/14/2012)
%
% Thanks to John D'Errico for useful comments and insight which has helped
% to improve this code. His code POLYFITN was consulted in the inclusion of
% the C-option (REF. File ID: #34765).

if isempty(varargin); c = true; 
elseif length(varargin)>1; error 'Too many input arguments';
elseif ~islogical(varargin{1}); error 'C must be logical (TRUE||FALSE)'
else c = varargin{1}; 
end

% Compare inputs
if ~all(size(y)==size(f)); error 'Y and F must be the same size'; end

% Check for NaN
tmp = ~or(isnan(y),isnan(f));
y = y(tmp);
f = f(tmp);

if c; r2 = max(0,1 - sum((y(:)-f(:)).^2)/sum((y(:)-mean(y(:))).^2));
else r2 = 1 - sum((y(:)-f(:)).^2)/sum((y(:)).^2);
    if r2<0
    % http://web.maths.unsw.edu.au/~adelle/Garvan/Assays/GoodnessOfFit.html
        warning('Consider adding a constant term to your model') %#ok<WNTAG>
        r2 = 0;
    end
end

rmse = sqrt(mean((y(:) - f(:)).^2));


引用: 在MATLAB的工具箱中,bpnn是指反向传播神经网络(backpropagation neural network)。反向传播神经网络是一种常用的人工神经网络算法,用于解决分类和回归问题。它通过反向传播误差来调整网络的权重和偏置,以逐步优化网络的性能。bpnn算法在MATLAB的神经网络工具箱中是以函数的形式提供的,可以用于构建、训练和测试反向传播神经网络模型。 在使用bpnn算法构建神经网络模型时,常常需要对输入数据进行归一化处理,以确保数据集在合适的范围内。在MATLAB的神经网络工具箱中,提供了几个函数用于归一化处理,包括premnmx、tramnmx、postmnmx和mapminmax。premnmx用于将网络的输入数据或输出数据进行归一化,使其分布在[-1, 1]区间内。tramnmx用于对新的数据进行与样本数据相同的预处理。postmnmx用于将网络的输出数据进行反归一化还原。mapminmax则可以将矩阵的每一行归一化到[-1, 1]区间内。 引用: 在使用bpnn算法时,premnmx函数是进行归一化处理的重要步骤之一。它可以将输入数据归一化到[-1, 1]区间内。如果你的输入数据已经在[0, 1]范围内,那么就不需要再进行归一化处理。不过,如果你使用logsig函数作为激活函数,或者使用tansig函数时,还是将数据归一化到[-1, 1]范围内会更好。 引用: 在bpnn算法中,BLF是指反向传播的权重/偏置学习函数(Backprop weight/bias learning function),默认为'learngdm'。这个函数用于计算网络中权重和偏置的调整量,以实现网络的训练过程。BLF函数的选择会影响网络的学习速度和性能,具体选择哪种BLF函数要根据具体情况和需求来决定。 综上所述,MATLAB的工具箱中的bpnn是指反向传播神经网络算法,可以用于构建、训练和测试神经网络模型。在使用bpnn算法时,需要对输入数据进行归一化处理,可以使用premnmx函数来实现。同时,选择合适的BLF函数也是网络训练过程中需要考虑的因素。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* *2* [bpnn——matlab工具箱-归一化函数 premnmx、tramnmx、postmnmx、mapminmax](https://blog.youkuaiyun.com/ustceduruixing/article/details/50060541)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"] - *3* [bpnn matlab工具箱,bpnn——MATLAB工具箱--newff](https://blog.youkuaiyun.com/weixin_34982884/article/details/115945930)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"] [ .reference_list ]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值