📄 bpnet.cpp
字号:
// BPnet.cpp: implementation of the BPnet class.
//
//////////////////////////////////////////////////////////////////////
#include "stdafx.h"
#include "BPtoXorS.h"
#include "BPnet.h"
#ifdef _DEBUG
#undef THIS_FILE
static char THIS_FILE[]=__FILE__;
#define new DEBUG_NEW
#endif
//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////
BPnet::BPnet()
{
//input[]={0.05 , 0.95}; //为什么这样给数组赋值在vc++中就会出错 ?
input[0] = 0.05;
input[1] = 0.95;
output = 1.0;
//threshold_m[] = {rand() , rand()};
/*double AverageRandom(double min,double max)
{
int minInteger = (int)(min*10000);
int maxInteger = (int)(max*10000);
int randInteger = rand()*rand();
int diffInteger = maxInteger - minInteger;
int resultInteger = randInteger % diffInteger + minInteger;
return resultInteger/10000.0;
}*/
srand( (unsigned)time( NULL ) );
for(int i=0; i<2; i++)
threshold_m[i] = AverageRandom(-1,1);
threshold_o = AverageRandom(-1,1);
//w_middle[] = {rand() , rand() , rand() , rand()};
for(i=0; i<4; i++)
w_middle[i] = AverageRandom(-1,1);
//w_output[] = {rand() , rand()};
for(i=0; i<2; i++)
w_output[i] = AverageRandom(-1,1);
for(i=0; i<2; i++)
{
middle_s[i] = 0; //zero
middle_o[i] = 0; //zero
}
output_s = 0;
output_o = 0;
u0 = 0.3;
a = 0.5;
b = 0.5;
error = 5.0;
}
BPnet::~BPnet()
{
}
void BPnet::train()
{
//计算中间层激活值
for(int i=0; i<2; i++)
middle_s[0] += w_middle[i] * input[i];
middle_s[0] -= threshold_m[0];
for(i=0; i<2; i++)
middle_s[1] += w_middle[i+2] * input[i];
middle_s[1] -= threshold_m[1];
//中间层的输出值
for(i=0; i<2; i++)
middle_o[i] = 0.5 * (1 + tan(middle_s[i] / u0));
//输出层的激活值
for(i=0; i<2; i++)
output_s +=w_output[i] * middle_o[i];
output_s -= threshold_o;
//输出层的输出值
output_o = 0.5 * (1 + tan(output_s / u0));
//输出误差的逆传播
//输出层的矫正误差
error_o = (output - output_o) * output_o * (1 + output_o);
//中间层个单元的矫正误差
for(i=0; i<2; i++)
error_m[i] = w_output[i] * error_o * middle_o[i] *(1 + middle_o[i]);
//重新计算输出层到中间层的权值和输出层的阈值
for(i=0; i<2; i++)
w_output[i] += a * error_o * middle_o[i];
threshold_o += a * error_o;
//重新计算中间层到输入层的权值和中间层的阈值
w_middle[0] += b * error_m[0] * input[0];
w_middle[1] += b * error_m[1] * input[0];
w_middle[2] += b * error_m[0] * input[1];
w_middle[3] += b * error_m[1] * input[1];
threshold_m[0] += b * error_m[0];
threshold_m[1] += b * error_m[1];
//计算误差
error = fabs(output - output_o);
}
//求随机数
double BPnet::AverageRandom(double min, double max)
{
int minInteger = (int)(min*10000);
int maxInteger = (int)(max*10000);
int randInteger = rand()*rand();
int diffInteger = maxInteger - minInteger;
int resultInteger = randInteger % diffInteger + minInteger;
return resultInteger/10000.0;
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -