Skip to content

Instantly share code, notes, and snippets.

@wadoon
Created December 7, 2013 00:11
Show Gist options
  • Save wadoon/7835028 to your computer and use it in GitHub Desktop.
Save wadoon/7835028 to your computer and use it in GitHub Desktop.
Hopfield net small implementation
#!/usr/bin/python
import numpy as np
np.set_printoptions(precision=3, suppress = True)
def mprint(n,v):
print "%s = \n\t" %n , str(v).replace("\n", "\n\t")
print
SIZE = 7
np.random.seed(4213213)
T = np.random.randn(SIZE,SIZE)
U = np.random.randint(0,2,SIZE)
for i in range(SIZE):
for j in range(i):
T[i,j] = T[j,i]
T[i,i] = 0
print "symmtric:" , (T == T.T).all()
mprint("T", T)
mprint("U", U)
def combine_pattern(A):
m,n = A.shape
T = np.zeros((n,n))
for i in range(n):
for j in range(i):
x = 0
for p in range(m):
x += (2*A[p,i]-1)*(2*A[p,j]-1)
T[j,i] = x
T[i,j] = x
T[i,i] = 0
return T
def energy(T, U):
s = 0
for i in range(SIZE):
for j in range(SIZE):
if i!=j:
s += U[i]*U[j]*T[j,i]
return -0.5* s
def step(T, U):
Unext = U.copy()
for i in range(SIZE):
W = T[:,i]
x = sum(W * U)
u = 1 if x >= 0 else 0
Unext[i] = u
return Unext
for m in range(0):#2**SIZE):
mprint("E", energy(T,U))
Un = step(T,U)
b = (Un == U).all()
if b: break
U = Un
#mprint("b",b)
#mprint("m",m)
#mprint("U", U)
A = readImages(["1.jpg", "2.jpg", "3.jpg"], 32*32)
T = combine_pattern(A)
a1 = A[1,:].copy()
a1[:250] = 0
a1[600:] = 0
for m in range(10):
mprint("E", energy(T,a1))
a1n = step(T,a1)
b = (a1n == a1).all()
if b: break
a1 = a1n
I = a1.reshape((32,32))
cv2.imshow("abc" , I*255)
cv2.waitKey()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment