Home > Contenuti utili > PLS 2026, Hopfield Anello
PLS 2026, Hopfield Anello
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
# -----------------------------
# Parametri
# -----------------------------
N = 50
n_steps = 100
b_1 = 1.0
b_2 = 0.0
# -----------------------------
# Genera 2 pattern
# -----------------------------
pattern1 = np.array([1 if i % 2 == 0 else -1 for i in range(N)])
pattern2 = np.ones(N)
# -----------------------------
# Disegno patterns
# -----------------------------
radius = 1.0
theta = np.linspace(0, 2*np.pi, N, endpoint=False)
x = radius * np.cos(theta)
y = radius * np.sin(theta)
fig_patterns, axes = plt.subplots(1, 2, figsize=(10, 5))
# pattern 1
axes[0].scatter(
x, y,
c=pattern1,
cmap="bwr",
vmin=-1,
vmax=1,
s=200
)
axes[0].set_aspect("equal")
axes[0].axis("off")
axes[0].set_title("Pattern 1")
# pattern 2 (se attivo)
if b_2 != 0:
axes[1].scatter(
x, y,
c=pattern2,
cmap="bwr",
vmin=-1,
vmax=1,
s=200
)
axes[1].set_aspect("equal")
axes[1].axis("off")
axes[1].set_title("Pattern 2")
plt.tight_layout()
plt.show()
# -----------------------------
# Calcolo pesi sinaptici
# -----------------------------
J = np.zeros((N, N))
for i in range(N):
for j in range(N):
J[i, j] = (
b_1 * pattern1[i] * pattern1[j] / N
+ b_2 * pattern2[i] * pattern2[j] / N
)
J[j, i] = J[i, j]
if i == j:
J[i, i] = 0.0
# -----------------------------
# Stato iniziale
# -----------------------------
spins = np.random.choice([-1, 1], size=N)
# -----------------------------
# Setup grafico animazione
# -----------------------------
fig, ax = plt.subplots(figsize=(5, 5))
scat = ax.scatter(
x, y,
c=spins,
cmap="bwr",
vmin=-1,
vmax=1,
s=200
)
ax.set_aspect("equal")
ax.axis("off")
ax.set_title("Dinamica di Hopfield")
# -----------------------------
# Update function
# -----------------------------
def update(frame):
i = np.random.randint(N)
h = np.dot(J[i], spins)
if h != 0:
spins[i] = np.sign(h)
scat.set_array(spins)
return scat,
# -----------------------------
# Animazione
# -----------------------------
ani = FuncAnimation(
fig,
update,
frames=n_steps,
interval=80,
blit=True
)
plt.show()