⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 simplenet.cpp

📁 用遗传算法优化神经网络权值的源程序
💻 CPP
字号:

#include <stdlib.h>
#include <time.h>

#include "simplenet.h"

CSimpleNet::CSimpleNet() {
	for (int i=0;i<3;i++) {
		for (int j=0;j<3;j++) {
			// A random number between -3 and 3.
			m_fWeights[i][j] = (float)(rand())/(32767/6) - 3;
		}
	}
}

CSimpleNet::~CSimpleNet() {}

float CSimpleNet::Run(float i1, float i2, float d) {
	// These are all the main variables used in the 
	// routine. Seems easier to group them all here.
	float net1, net2, i3, i4;
	
	// Calculate the net values for the hidden layer neurons.
	net1 = 1 * m_fWeights[0][0] + i1 * m_fWeights[1][0] +
		  i2 * m_fWeights[2][0];
	net2 = 1 * m_fWeights[0][1] + i1 * m_fWeights[1][1] +
		  i2 * m_fWeights[2][1];

	// Use the hardlimiter function - the Sigmoid.
	i3 = Sigmoid(net1);
	i4 = Sigmoid(net2);

	// Now, calculate the net for the final output layer.
	net1 = 1 * m_fWeights[0][2] + i3 * m_fWeights[1][2] +
	   	  i4 * m_fWeights[2][2];
	
	return Sigmoid(net1);
}

float CSimpleNet::Train(float i1, float i2, float d) {
	// The Train function returns the error.
	return float(fabs(Run(i1,i2,d) - d));
}

float CSimpleNet::Sigmoid(float num) {
	return (float)(1/(1+exp(-num)));
}

void CSimpleNet::AlterWeights(float amount) {
	for (int i=0;i<3;i++) {
		for (int j=0;j<3;j++) {
			m_fWeights[i][j] += (float)(rand())/(32767/(amount * 2)) - amount;
		}
	}
}

void CSimpleNet::GetWeights(float *wp) {
	for (int i=0;i<3;i++) {
		for (int j=0;j<3;j++) {
			*wp = m_fWeights[i][j];
			wp++;
		}
	}
}

void CSimpleNet::SetWeights(float *wp) {
	for (int i=0;i<3;i++) {
		for (int j=0;j<3;j++) {
			m_fWeights[i][j] = *wp;
			wp++;
		}
	}
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -