Created
January 27, 2015 10:12
-
-
Save iwagaki/7899d4619bb5ec05668a to your computer and use it in GitHub Desktop.
hopfield model
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <cstdio> | |
#include <cmath> | |
#include <ctime> | |
#include <cassert> | |
#include <stdint.h> | |
#include <vector> | |
#include <boost/numeric/ublas/vector.hpp> | |
#include <boost/numeric/ublas/matrix.hpp> | |
using namespace boost::numeric; | |
static const int M = 2; | |
static const int N = 8; | |
int main() | |
{ | |
// patterns | |
ublas::vector<int> P[M]; | |
ublas::vector<int> p(N); | |
p(0) = +1; | |
p(1) = +1; | |
p(2) = +1; | |
p(3) = +1; | |
p(4) = -1; | |
p(5) = -1; | |
p(6) = -1; | |
p(7) = -1; | |
P[0] = p; | |
p(0) = +1; | |
p(1) = +1; | |
p(2) = -1; | |
p(3) = -1; | |
p(4) = +1; | |
p(5) = +1; | |
p(6) = -1; | |
p(7) = -1; | |
P[1] = p; | |
// learning phase | |
ublas::matrix<int> W(N, N); | |
for(int i = 0; i < N; ++i) | |
{ | |
for(int j = 0; j < N; ++j) | |
{ | |
int sum = 0; | |
if (i != j) | |
{ | |
for(int s = 0; s < M; ++s) | |
{ | |
sum += P[s](i) * P[s](j); | |
} | |
} | |
W(i, j) = sum; | |
} | |
} | |
// initial pattern | |
ublas::vector<int> u(N); | |
u(0) = +1; | |
u(1) = +1; | |
u(2) = -1; | |
u(3) = -1; | |
u(4) = +1; | |
u(5) = -1; | |
u(6) = +1; | |
u(7) = +1; | |
// recovering | |
bool isUnstable; | |
do | |
{ | |
isUnstable = false; | |
ublas::vector<int> v = u; | |
for(int i = 0; i < N; ++i) | |
{ | |
printf("u[%d] = %d\n", i, u(i)); | |
} | |
int E = 0; | |
for(int i = 0; i < N; ++i) | |
for(int j = 0; j < N; ++j) | |
E += - W(i,j) * u(i) * u(j); | |
printf("E = %d\n", E / 2); | |
printf("-------------------\n"); | |
for(int i = 0; i < N; ++i) | |
{ | |
int sum = 0; | |
for(int j = 0; j < N; ++j) | |
{ | |
sum += W(i, j) * v(j); | |
} | |
u(i) = (sum >= 0) ? +1 : -1; | |
if (u(i) != v(i)) | |
isUnstable = true; | |
} | |
} | |
while(isUnstable); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment