本文实例为大家分享了C++实现神经BP神经网络的具体代码,供大家参考,具体内容如下
BP.h
#pragma once #include#include #include #include #include using std::vector; using std::exp; using std::cout; using std::endl; class BP { private: int studyNum;//允许学习次数 double h;//学习率 double allowError;//允许误差 vector layerNum;//每层的节点数,不包括常量节点1 vector >> w;//权重 vector >> dw;//权重增量 vector > b;//偏置 vector > db;//偏置增量 vector >> a;//节点值 vector > x;//输入 vector > y;//期望输出 void iniwb();//初始化w与b void inidwdb();//初始化dw与db double sigmoid(double z);//激活函数 void forward();//前向传播 void backward();//后向传播 double Error();//计算误差 public: BP(vector const& layer_num, vector >const & input_a0, vector > const & output_y, double hh = 0.5, double allerror = 0.001, int studynum = 1000); BP(); void setLayerNumInput(vector const& layer_num, vector > const & input); void setOutputy(vector > const & output_y); void setHErrorStudyNum(double hh, double allerror,int studynum); void run();//运行BP神经网络 vector predict(vector & input);//使用已经学习好的神经网络进行预测 ~BP(); };
BP.cpp
#include "BP.h" BP::BP(vectorconst& layer_num, vector >const & input, vector > const & output_y, double hh, double allerror,int studynum) { layerNum = layer_num; x = input;//输入多少个节点的数据,每个节点有多少份数据 y = output_y; h = hh; allowError = allerror; a.resize(layerNum.size());//有这么多层网络节点 for (int i = 0; i const& layer_num, vector > const & input) { layerNum = layer_num; x = input; a.resize(layerNum.size());//有这么多层网络节点 for (int i = 0; i > const & output_y) { y = output_y; } void BP::setHErrorStudyNum(double hh, double allerror,int studynum) { h = hh; allowError = allerror; studyNum = studynum; } //初始化权重矩阵 void BP::iniwb() { w.resize(layerNum.size() - 1); b.resize(layerNum.size() - 1); srand((unsigned)time(NULL)); //节点层数层数 for (int l = 0; l daP, daB; for (int j = 0; j 0; l--) { daB = daP; daP.clear(); daP.resize(layerNum[l]); for (int k = 0; k BP::predict(vector & input) { vector > a1; a1.resize(layerNum.size()); for (int l = 0; l
验证程序:
#include"BP.h" int main() { vectorlayer_num = { 1, 10, 1 }; vector > input_a0 = { { 1,2,3,4,5,6,7,8,9,10 } }; vector > output_y = { {0,0,0,0,1,1,1,1,1,1} }; BP bp(layer_num, input_a0,output_y,0.6,0.001, 2000); bp.run(); for (int j = 0; j <30; j++) { vector input = { 0.5*j }; vector output = bp.predict(input); for (auto i : output) cout <<"j:" <<0.5*j <<" pridict:" <
输出:
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。