📄 chopfield.cpp
字号:
#include "CHopfield.h"
CHopfield::CHopfield() {
// Seed the random engine.
srand((unsigned)time(NULL));
// Allocate all necessary memory.
m_piOutputs = (int *)calloc(ELEMENTS, sizeof(int));
m_piThresholds = (int *)calloc(ELEMENTS, sizeof(int));
m_hiWeights = (int**)calloc(ELEMENTS, sizeof(int*));
for (int i=0; i<ELEMENTS; i++) {
m_piThresholds[i] = 0; // Set the threshold.
// Allocate additional memory for the weights.
m_hiWeights[i] = (int *)calloc(ELEMENTS, sizeof(int));
}
ImageAltered = 0;
}
CHopfield::~CHopfield() {}
bool CHopfield::ReadData(char *filename) {
ifstream data(filename);
if (!data) return false;
int temp;
for(int n=0;n<NUMDATA;n++) {
for(int y=0;y<RESY;y++) {
for (int x=0;x<RESX;x++) {
data >> temp;
m_iInputs[n][y*RESX+x] = _bipolar(temp);
}
}
}
return true;
}
void CHopfield::TrainNet() {
// Firstly, calculate the weights.
for(int i=0;i<ELEMENTS;i++) {
for (int j=0;j<ELEMENTS;j++) {
int weight=0;
if (i != j) {
for (int k=0;k<NUMDATA;k++) {
weight += m_iInputs[k][i] * m_iInputs[k][j];
}
}
m_hiWeights[i][j] = weight;
}
}
}
void CHopfield::Run(int ind) {
// Set the inputs.
for(int j=0;j<ELEMENTS;j++) m_piOutputs[j] = m_iInputs[ind][j];
AdvanceNet(); // Advance the net.
}
void CHopfield::RunNet() {
for(int i=0;i<NUMDATA;i++) {
// Set the inputs.
for(int j=0;j<ELEMENTS;j++) m_piOutputs[j] = m_iInputs[i][j];
AdvanceNet(); // Advance the net.
}
}
bool CHopfield::AdvanceNeuron(int neuron) {
int net = 0;
bool changed = false;
for (int j=0;j<ELEMENTS;j++)
net += m_hiWeights[neuron][j] * m_piOutputs[j];
int result;
if (net != m_piThresholds[neuron]) {
if (net < m_piThresholds[neuron]) result = -1;
else if (net > m_piThresholds[neuron]) result = 1;
if (result != m_piOutputs[neuron]) {
m_piOutputs[neuron] = result;
changed = true;
if (ImageAltered) {
int x = (neuron % RESY),
y = (neuron / RESY);
ImageAltered(x,y);
}
}
}
return changed;
}
void CHopfield::AdvanceNet() {
int iter = 0, last = 0;
do {
iter++;
int rndunit = rand();
rndunit %= ELEMENTS;
if (AdvanceNeuron(rndunit)) {
last = iter;
}
} while (iter - last < 10*ELEMENTS);
}
void CHopfield::SetCallback(_callback cb) {
ImageAltered = cb;
}
void CHopfield::GetOutput(bool *result, int num) {
for (int i=0;i<RESY;i++) {
for (int j=0;j<RESX;j++) {
result[num*ELEMENTS+(i*RESY+j)] = _binary(m_piOutputs[i*RESY+j]);
}
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -