-
Notifications
You must be signed in to change notification settings - Fork 0
/
hopfield.py
72 lines (53 loc) · 1.81 KB
/
hopfield.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
"""hopfield.py -- Hopfield Network
Authors:
Jessica Hamrick (jhamrick@berkeley.edu)
Josh Abbott (joshua.abbott@berkeley.edu)
"""
import numpy as np
class hopnet(object):
def __init__(self, input):
"""Initialize a Hopfield network
Parameters
----------
input : an hstack of the input
"""
# convert input to -1/+1
ninput = (input * 2) - 1
# save parameters
self.numNeurons,self.numPatterns = ninput.shape
# create connectivity matrix
self.T = np.zeros((self.numNeurons, self.numNeurons))
# initialize T using hopfield init rule
for i in xrange(self.numPatterns):
self.T += np.outer(ninput[:,i], ninput[:,i])
self.T /= self.numPatterns
def read(self, address, iters):
"""Simulates a Hopfield network
Parameters
----------
address : array or None
initial input for the network (numNeuronsx1) to test
iters : int
number of iterations to run
Returns
-------
data : array
the result of running `iters` iterations of the hopfield network
defined by the matrix `T`, starting with input `address`
"""
# copy the data
data = address.copy().astype('i4')
# convert to -1/+1
mul = ((address * 2) - 1).astype('i4')
# udpate random indices
idx = np.random.randint(self.numNeurons, size=iters)
# read data
data[idx] = np.dot(self.T[idx,:], mul) > 0
return data
def readM(self, addresses, iters):
M = addresses.shape[1]
data = np.empty(addresses.shape, dtype='i4')
for i in xrange(M):
address = addresses[:, i]
data[:, i] = self.read(address, iters)
return data