File size: 1,398 Bytes
f44a265
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
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)