1.matlab BP神经网络的源码训练算法中训练函数(traingdm 、trainlm、源码trainbr)的源码实现过程及相应的VC源代码
2.用C++编写的小游戏源代码
matlab BP神经网络的训练算法中训练函数(traingdm 、trainlm、源码trainbr)的源码无限火力源码实现过程及相应的VC源代码
VC源代码?你很搞笑嘛。。源码cpr源码分析
给你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 Epochs between displays
% showCommandLine 0 generate command line output
% showWindow 1 show training GUI
% epochs Maximum number of epochs to train
% goal 0 Performance goal
% max_fail 5 Maximum validation failures
% min_grad 1e- Minimum performance gradient
% mu 0. Initial Mu
% mu_dec 0.1 Mu decrease factor
% mu_inc Mu increase factor
% mu_max 1e 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, --, ODJ //
% Updated by Orlando De Jes鷖, Martin Hagan, Dynamic Training 7--
% Copyright - The MathWorks, Inc.
% $Revision: 1.1.6..2.2 $ $Date: // :: $
%% =======================================================
% 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 during training.'), ...
nnetParamInfo('showCommandLine','Show Command Line Feedback','nntype.bool_scalar',false,...
'Generate command line output during training.'), ...
nnetParamInfo('show','Command Line Frequency','nntype.strict_pos_int_inf_scalar',,...
'Frequency to update command line.'), ...
...
nnetParamInfo('epochs','Maximum Epochs','nntype.pos_int_scalar',,...
'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.,...
'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',,...
'Ratio to increase mu.'), ...
nnetParamInfo('mu_max','Maximum mu','nntype.strict_pos_scalar',1e,...
'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 Reduction = 1
if (perf2 < perf) && flag_inv
WB = WB2; net = net2;
mu = max(mu*param.mu_dec,1e-);
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
用C++编写的小游戏源代码
五子棋的代码:#include<iostream>
#include<stdio.h>
#include<stdlib.h>
#include <time.h>
using namespace std;
const int N=; //*的棋盘
const char ChessBoardflag = ' '; //棋盘标志
const char flag1='o'; //玩家1或电脑的棋子标志
const char flag2='X'; //玩家2的棋子标志
typedef struct Coordinate //坐标类
{
int x; //代表行
int y; //代表列
}Coordinate;
class GoBang //五子棋类
{
public:
GoBang() //初始化
{
InitChessBoard();
}
void Play() //下棋
{
Coordinate Pos1; // 玩家1或电脑
Coordinate Pos2; //玩家2
int n = 0;
while (1)
{
int mode = ChoiceMode();
while (1)
{
if (mode == 1) //电脑vs玩家
{
ComputerChess(Pos1,flag1); // 电脑下棋
if (GetVictory(Pos1, 0, flag1) == 1) //0表示电脑,真表示获胜
break;
PlayChess(Pos2, 2, flag2); //玩家2下棋
if (GetVictory(Pos2, 2, flag2)) //2表示玩家2
break;
}
else //玩家1vs玩家2
{
PlayChess(Pos1, 1, flag1); // 玩家1下棋
if (GetVictory(Pos1, 1, flag1)) //1表示玩家1
break;
PlayChess(Pos2, 2, flag2); //玩家2下棋
if (GetVictory(Pos2, 2, flag2)) //2表示玩家2
break;
}
}
cout << "***再来一局***" << endl;
cout << "y or n :";
char c = 'y';
cin >> c;
if (c == 'n')
break;
}
}
protected:
int ChoiceMode() //选择模式
{
int i = 0;
system("cls"); //系统调用,清屏
InitChessBoard(); //重新初始化棋盘
cout << "***0、源码退出 1、源码电脑vs玩家 2、源码玩家vs玩家***" << endl;
while (1)
{
cout << "请选择:";
cin >> i;
if (i == 0) //选择0退出
exit(1);
if (i == 1 || i == 2)
return i;
cout << "输入不合法" << endl;
}
}
void InitChessBoard() //初始化棋盘
{
for (int i = 0; i < N + 1; ++i)
{
for (int j = 0; j < N + 1; ++j)
{
_ChessBoard[i][j] = ChessBoardflag;
}
}
}
void PrintChessBoard() //打印棋盘,源码这个函数可以自己调整
{
system("cls"); //系统调用,源码清空屏幕
for (int i = 0; i < N+1; ++i)
{
for (int j = 0; j < N+1; ++j)
{
if (i == 0) //打印列数字
{
if (j!=0)
printf("%d ",源码企业源码打包 j);
else
printf(" ");
}
else if (j == 0) //打印行数字
printf("%2d ", i);
else
{
if (i < N+1)
{
printf("%c |",_ChessBoard[i][j]);
}
}
}
cout << endl;
cout << " ";
for (int m = 0; m < N; m++)
{
printf("--|");
}
cout << endl;
}
}
void PlayChess(Coordinate& pos, int player, int flag) //玩家下棋
{
PrintChessBoard(); //打印棋盘
while (1)
{
printf("玩家%d输入坐标:", player);
cin >> pos.x >> pos.y;
if (JudgeValue(pos) == 1) //坐标合法
break;
cout << "坐标不合法,重新输入" << endl;
}
_ChessBoard[pos.x][pos.y] = flag;
}
void ComputerChess(Coordinate& pos,源码 char flag) //电脑下棋
{
PrintChessBoard(); //打印棋盘
int x = 0;
int y = 0;
while (1)
{
x = (rand() % N) + 1; //产生1~N的随机数
srand((unsigned int) time(NULL));
y = (rand() % N) + 1; //产生1~N的随机数
srand((unsigned int) time(NULL));
if (_ChessBoard[x][y] == ChessBoardflag) //如果这个位置是空的,也就是源码没有棋子
break;
}
pos.x = x;
pos.y = y;
_ChessBoard[pos.x][pos.y] = flag;
}
int JudgeValue(const Coordinate& pos) //判断输入坐标是不是合法
{
if (pos.x > 0 && pos.x <= N&&pos.y > 0 && pos.y <= N)
{
if (_ChessBoard[pos.x][pos.y] == ChessBoardflag)
{
return 1; //合法
}
}
return 0; //非法
}
int JudgeVictory(Coordinate pos, char flag) //判断有没有人胜负(底层判断)
{
int begin = 0;
int end = 0;
int begin1 = 0;
int end1 = 0;
//判断行是否满足条件
(pos.y - 4) > 0 ? begin = (pos.y - 4) : begin = 1;
(pos.y + 4) >N ? end = N : end = (pos.y + 4);
for (int i = pos.x, j = begin; j + 4 <= end; j++)
{
if (_ChessBoard[i][j] == flag&&_ChessBoard[i][j + 1] == flag&&
_ChessBoard[i][j + 2] == flag&&_ChessBoard[i][j + 3] == flag&&
_ChessBoard[i][j + 4] == flag)
return 1;
}
//判断列是否满足条件
(pos.x - 4) > 0 ? begin = (pos.x - 4) : begin = 1;
(pos.x + 4) > N ? end = N : end = (pos.x + 4);
for (int j = pos.y, i = begin; i + 4 <= end; i++)
{
if (_ChessBoard[i][j] == flag&&_ChessBoard[i + 1][j] == flag&&
_ChessBoard[i + 2][j] == flag&&_ChessBoard[i + 3][j] == flag&&
_ChessBoard[i + 4][j] == flag)
return 1;
}
int len = 0;
//判断主对角线是否满足条件
pos.x > pos.y ? len = pos.y - 1 : len = pos.x - 1;
if (len > 4)
len = 4;
begin = pos.x - len; //横坐标的起始位置
begin1 = pos.y - len; //纵坐标的起始位置
pos.x > pos.y ? len = (N - pos.x) : len = (N - pos.y);
if (len>4)
len = 4;
end = pos.x + len; //横坐标的结束位置
end1 = pos.y + len; //纵坐标的结束位置
for (int i = begin, j = begin1; (i + 4 <= end) && (j + 4 <= end1); ++i, ++j)
{
if (_ChessBoard[i][j] == flag&&_ChessBoard[i + 1][j + 1] == flag&&
_ChessBoard[i + 2][j + 2] == flag&&_ChessBoard[i + 3][j + 3] == flag&&
_ChessBoard[i + 4][j + 4] == flag)
return 1;
}
//判断副对角线是否满足条件
(pos.x - 1) >(N - pos.y) ? len = (N - pos.y) : len = pos.x - 1;
if (len > 4)
len = 4;
begin = pos.x - len; //横坐标的起始位置
begin1 = pos.y + len; //纵坐标的起始位置
(N - pos.x) > (pos.y - 1) ? len = (pos.y - 1) : len = (N - pos.x);
if (len>4)
len = 4;
end = pos.x + len; //横坐标的结束位置
end1 = pos.y - len; //纵坐标的结束位置
for (int i = begin, j = begin1; (i + 4 <= end) && (j - 4 >= end1); ++i, --j)
{
if (_ChessBoard[i][j] == flag&&_ChessBoard[i + 1][j - 1] == flag&&
_ChessBoard[i + 2][j - 2] == flag&&_ChessBoard[i + 3][j - 3] == flag&&
_ChessBoard[i + 4][j - 4] == flag)
return 1;
}
for (int i = 1; i < N + 1; ++i) //棋盘有没有下满
{
for (int j =1; j < N + 1; ++j)
{
if (_ChessBoard[i][j] == ChessBoardflag)
return 0; //0表示棋盘没满
}
}
return -1; //和棋
}
bool GetVictory(Coordinate& pos, int player, int flag) //对JudgeVictory的一层封装,得到具体那个玩家获胜
{
int n = JudgeVictory(pos, flag); //判断有没有人获胜
if (n != 0) //有人获胜,0表示没有人获胜
{
PrintChessBoard();
if (n == 1) //有玩家赢棋
{
if (player == 0) //0表示电脑获胜,成品源码19881表示玩家1,2表示玩家2
printf("***电脑获胜***\n");
else
printf("***恭喜玩家%d获胜***\n", player);
}
else
printf("***双方和棋***\n");
return true; //已经有人获胜
}
return false; //没有人获胜
}
private:
char _ChessBoard[N+1][N+1];
};
扩展资料:
设计思路
1、进行问题分析与设计,计划实现的功能为,开局选择人机或双人对战,dylib源码在哪确定之后比赛开始。
2、比赛结束后初始化棋盘,询问是否继续比赛或退出,后续可加入复盘、悔棋等功能。
3、整个过程中,涉及到了棋子和棋盘两种对象,同时要加上人机对弈时的AI对象,即涉及到三个对象。