如何使用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));


  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是一种使用Matlab实现粒子群优化的BPNN算法的代码示例。 首先,我们需要定义神经网络的结构和参数。在这个示例中,我们将使用一个三层的神经网络,其中输入层有2个神经元,隐藏层有3个神经元,输出层有1个神经元。我们还需要定义每个粒子的初始位置和速度。 ``` % Define neural network structure and parameters input_layer_size = 2; hidden_layer_size = 3; output_layer_size = 1; % Define particle swarm optimization parameters num_particles = 20; max_iterations = 100; w = 0.5; c1 = 1; c2 = 2; % Initialize particle positions and velocities positions = rand(num_particles, (input_layer_size+1)*hidden_layer_size + (hidden_layer_size+1)*output_layer_size); velocities = zeros(num_particles, size(positions,2)); ``` 接下来,我们需要定义一个函数来计算神经网络的输出和误差。这个函数需要接受一个粒子的位置作为输入,并返回神经网络的输出和误差。 ``` function [output, error] = evaluate_network(position) % Reshape particle position into weights and biases matrices W1 = reshape(position(1:hidden_layer_size*(input_layer_size+1)), hidden_layer_size, input_layer_size+1); W2 = reshape(position(hidden_layer_size*(input_layer_size+1)+1:end), output_layer_size, hidden_layer_size+1); % Forward propagate inputs through network z2 = W1 * [1; x']; a2 = sigmoid(z2); z3 = W2 * [1; a2]; output = sigmoid(z3); % Calculate error error = 0.5 * sum((output - y).^2); end ``` 接下来,我们需要定义一个函数来执行粒子群优化。在每个迭代中,我们将计算每个粒子的适应度(即神经网络的误差),并更新每个粒子的速度和位置。 ``` % Define sigmoid function function [y] = sigmoid(x) y = 1 ./ (1 + exp(-x)); end % Perform particle swarm optimization for iteration = 1:max_iterations % Evaluate fitness of each particle fitness = zeros(num_particles, 1); for i = 1:num_particles [output, error] = evaluate_network(positions(i,:)); fitness(i) = 1 / error; end % Update global best position and fitness [global_best_fitness, global_best_index] = max(fitness); global_best_position = positions(global_best_index,:); % Update particle velocities and positions for i = 1:num_particles % Update velocity velocities(i,:) = w * velocities(i,:) ... + c1 * rand() * (best_positions(i,:) - positions(i,:)) ... + c2 * rand() * (global_best_position - positions(i,:)); % Update position positions(i,:) = positions(i,:) + velocities(i,:); end end ``` 在最后一步中,我们可以使用最佳粒子的位置来计算最终的神经网络输出。 ``` % Use best particle position to evaluate final neural network [output, error] = evaluate_network(global_best_position); ```

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值