📄 bp.cpp
字号:
// bp.cpp: implementation of the bp class.
//
//////////////////////////////////////////////////////////////////////
#include "stdafx.h"
#include "Bp_net.h"
#include "bp.h"
#include <stdio.h>
#include<time.h>
#include <stdlib.h>
#include <math.h>
#ifdef _DEBUG
#undef THIS_FILE
static char THIS_FILE[]=__FILE__;
#define new DEBUG_NEW
#endif
#define BIGRND 32767
//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////
bp::bp()
{
}
bp::~bp()
{
}
double bp::dpn1()
{
return ((double)rand()/(double)BIGRND);
}
double bp::drnd()
{
return ((drnd()*2.0)-1.0);
}
double bp::sigmo(double x)
{
return (1.0/(1.0+exp(-x)));
}
/*** 申请1维双精度实数数组 ***/
double *bp::alloc_1d_dbl(int n)
{
double *new1;
new1 = (double *) malloc ((unsigned) (n * sizeof (double)));
if (new1 == NULL) {
printf("ALLOC_1D_DBL: Couldn't allocate array of doubles\n");
return (NULL);
}
return (new1);
}
/*** 申请2维双精度实数数组 ***/
double **bp::alloc_2d_dbl(int m, int n)
{
int i;
double **new1;
new1 = (double **) malloc ((unsigned) (m * sizeof (double *)));
if (new1 == NULL) {
// printf("ALLOC_2D_DBL: Couldn't allocate array of dbl ptrs\n");
return (NULL);
}
for (i = 0; i < m; i++) {
new1[i] = alloc_1d_dbl(n);
}
return (new1);
}
/*** 设置随机数种子 ***/
void bp::bpnn_initialize(int seed)
{
srand(seed);
}
/*** 随机初始化权值 ***/
void bp::bpnn_randomize_weights(double **w, int m, int n)
{
int i, j;
for (i = 0; i <= m; i++) {
for (j = 0; j <= n; j++) {
w[i][j] = dpn1();
}
}
}
/*** 0初始化权值 ***/
void bp::bpnn_zero_weights(double **w, int m, int n)
{
int i, j;
for (i = 0; i <= m; i++) {
for (j = 0; j <= n; j++) {
w[i][j] = 0.0;
}
}
}
/*********前向传输*********/
void bp::bpnn_layerforward(double *l1, double *l2, double **conn, int n1, int n2)
{
double sum;
int j, k;
/*** 设置阈值 ***/
l1[0] = 1.0;
/*** 对于第二层的每个神经元 ***/
for (j = 1; j <= n2; j++)
{
/*** 计算输入的加权总和 ***/
sum = 0.0;
for (k = 0; k <= n1; k++)
{
sum += conn[k][j] * l1[k];
}
l2[j] = sigmo(sum);
}
}
/**输出层误差**/
void bp::bpnn_output_error(double *delta,double *target,double *output,int nj)
{
int j;
double y,t;
for (j=1;j<=nj;j++)
{
y=output[j];
t=target[j];
delta[j]=y*(1.0-y)*(t-y);
}
}
/**隐含层误差**/
void bp::bpnn_hidden_error(double *delta_h,int nh,double *delta_o,int no,double **who,double *hid)
{
int i,j;
double hi,sum;
for (i=1;i<=nh;i++)
{
hi=hid[i];
sum=0.0;
for (j=1;j<=no;j++)
{
sum+=delta_o[j]*who[i][j];
}
delta_h[i] = hi * (1.0 - hi) * sum;
}
}
/* 调整权值 */
void bp::bpnn_adjust_weights(double *delta, int ndelta, double *ly, int nly, double** w, double **oldw, double eta, double momentum)
{
double new_dw;
int k, j;
ly[0] = 1.0;
for (j = 1; j <= ndelta; j++) {
for (k = 0; k <= nly; k++) {
new_dw = ((eta * delta[j] * ly[k]) + (momentum * oldw[k][j]));
w[k][j] += new_dw;
oldw[k][j] = new_dw;
}
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -