Associative memory with Hopfield networks
File: hopfield.lisp
A Hopfield network stores patterns as attractors (stable states) of a dynamical system: train it with Hebbian learning, then present a corrupted pattern and let the network settle into the nearest stored pattern.
Training on bipolar patterns
sets the weights to the outer-product sum:

Recalling iterates the sign rule
, which never increases the energy:

when neurons update one at a time, so the energy falls until the state reaches a stored pattern.
The code
1 ;; sbcl --script hopfield.lisp (Hopfield associative neural network)
2
3 (defun hopfield-train (patterns size)
4 (let ((w (make-array (list size size) :initial-element 0)))
5 (dolist (p patterns w)
6 (dotimes (i size)
7 (dotimes (j size)
8 (unless (= i j)
9 (incf (aref w i j) (* (nth i p) (nth j p)))))))))
10
11 (defun hopfield-recall (w input &optional (max-sweeps 10))
12 "Update neurons one at a time, in place, until a full sweep changes
13 nothing. Returns the final state and the number of sweeps used."
14 (let ((state (copy-seq input))
15 (n (length input)))
16 (dotimes (sweep max-sweeps (values state max-sweeps))
17 (let ((changed nil))
18 (dotimes (i n)
19 (let* ((sum (loop for j below n
20 sum (* (aref w i j) (nth j state))))
21 (new (if (>= sum 0) 1 -1)))
22 (unless (= new (nth i state))
23 (setf (nth i state) new
24 changed t))))
25 (unless changed
26 (return (values state (1+ sweep))))))))
27
28 (defun hopfield-energy (w state)
29 (- (* 0.5
30 (loop for i below (length state)
31 sum (loop for j below (length state)
32 sum (* (aref w i j)
33 (nth i state)
34 (nth j state)))))))
35
36 (defun show-pattern (pat &optional (width 4))
37 (loop for i from 0 below (length pat)
38 do (format t "~a " (if (= (nth i pat) 1) "#" "."))
39 when (zerop (mod (1+ i) width)) do (terpri)))
40
41 ;; Demo: Train on 16-bit 'X' and 'O' patterns, recall corrupted pattern
42 (let* ((pattern-x '( 1 -1 -1 1
43 -1 1 1 -1
44 -1 1 1 -1
45 1 -1 -1 1))
46 (pattern-o '( 1 1 1 1
47 1 -1 -1 1
48 1 -1 -1 1
49 1 1 1 1))
50 (w (hopfield-train (list pattern-x pattern-o) 16))
51 ;; Corrupt pattern-x by flipping 3 bits (indices 0, 5, 10)
52 (noisy (let ((cp (copy-seq pattern-x)))
53 (dolist (idx '(0 5 10) cp)
54 (setf (nth idx cp) (- (nth idx cp)))))))
55 (format t "Original Pattern 'X' (Energy: ~,1f):~%"
56 (hopfield-energy w pattern-x))
57 (show-pattern pattern-x)
58 (format t "~%Noisy Pattern with 3 bit-flips (Energy: ~,1f):~%"
59 (hopfield-energy w noisy))
60 (show-pattern noisy)
61 (multiple-value-bind (recalled sweeps) (hopfield-recall w noisy)
62 (format t "~%Recalled Associative Memory (Energy: ~,1f):~%"
63 (hopfield-energy w recalled))
64 (show-pattern recalled)
65 (format t "~%Recovered perfectly? ~a (stable after ~d sweeps)~%"
66 (equal recalled pattern-x) sweeps)))
How it works
hopfield-trainadds the outer product of each pattern into an
weight matrix and skips the diagonal, so the whole learning rule is one incf.hopfield-recallcopies the input (so it does not change the caller’s list) and sweeps over the neurons, updating each one in place, so later neurons in the same sweep see their neighbors’ new values. These asynchronous updates guarantee that the energy never rises. (Synchronous updates, where every neuron reads the previous sweep’s state, can flip between two states forever.)(if (>= sum 0) 1 -1)is the sign activation.- Recall stops when a full sweep changes nothing, meaning the state has reached a fixed point, and returns the number of sweeps as a second value.
max-sweepsis only a safety limit. hopfield-energycomputes the Lyapunov function above; the demo uses it to show recall making progress.show-patternrenders a bipolar list as a#/.grid.
Running it
1 $ sbcl --script hopfield.lisp
Actual output:
1 Original Pattern 'X' (Energy: -144.0):
2 # . . #
3 . # # .
4 . # # .
5 # . . #
6
7 Noisy Pattern with 3 bit-flips (Energy: -52.0):
8 . . . #
9 . . # .
10 . # . .
11 # . . #
12
13 Recalled Associative Memory (Energy: -144.0):
14 # . . #
15 . # # .
16 . # # .
17 # . . #
18
19 Recovered perfectly? T (stable after 2 sweeps)
The corrupted pattern starts at energy -52.0. The first sweep fixes all three flipped bits and returns the network to the stored X at energy -144.0; the second sweep changes nothing, which tells hopfield-recall to stop.
Using it
Hopfield networks make good teaching tools for attractor dynamics, Hebbian learning, and energy minimization, all in about sixty lines. Their capacity is small (roughly
random patterns before patterns interfere), but the same outer-product idea appears again in modern work on associative memory and attention. Try training on the O pattern, corrupting it, and checking that recall lands on O; then store more patterns than the capacity allows and watch the network produce spurious mixtures.