Spaces:
Sleeping
Sleeping
| import numpy as np | |
| import matplotlib.pyplot as plt | |
| import gradio as gr | |
| import pandas as pd | |
| def flatten(img : np.array) -> list[int] : | |
| new : list[int] = [] | |
| for row in img: | |
| for item in row: | |
| new.append(int(item)) | |
| return new | |
| class Hopfield: | |
| def __init__(self,patts): | |
| self.E : list[int] = [] | |
| self.patts = patts | |
| self.size = (4,4) | |
| self.Px :int = len(patts) | |
| self.Py :int = len(patts[0]) | |
| self.W : np.array = np.zeros((self.Py,self.Py),dtype=np.float16) | |
| def train(self): | |
| for i in range(self.Py): | |
| for j in range(self.Py): | |
| if i == j: | |
| self.W[i][j] = 0 | |
| continue | |
| self.W[i][j] = (1 / self.Px) * sum([patt[i] * patt[j] for patt in self.patts]) | |
| def Energy(self): | |
| return self.E | |
| def update(self,pattern): | |
| pattern_flat = flatten(pattern) | |
| H : list[int] = [] | |
| for i in self.W: | |
| H.append((sum([w * s for w,s in zip(i, pattern_flat)]))) | |
| H = np.array(H) | |
| H = np.sign(H) | |
| E = 0 | |
| for i in range(self.Py): | |
| for j in range(self.Py): | |
| E += float(-0.5 * self.W[i][j] * H[i] * H[j]) | |
| self.E.append(E) | |