To obtain the patterns that a Hopfield Network has been trained with, we need to perform some reverse-engineering from the provided weights. The Hopfield Network is an associative memory model, and if we have the weights matrix, we can deduce the patterns stored.
Each weight ( W_{ij} ) is typically the sum of products of the patterns that were used to train the network. Mathematically:
[ W_{ij} = \frac{1}{N} \sum_{\mu} x_i^{(\mu)} x_j^{(\mu)} ]
where ( x_i^{(\mu)} ) is the value of the ( i^{th} ) neuron in the ( \mu^{th} ) pattern, and ( N ) is the number of neurons.
To recover the patterns:
- We need to find a way to perform the outer-product operation on potential patterns and compare it with the weights matrix.
- Use a stochastic approach to guess and check potential patterns or leverage spectral decomposition of the weight matrix.
Here's a Python code to attempt the pattern recovery. This code performs principal component analysis on the weight matrix to deduce the patterns:
import matplotlib.pyplot as plt
import numpy as np
weights = np.load("weights.npy")
def pca(weights, num_patterns):
eigvals, eigvecs = np.linalg.eigh(weights)
ix = np.argsort(-eigvals) # Sort eigenvalues in descending order
eigvecs = eigvecs[:, ix] # Reorder eigenvectors accordingly
patterns = eigvecs[:, :num_patterns] # Select the first num_patterns eigenvectors
return patterns
def encode_pattern(key, arr):
assert arr.shape == (80, 80)
X = arr.copy().flatten()
boolean = format(key, '06b')
for c_ix, c in enumerate(boolean):
if c == '1':
X[c_ix] = 1
else:
X[c_ix] = -1
return X
# Number of neurons
N = weights.shape[0]
# Assume the number of patterns stored is 16 (can change if needed)
num_patterns = 16
# Get the patterns using PCA
patterns = pca(weights, num_patterns)
# Reshape patterns for visualization
flag = np.zeros((16, 80, 80))
for i, pattern in enumerate(patterns.T):
# Hopfield uses bipolar representation. Convert to binary representation (-1 to 1).
flag[i] = pattern.reshape(80, 80)
# Plot the recovered patterns
fig, axs = plt.subplots(3, 7, figsize=(14, 6))
plt.subplots_adjust(wspace=0, hspace=0)
axs = axs.flatten()
for c, ax in zip(flag, axs):
ax.imshow(c.reshape(80, 80), cmap="gray", aspect="auto")
for ax in axs:
ax.set_xticks([])
ax.set_yticks([])
plt.show()
This code uses PCA to retrieve the patterns encoded in the weights. Note that the quality of retrieved patterns depends on the assumptions we make, and additional tweaking could be required to match the challenge's hidden specifics.