matlab神经网络算法
⑴ 用Matlab算BP神经网络的具体算法
BP神经网络的传递函数一般采用sigmiod函数,学习算法一般采用最小梯度下降法;下面是具体的程序例子:
例1 采用动量梯度下降算法训练 BP 网络。
训练样本定义如下:
输入矢量为
p =[-1 -2 3 1
-1 1 5 -3]
目标矢量为 t = [-1 -1 1 1]
解:本例的 MATLAB 程序如下:
close all
clear
echo on
clc
% NEWFF——生成一个新的前向神经网络
% TRAIN——对 BP 神经网络进行训练
% SIM——对 BP 神经网络进行仿真
pause
% 敲任意键开始
clc
% 定义训练样本
% P 为输入矢量
P=[-1, -2, 3, 1; -1, 1, 5, -3];
% T 为目标矢量
T=[-1, -1, 1, 1];
pause;
clc
% 创建一个新的前向神经网络
net=newff(minmax(P),[3,1],{'tansig','purelin'},'traingdm')
% 当前输入层权值和阈值
inputWeights=net.IW{1,1}
inputbias=net.b{1}
% 当前网络层权值和阈值
layerWeights=net.LW{2,1}
layerbias=net.b{2}
pause
clc
% 设置训练参数
net.trainParam.show = 50;
net.trainParam.lr = 0.05; 学习速率
net.trainParam.mc = 0.9; 动量系数
net.trainParam.epochs = 1000;
net.trainParam.goal = 1e-3;
pause
clc
% 调用TRAINGDM 算法训练 BP 网络
[net,tr]=train(net,P,T);
pause
clc
% 对 BP 网络进行仿真
A = sim(net,P)
% 计算仿真误差
E = T - A
MSE=mse(E)
pause
clc
echo off
⑵ 请问matlab中RBF神经网络newrbe函数用的什么算法
newrbe是设计精确的径向基神经网络的函数,用法如:
P = [1 2 3];%输入
T = [2.0 4.1 5.9];%目标
net = newrbe(P,T);%生成神经网络
其算法是:生成的网络有2层,第一层是radbas神经元,用dist计算加权输入,用netprod计算网络输入,第二层是purelin神经元,用 dotprod计算加权输入,用netsum计算网络输入。两层都有偏差b。
newrbe先设第一层权重为p',偏差为0.8326,第二层权重IW{2,1}从第一层的仿真输出 A{1}得到,偏差 b{2}从解线性方程 [W{2,1} b{2}] * [A{1}; ones] = T 得到。
⑶ bp神经网络 matlab算法 运行显示一直在进行网络训练,怎么解决
运行结束,训练101次,没改你的源程序,你那有什么错误提示么?这是matlab R2012a版本
⑷ matlab BP神经网络的训练算法中训练函数(traingdm 、trainlm、trainbr)的实现过程及相应的VC源代码
VC源代码?你很搞笑嘛。。
给你trainlm的m码
function [out1,out2] = trainlm(varargin)
%TRAINLM Levenberg-Marquardt backpropagation.
%
% <a href="matlab:doc trainlm">trainlm</a> is a network training function that updates weight and
% bias states according to Levenberg-Marquardt optimization.
%
% <a href="matlab:doc trainlm">trainlm</a> is often the fastest backpropagation algorithm in the toolbox,
% and is highly recommended as a first choice supervised algorithm,
% although it does require more memory than other algorithms.
%
% [NET,TR] = <a href="matlab:doc trainlm">trainlm</a>(NET,X,T) takes a network NET, input data X
% and target data T and returns the network after training it, and a
% a training record TR.
%
% [NET,TR] = <a href="matlab:doc trainlm">trainlm</a>(NET,X,T,Xi,Ai,EW) takes additional optional
% arguments suitable for training dynamic networks and training with
% error weights. Xi and Ai are the initial input and layer delays states
% respectively and EW defines error weights used to indicate
% the relative importance of each target value.
%
% Training occurs according to training parameters, with default values.
% Any or all of these can be overridden with parameter name/value argument
% pairs appended to the input argument list, or by appending a structure
% argument with fields having one or more of these names.
% show 25 Epochs between displays
% showCommandLine 0 generate command line output
% showWindow 1 show training GUI
% epochs 100 Maximum number of epochs to train
% goal 0 Performance goal
% max_fail 5 Maximum validation failures
% min_grad 1e-10 Minimum performance gradient
% mu 0.001 Initial Mu
% mu_dec 0.1 Mu decrease factor
% mu_inc 10 Mu increase factor
% mu_max 1e10 Maximum Mu
% time inf Maximum time to train in seconds
%
% To make this the default training function for a network, and view
% and/or change parameter settings, use these two properties:
%
% net.<a href="matlab:doc nnproperty.net_trainFcn">trainFcn</a> = 'trainlm';
% net.<a href="matlab:doc nnproperty.net_trainParam">trainParam</a>
%
% See also trainscg, feedforwardnet, narxnet.
% Mark Beale, 11-31-97, ODJ 11/20/98
% Updated by Orlando De Jes鹥, Martin Hagan, Dynamic Training 7-20-05
% Copyright 1992-2010 The MathWorks, Inc.
% $Revision: 1.1.6.11.2.2 $ $Date: 2010/07/23 15:40:16 $
%% =======================================================
% BOILERPLATE_START
% This code is the same for all Training Functions.
persistent INFO;
if isempty(INFO), INFO = get_info; end
nnassert.minargs(nargin,1);
in1 = varargin{1};
if ischar(in1)
switch (in1)
case 'info'
out1 = INFO;
case 'check_param'
nnassert.minargs(nargin,2);
param = varargin{2};
err = nntest.param(INFO.parameters,param);
if isempty(err)
err = check_param(param);
end
if nargout > 0
out1 = err;
elseif ~isempty(err)
nnerr.throw('Type',err);
end
otherwise,
try
out1 = eval(['INFO.' in1]);
catch me, nnerr.throw(['Unrecognized first argument: ''' in1 ''''])
end
end
return
end
nnassert.minargs(nargin,2);
net = nn.hints(nntype.network('format',in1,'NET'));
oldTrainFcn = net.trainFcn;
oldTrainParam = net.trainParam;
if ~strcmp(net.trainFcn,mfilename)
net.trainFcn = mfilename;
net.trainParam = INFO.defaultParam;
end
[args,param] = nnparam.extract_param(varargin(2:end),net.trainParam);
err = nntest.param(INFO.parameters,param);
if ~isempty(err), nnerr.throw(nnerr.value(err,'NET.trainParam')); end
if INFO.isSupervised && isempty(net.performFcn) % TODO - fill in MSE
nnerr.throw('Training function is supervised but NET.performFcn is undefined.');
end
if INFO.usesGradient && isempty(net.derivFcn) % TODO - fill in
nnerr.throw('Training function uses derivatives but NET.derivFcn is undefined.');
end
if net.hint.zeroDelay, nnerr.throw('NET contains a zero-delay loop.'); end
[X,T,Xi,Ai,EW] = nnmisc.defaults(args,{},{},{},{},{1});
X = nntype.data('format',X,'Inputs X');
T = nntype.data('format',T,'Targets T');
Xi = nntype.data('format',Xi,'Input states Xi');
Ai = nntype.data('format',Ai,'Layer states Ai');
EW = nntype.nndata_pos('format',EW,'Error weights EW');
% Prepare Data
[net,data,tr,~,err] = nntraining.setup(net,mfilename,X,Xi,Ai,T,EW);
if ~isempty(err), nnerr.throw('Args',err), end
% Train
net = struct(net);
fcns = nn.subfcns(net);
[net,tr] = train_network(net,tr,data,fcns,param);
tr = nntraining.tr_clip(tr);
if isfield(tr,'perf')
tr.best_perf = tr.perf(tr.best_epoch+1);
end
if isfield(tr,'vperf')
tr.best_vperf = tr.vperf(tr.best_epoch+1);
end
if isfield(tr,'tperf')
tr.best_tperf = tr.tperf(tr.best_epoch+1);
end
net.trainFcn = oldTrainFcn;
net.trainParam = oldTrainParam;
out1 = network(net);
out2 = tr;
end
% BOILERPLATE_END
%% =======================================================
% TODO - MU => MU_START
% TODO - alternate parameter names (i.e. MU for MU_START)
function info = get_info()
info = nnfcnTraining(mfilename,'Levenberg-Marquardt',7.0,true,true,...
[ ...
nnetParamInfo('showWindow','Show Training Window Feedback','nntype.bool_scalar',true,...
'Display training window ring training.'), ...
nnetParamInfo('showCommandLine','Show Command Line Feedback','nntype.bool_scalar',false,...
'Generate command line output ring training.'), ...
nnetParamInfo('show','Command Line Frequency','nntype.strict_pos_int_inf_scalar',25,...
'Frequency to update command line.'), ...
...
nnetParamInfo('epochs','Maximum Epochs','nntype.pos_int_scalar',1000,...
'Maximum number of training iterations before training is stopped.'), ...
nnetParamInfo('time','Maximum Training Time','nntype.pos_inf_scalar',inf,...
'Maximum time in seconds before training is stopped.'), ...
...
nnetParamInfo('goal','Performance Goal','nntype.pos_scalar',0,...
'Performance goal.'), ...
nnetParamInfo('min_grad','Minimum Gradient','nntype.pos_scalar',1e-5,...
'Minimum performance gradient before training is stopped.'), ...
nnetParamInfo('max_fail','Maximum Validation Checks','nntype.strict_pos_int_scalar',6,...
'Maximum number of validation checks before training is stopped.'), ...
...
nnetParamInfo('mu','Mu','nntype.pos_scalar',0.001,...
'Mu.'), ...
nnetParamInfo('mu_dec','Mu Decrease Ratio','nntype.real_0_to_1',0.1,...
'Ratio to decrease mu.'), ...
nnetParamInfo('mu_inc','Mu Increase Ratio','nntype.over1',10,...
'Ratio to increase mu.'), ...
nnetParamInfo('mu_max','Maximum mu','nntype.strict_pos_scalar',1e10,...
'Maximum mu before training is stopped.'), ...
], ...
[ ...
nntraining.state_info('gradient','Gradient','continuous','log') ...
nntraining.state_info('mu','Mu','continuous','log') ...
nntraining.state_info('val_fail','Validation Checks','discrete','linear') ...
]);
end
function err = check_param(param)
err = '';
end
function [net,tr] = train_network(net,tr,data,fcns,param)
% Checks
if isempty(net.performFcn)
warning('nnet:trainlm:Performance',nnwarning.empty_performfcn_corrected);
net.performFcn = 'mse';
net.performParam = mse('defaultParam');
tr.performFcn = net.performFcn;
tr.performParam = net.performParam;
end
if isempty(strmatch(net.performFcn,{'sse','mse'},'exact'))
warning('nnet:trainlm:Performance',nnwarning.nonjacobian_performfcn_replaced);
net.performFcn = 'mse';
net.performParam = mse('defaultParam');
tr.performFcn = net.performFcn;
tr.performParam = net.performParam;
end
% Initialize
startTime = clock;
original_net = net;
[perf,vperf,tperf,je,jj,gradient] = nntraining.perfs_jejj(net,data,fcns);
[best,val_fail] = nntraining.validation_start(net,perf,vperf);
WB = getwb(net);
lengthWB = length(WB);
ii = sparse(1:lengthWB,1:lengthWB,ones(1,lengthWB));
mu = param.mu;
% Training Record
tr.best_epoch = 0;
tr.goal = param.goal;
tr.states = {'epoch','time','perf','vperf','tperf','mu','gradient','val_fail'};
% Status
status = ...
[ ...
nntraining.status('Epoch','iterations','linear','discrete',0,param.epochs,0), ...
nntraining.status('Time','seconds','linear','discrete',0,param.time,0), ...
nntraining.status('Performance','','log','continuous',perf,param.goal,perf) ...
nntraining.status('Gradient','','log','continuous',gradient,param.min_grad,gradient) ...
nntraining.status('Mu','','log','continuous',mu,param.mu_max,mu) ...
nntraining.status('Validation Checks','','linear','discrete',0,param.max_fail,0) ...
];
nn_train_feedback('start',net,status);
% Train
for epoch = 0:param.epochs
% Stopping Criteria
current_time = etime(clock,startTime);
[userStop,userCancel] = nntraintool('check');
if userStop, tr.stop = 'User stop.'; net = best.net;
elseif userCancel, tr.stop = 'User cancel.'; net = original_net;
elseif (perf <= param.goal), tr.stop = 'Performance goal met.'; net = best.net;
elseif (epoch == param.epochs), tr.stop = 'Maximum epoch reached.'; net = best.net;
elseif (current_time >= param.time), tr.stop = 'Maximum time elapsed.'; net = best.net;
elseif (gradient <= param.min_grad), tr.stop = 'Minimum gradient reached.'; net = best.net;
elseif (mu >= param.mu_max), tr.stop = 'Maximum MU reached.'; net = best.net;
elseif (val_fail >= param.max_fail), tr.stop = 'Validation stop.'; net = best.net;
end
% Feedback
tr = nntraining.tr_update(tr,[epoch current_time perf vperf tperf mu gradient val_fail]);
nn_train_feedback('update',net,status,tr,data, ...
[epoch,current_time,best.perf,gradient,mu,val_fail]);
% Stop
if ~isempty(tr.stop), break, end
% Levenberg Marquardt
while (mu <= param.mu_max)
% CHECK FOR SINGULAR MATRIX
[msgstr,msgid] = lastwarn;
lastwarn('MATLAB:nothing','MATLAB:nothing')
warnstate = warning('off','all');
dWB = -(jj+ii*mu) \ je;
[~,msgid1] = lastwarn;
flag_inv = isequal(msgid1,'MATLAB:nothing');
if flag_inv, lastwarn(msgstr,msgid); end;
warning(warnstate)
WB2 = WB + dWB;
net2 = setwb(net,WB2);
perf2 = nntraining.train_perf(net2,data,fcns);
% TODO - possible speed enhancement
% - retain intermediate variables for Memory Rection = 1
if (perf2 < perf) && flag_inv
WB = WB2; net = net2;
mu = max(mu*param.mu_dec,1e-20);
break
end
mu = mu * param.mu_inc;
end
% Validation
[perf,vperf,tperf,je,jj,gradient] = nntraining.perfs_jejj(net,data,fcns);
[best,tr,val_fail] = nntraining.validation(best,tr,val_fail,net,perf,vperf,epoch);
end
end
⑸ 有哪位大神知道BP神经网络变学习率学习算法在Matlab中怎么实现啊
额。。。
一种启发式的改进就是,为学习速率选用自适应值,它依赖于连续迭代步骤中的误差函数值。
自适应调整学习速率的梯度下降算法,在训练的过程中,力图使算法稳定,同时又使学习的步长尽量地大,学习速率则是根据局部误差曲面作出相应的调整。当误差以减小的方式趋于目标时,说明修正方向正确,于是步长(学习速率)增加,因此学习速率乘以增量因子Ir_inc,使学习速率增加;而当误差增加超过设定的值C倍时,说明修正过头,应减小步长,因此学习速率乘以减量因子Ir_dec,使学习速率减少.其他情况学习速率则不变。
Matlab 里有对应的变学习速率的函数。
bpnet=newff(x,[60,4],{'logsig','logsig'},'traingda'); %'traingda'表示自适应学习速率调整方法
bpnet.trainParam.show=50;
bpnet.trainParam.lr=0.01; %预设值的学习速率
bpnet.trainParam.epochs=3000;
bpnet.trainParam.goal=0.247;
bpnet.trainParam.Ir_inc=1.05; %增加的学习速率倍数,默认为1.05
bpnet.trainParam.Ir_dec=0.7; %减少的学习速率倍数,默认为0.7
bpnet.trainParam.max_perf_inc=1.04; %误差函数增加为迭代前的1.04时,减少学习速率。默认为1.04
[bpnet]=train(bpnet,p,t);
save bpnet;
%%%%%%%%%%%%%%%%%%%%
⑹ bp神经网络算法 在matlab中的实现
BP神经网络是最基本、最常用的神经网络,Matlab有专用函数来建立、训练它,主要就是newff()、train()、sim()这三个函数,当然其他如归一化函数mapminmax()、其他net的参数设定(lr、goal等)设置好,就可以通过对历史数据的学习进行预测。附件是一个最基本的预测实例,本来是电力负荷预测的实例,但具有通用性,你仔细看看就明白了。
⑺ Matlab神经网络原理中可以用于寻找最优解的算法有哪些
若果对你有帮助,请点赞。
神经网络的结构(例如2输入3隐节点1输出)建好后,一般就要求神经网络里的权值和阈值。现在一般求解权值和阈值,都是采用梯度下降之类的搜索算法(梯度下降法、牛顿法、列文伯格-马跨特法、狗腿法等等),这些算法会先初始化一个解,在这个解的基础上,确定一个搜索方向和一个移动步长(各种法算确定方向和步长的方法不同,也就使各种算法适用于解决不同的问题),使初始解根据这个方向和步长移动后,能使目标函数的输出(在神经网络中就是预测误差)下降。 然后将它更新为新的解,再继续寻找下一步的移动方向的步长,这样不断的迭代下去,目标函数(神经网络中的预测误差)也不断下降,最终就能找到一个解,使得目标函数(预测误差)比较小。
而在寻解过程中,步长太大,就会搜索得不仔细,可能跨过了优秀的解,而步长太小,又会使寻解过程进行得太慢。因此,步长设置适当非常重要。
学习率对原步长(在梯度下降法中就是梯度的长度)作调整,如果学习率lr = 0.1,那么梯度下降法中每次调整的步长就是0.1*梯度,
而在matlab神经网络工具箱里的lr,代表的是初始学习率。因为matlab工具箱为了在寻解不同阶段更智能的选择合适的步长,使用的是可变学习率,它会根据上一次解的调整对目标函数带来的效果来对学习率作调整,再根据学习率决定步长。
机制如下:
if newE2/E2 > maxE_inc %若果误差上升大于阈值
lr = lr * lr_dec; %则降低学习率
else
if newE2 < E2 %若果误差减少
lr = lr * lr_inc;%则增加学习率
end
详细的可以看《神经网络之家》nnetinfo里的《[重要]写自己的BP神经网络(traingd)》一文,里面是matlab神经网络工具箱梯度下降法的简化代码
⑻ 自己用matlab实现的BP神经网络算法,无法得到预期的效果,主要是误差太大
lr=0.05; %lr为学习速率;
err_goal=0.1; %err_goal为期望误差最小值
max_epoch=15000; %max_epoch为训练的最大次数;
a=0.9; %a为惯性系数
Oi=0;
Ok=0; %置隐含层和输出层各神经元输出初值为0
这些初始参数是谁提供给你?
调整一下这些参数看看.
⑼ 在MATLAB中用神经网络算法求解无约束最优化问题
程序一:GA训练BP权值的主函数 function net=GABPNET(XX,YY) % 使用遗传算法对BP网络权值阈值进行优化,再用BP算法训练网络 %数据归一化预处理 nntwarn off XX=[1:19;2:20;3:21;4:22]'; YY=[1:4]; XX=premnmx(XX); YY=premnmx(YY); YY %创建网络 net=newff(minmax(XX),[19,25,1],{'tansig','tansig','purelin'},'trainlm'); %下面使用遗传算法对网络进行优化 P=XX; T=YY; R=size(P,1); S2=size(T,1); S1=25;%隐含层节点数 S=R*S1+S1*S2+S1+S2;%遗传算法编码长度 aa=ones(S,1)*[-1,1]; popu=50;%种群规模 save data2 XX YY % 是将 xx,yy 二个变数的数值存入 data2 这个MAT-file, initPpp=initializega(popu,aa,'gabpEval');%初始化种群 gen=100;%遗传代数 %下面调用gaot工具箱,其中目标函数定义为gabpEval [x,endPop,bPop,trace]=ga(aa,'gabpEval',[],initPpp,[1e-6 1 1],'maxGenTerm',gen,... 'normGeomSelect',[0.09],['arithXover'],[2],'nonUnifMutation',[2 gen 3]); %绘收敛曲线图 figure(1) plot(trace(:,1),1./trace(:,3),'r-'); hold on plot(trace(:,1),1./trace(:,2),'b-'); xlabel('Generation'); ylabel('Sum-Squared Error'); figure(2) plot(trace(:,1),trace(:,3),'r-'); hold on plot(trace(:,1),trace(:,2),'b-'); xlabel('Generation'); ylabel('Fittness');
⑽ matlab中的BP神经网络
从原理上来说,神经网络是可以预测未来的点的。
实际上,经过训练之后,神经网络就拟合了输入和输出数据之间的函数关系。只要训练的足够好,那么这个拟合的关系就会足够准确,从而能够预测在其他的输入情况下,会有什么样的输出。
如果要预测t=[6
7]两点的R值,先以t=[1
2
3
4
5]作为输入,R=[12
13
14
14
15]作为输出,训练网络。训练完成之后,用t=[2
3
4
5
6]作为输入,这样会得到一个输出。不出意外的话,输出的数组应该是[13
14
14
15
X],这里的X就是预测t=6时的R值。然后以t=[3
4
5
6
7]作为输入,同理得到t=7时候的R值。
根据我的神经网络预测,t=6时,R=15,t=7时,R=15。我不知道这个结果是否正确,因为神经网络通常需要大量的数据来训练,而这里给的数据似乎太少,可能不足以拟合出正确的函数。