from random import choice p_init = [-1,1,-1,1,-1,1,-1,1,-1] # pattern to learn x = int(input("How many times do you want to train the network? ")) # initializes the weights' matrix with values set to 0 weights = list() for n in range(len(p_init)): tmp = [] for u in range(len(p_init)): tmp.append(0) weights.append(tmp) # Hebbian Theory def learn(pattern): i_index = -1 for i in pattern: i_index += 1 j_index = -1 for j in pattern: j_index += 1 if i_index != j_index: if i == j: weights[i_index][j_index] += 1 elif i != j: weights[i_index][j_index] -= 1 # Hopfield Update Rules def update(pattern): i_index = -1 for i in pattern: s = 0 # sum i_index += 1 j_index = -1 for j in pattern: j_index += 1 if j != i: s += j * weights[i_index][j_index] if s >= 0: pattern[i_index] = 1 elif s < 0: pattern[i_index] = -1 learn(p_init) p = [1,1,-1,1,1,1,1,1,-1] # user pattern to be checked with the learned pattern (can be anything with the same length as p_init) input_pattern = p.copy() print("This is the pattern to be checked:", input_pattern) for k in range(x): # trains for x time(s) if p != p_init: update(p) if p == input_pattern: print("This may be a new pattern.") else: print("I assume this pattern refers to the initial learned pattern.")