失败的一次,BP神经网络C++编程

本文分享了一次使用人工神经网络进行数学建模的经历。通过参考CodeProject上的教程,作者设计并实现了神经网络的类结构,包括神经元和层级,并在主函数中进行了权重初始化和前向传播过程。

*疼无比,编了好久,竟然还是错了。由于数学建模要用到人工神经网络,所以特意加紧学习。在CodeProject上找到一篇好文章,虽然是VB语言,但思想还是可以借鉴的。

原文地址:http://www.codeproject.com/Articles/14342/Designing-And-Implementing-A-Neural-Network-Librar

 

这一次再次感受到恰当的数据结构的重要性。

1、以神经细胞作为一个类,没有重视层与层之间的相通关系,导致工程量巨大,反复修改,失败告终。

2、思考过后,决定以每一层作为类,用struct类型表示细胞,将细胞所带的有用值精简。

 

#pragma once

struct NEURON
{
	float m_Bias 
		, m_Delta
		, m_Output
		, m_ErrorFactor;
};

class LAYER
{
public:
	LAYER(void);
	LAYER(int nNEURON);
	~LAYER(void);

	void UpdateOutput(LAYER& preLayer, float **Weight);
	void UpdateErrorFactor(LAYER& nextLayer, float **Weight);
	void UpdateDelta(LAYER& nextLayer, float **Weight);

	int m_Num;
	NEURON *m_Neuron;
};

 

按照CodeProject的提示,编写主函数如下

#include "stdafx.h"
#include "LAYER.h"
#include <iostream>
#include <assert.h>
using namespace std;

const int nLayer1 = 2;
const int nLayer2 = 2;
const int nLayer3 = 1;

int _tmain(int argc, _TCHAR* argv[])
{
	LAYER Layer1(nLayer1), Layer2(nLayer2), Layer3(nLayer3);
	float Input[nLayer1] = {0}, Output[nLayer3] = {0};
	float **Weight1, **Weight2;

	//初始化
	cout<<"输入:\n";
	for(int i=0; i<nLayer1; ++i)cin>>Input[i];
	cout<<"输出:\n";
	for(int i=0; i<nLayer3; ++i)cin>>Output[i];

	//随机生成权值矩阵
	Weight1 = new float * [nLayer1];
	assert(Weight1);
	for(int i=0; i<nLayer1; ++i)
	{
		Weight1[i] = new float [nLayer2];
		assert(Weight1[i]);
		for(int j=0; j<nLayer2; ++j)
		{
			Weight1[i][j] = (float)rand()/rand();
			if(Weight1[i][j] > 1) Weight1[i][j] = 1/Weight1[i][j];
			Weight1[i][j] = Weight1[j][i];
		}
	}
	Weight2 = new float * [nLayer2];
	assert(Weight2);
	for(int i=0; i<nLayer2; ++i)
	{
		Weight2[i] = new float [nLayer3];
		assert(Weight2[i]);
		for(int j=0; j<nLayer3; ++j)
		{
			Weight2[i][j] = (float)rand()/rand();
			if(Weight2[i][j] > 1) Weight2[i][j] = 1/Weight2[i][j];
			Weight1[i][j] = Weight1[j][i];
		}
	}

	//设定输入层
	for(int i=0; i<nLayer1; ++i)
		Layer1.m_Neuron[i].m_Output = Input[i];
	
	//改变各层输出
	Layer2.UpdateOutput(Layer1, Weight1);
	Layer3.UpdateOutput(Layer2, Weight2);

	//设定末层ErrorFactor
	for(int i=0; i<nLayer3; ++i)
	{
		Layer3.m_Neuron[i].m_ErrorFactor = Output[i] - Layer3.m_Neuron[i].m_ErrorFactor;
		Layer3.m_Neuron[i].m_Delta = Layer3.m_Neuron[i].m_Output * (1 - Layer3.m_Neuron[i].m_Output) * Layer3.m_Neuron[i].m_ErrorFactor;
	}

	//计算各层delta
	Layer2.UpdateErrorFactor(Layer3, Weight2);
	Layer2.UpdateDelta(Layer3, Weight2);
	Layer1.UpdateErrorFactor(Layer2, Weight1);
	Layer1.UpdateDelta(Layer2, Weight1);

	for(int i=0; i<nLayer1; ++i)delete []Weight1[i];
	delete []Weight1;

	for(int i=0; i<nLayer2; ++i)delete []Weight2[i];
	delete []Weight2;

	system("pause");
	return 0;
}

又出错了,*疼无比,今天要好好歇歇......

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值