C++实现神经实现神经BP神经网络神经网络
本文实例为大家分享了C++实现神经BP神经网络的具体代码,供大家参考,具体内容如下
BP.h
#pragma once
#include<vector>
#include<stdlib.h>
#include<time.h>
#include<cmath>
#include<iostream>
using std::vector;
using std::exp;
using std::cout;
using std::endl;
class BP
{
private:
int studyNum;//允许学习次数
double h;//学习率
double allowError;//允许误差
vector<int> layerNum;//每层的节点数,不包括常量节点1
vector<vector<vector<double>>> w;//权重
vector<vector<vector<double>>> dw;//权重增量
vector<vector<double>> b;//偏置
vector<vector<double>> db;//偏置增量
vector<vector<vector<double>>> a;//节点值
vector<vector<double>> x;//输入
vector<vector<double>> y;//期望输出
void iniwb();//初始化w与b
void inidwdb();//初始化dw与db
double sigmoid(double z);//激活函数
void forward();//前向传播
void backward();//后向传播
double Error();//计算误差
public:
BP(vector<int>const& layer_num, vector<vector<double>>const & input_a0,
vector<vector<double>> const & output_y, double hh = 0.5, double allerror = 0.001, int studynum = 1000);
BP();
void setLayerNumInput(vector<int>const& layer_num, vector<vector<double>> const & input);
void setOutputy(vector<vector<double>> const & output_y);
void setHErrorStudyNum(double hh, double allerror,int studynum);
void run();//运行BP神经网络
vector<double> predict(vector<double>& input);//使用已经学习好的神经网络进行预测
~BP();
};
BP.cpp
#include "BP.h"
BP::BP(vector<int>const& layer_num, vector<vector<double>>const & input,
vector<vector<double>> 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 < layerNum.size(); i++)
{
a[i].resize(layerNum[i]);//每层网络节点有这么多个节点
for (int j = 0; j < layerNum[i]; j++)
a[i][j].resize(input[0].size());
}
a[0] = input;
studyNum = studynum;
}
BP::BP()
{
评论0