📄 bpyy.cpp
字号:
#include <iostream.h>
#include <math.h>
#include <stdlib.h>
#include <time.h>
#define k (float)(0.5) // 学习系数
#define BPM_ITER 6000//迭代次数
class CBPyy
{
public:
CBPyy();
~CBPyy() {};
float Train(float, float, float);
float Run(float, float);
private:
float W[3][3]; // 3个神经元
float Sigmoid(float); // S形函数
};
CBPyy::CBPyy()
{
srand((unsigned)(time(NULL)));
for (int i=0;i<3;i++)
{
for (int j=0;j<3;j++)
{
// 由于一些原因,微软提供的rand()函数产生的随机数是
// 整数,所以需要将之做适当的变换,变到-1~1之间
W[i][j] = (float)(rand())/(32767/2) - 1;
}
}
}
//训练网络
float CBPyy::Train(float i1, float i2, float d)
{
// 变量
float net1, net2, i3, i4, out;
// 计算隐含层的神经元值
net1 = 1 * W[0][0] + i1 * W[1][0] +
i2 * W[2][0];
net2 = 1 * W[0][1] + i1 * W[1][1] +
i2 * W[2][1];
// 使用S函数
i3 = Sigmoid(net1);
i4 = Sigmoid(net2);
// 计算输出层的值
net1 = 1 * W[0][2] + i3 * W[1][2] +
i4 * W[2][2];
out = Sigmoid(net1);
//计算误差,反向传播
float deltas[3];
deltas[2] = out*(1-out)*(d-out);
deltas[1] = i4*(1-i4)*(W[2][2])*(deltas[2]);
deltas[0] = i3*(1-i3)*(W[1][2])*(deltas[2]);
// 调整权值
float v1 = i1, v2 = i2;
for(int i=0;i<3;i++)
{
// 如果有必要,改变输出层的值
if (i == 2)
{
v1 = i3;
v2 = i4;
}
W[0][i] += k*1*deltas[i];
W[1][i] += k*v1*deltas[i];
W[2][i] += k*v2*deltas[i];
}
return out;
}
//S函数
float CBPyy::Sigmoid(float num)
{
return (float)(1/(1+exp(-num)));
}
//运行网络
float CBPyy::Run(float i1, float i2)
{
float net1, net2, i3, i4;
net1 = 1 * W[0][0] + i1 * W[1][0] +
i2 * W[2][0];
net2 = 1 * W[0][1] + i1 * W[1][1] +
i2 * W[2][1];
i3 = Sigmoid(net1);
i4 = Sigmoid(net2);
net1 = 1 * W[0][2] + i3 * W[1][2] +
i4 * W[2][2];
return Sigmoid(net1);
}
void main() {
CBPyy or;
CBPyy and;
CBPyy bp;
for (int i=0;i<BPM_ITER;i++) {
bp.Train(0,0,0); //异或
bp.Train(0,1,1);
bp.Train(1,0,1);
bp.Train(1,1,0);
or.Train (0,0,0); //或
or.Train (0,1,1);
or.Train (1,0,1);
or.Train (1,1,1);
and.Train (0,0,0); //与
and.Train (0,1,0);
and.Train (1,0,0);
and.Train (1,1,1);
}
cout <<"与:"<<endl;
cout << "0,0 = " << and.Run(0,0) << endl;
cout << "0,1 = " << and.Run(0,1) << endl;
cout << "1,0 = " << and.Run(1,0) << endl;
cout << "1,1 = " << and.Run(1,1) << endl;
cout <<"或:"<<endl;
cout << "0,0 = " << or.Run(0,0) << endl;
cout << "0,1 = " << or.Run(0,1) << endl;
cout << "1,0 = " << or.Run(1,0) << endl;
cout << "1,1 = " << or.Run(1,1) << endl;
cout <<"异或:"<<endl;
cout << "0,0 = " << bp.Run(0,0) << endl;
cout << "0,1 = " << bp.Run(0,1) << endl;
cout << "1,0 = " << bp.Run(1,0) << endl;
cout << "1,1 = " << bp.Run(1,1) << endl;
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -