-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathHopfield.py
267 lines (229 loc) · 5.77 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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
###########################################
# Hopfield network
# Copyright (c) 2018 christianb93
# Permission is hereby granted, free of charge, to
# any person obtaining a copy of this software and
# associated documentation files (the "Software"),
# to deal in the Software without restriction,
# including without limitation the rights to use,
# copy, modify, merge, publish, distribute,
# sublicense, and/or sell copies of the Software,
# and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice
# shall be included in all copies or substantial
# portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY
# OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT
# LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
# IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
# BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
# WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
# ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE
# OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#
###########################################
import numpy as np
import matplotlib.pyplot as plt
import tempfile
import argparse
############################################
#
# Some patterns that we use for testing
#
############################################
strings = []
strings.append("""
..X..
.X.X.
X...X
.X.X.
..X..""")
strings.append("""
..X..
..X..
..X..
..X..
..X..""")
strings.append("""
.....
.....
XXXXX
.....
.....""")
strings.append("""
X....
.X...
..X..
...X.
....X""")
strings.append("""
....X
...X.
..X..
.X...
X....""")
############################################
#
# Some utility functions
#
############################################
#
# Convert a string as above into a
# 5 x 5 matrix
#
def string_to_matrix(s):
x = np.zeros(shape=(5,5), dtype=float)
for i in range(len(s)):
row, col = i // 5, i % 5
x[row][col] = -1 if s[i] == 'X' else 1
return x
#
# and back
#
def matrix_to_string(m):
s = ""
for i in range(5):
for j in range(5):
s = s + ('X' if m[i][j] < 0 else '')
s = s + chr(10)
return s
class HopfieldNetwork:
#
# Initialize a Hopfield network with N
# neurons
#
def __init__(self, N):
self.N = N
self.W = np.zeros((N,N))
self.s = np.zeros((N,1))
#
# Apply the Hebbian learning rule. The argument is a matrix S
# which contains one sample state per row
#
def train(self, S):
self.W = np.matmul(S.transpose(), S)
#
# Run one simulation step
#
def runStep(self):
i = np.random.randint(0,self.N)
a = np.matmul(self.W[i,:], self.s)
if a < 0:
self.s[i] = -1
else:
self.s[i] = 1
#
# Starting with a given state, execute the update rule
# N times and return the resulting state
#
def run(self, state, steps):
self.s = state
for i in range(steps):
self.runStep()
return self.s
############################################
#
# Parse arguments
#
#############################################
def get_args():
parser = argparse.ArgumentParser()
parser.add_argument("--memories",
type=int,
default=3,
help="Number of patterns to learn")
parser.add_argument("--epochs",
type=int,
default=6,
help="Number of epochs")
parser.add_argument("--iterations",
type=int,
default=20,
help="Number of iterations per epoch")
parser.add_argument("--errors",
type=int,
default=5,
help="Number of error that we add to each sample")
parser.add_argument("--save",
type=int,
default=0,
help="Save output")
return parser.parse_args()
############################################
#
# Main
#
#############################################
#
# Read parameters
#
args = get_args()
#
# Number of epochs. After each
# epoch, we capture one image
#
epochs = args.epochs
#
# Number of iterations
# per epoch
#
iterations = args.iterations
#
# Number of bits that we flip in each sample
#
errors = args.errors
#
# Number of patterns that we try to memorize
#
memories = args.memories
#
# Init network
#
HN = HopfieldNetwork(5*5)
#
# Prepare sample data and train network
#
M = []
for _ in range(memories):
M.append(string_to_matrix(strings[_].replace(chr(10), '')).reshape(1,5*5))
S = np.concatenate(M)
HN.train(S)
#
# Run the network and display results
#
fig = plt.figure()
for pic in range(memories):
state = (S[pic,:].reshape(25,1)).copy()
#
# Display original pattern
#
ax = fig.add_subplot(memories,epochs + 1, 1+pic*(epochs+1))
ax.set_xticks([],[])
ax.set_yticks([],[])
ax.imshow(state.reshape(5,5), "binary_r")
#
# Flip a few bits
#
state = state.copy()
for i in range(errors):
index = np.random.randint(0,25)
state[index][0] = state[index][0]*(-1)
#
# Run network and display the current state
# at the beginning of each epoch
#
for i in range(epochs):
ax = fig.add_subplot(memories,epochs + 1, i+2+pic*(epochs+1))
ax.set_xticks([],[])
ax.set_yticks([],[])
ax.imshow(state.reshape(5,5), "binary_r")
state = HN.run(state, iterations)
if 1 == args.save:
outfile = tempfile.mktemp() + "_Hopfield.png"
print("Using outfile ", outfile)
plt.savefig(outfile)
plt.show()