# -*- coding: UTF-8 -*- import numpy as np import sys from math import * from random import * ##################################### # Hopfieldネットワーク(連想記憶) # Coded by Y.Suganuma ##################################### a = np.array([[0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 1, 1]], np.int) W = np.empty((36, 36), np.int) n = 36 p = 3 # 重みの設定(学習) for i1 in range(0, n-1) : for i2 in range(i1+1, n) : W[i1][i2] = 0 for i3 in range(0, p) : W[i1][i2] += (2 * a[i3][i1] - 1) * (2 * a[i3][i2] - 1) W[i2][i1] = W[i1][i2] for i1 in range(0, n) : W[i1][i1] = 0 # 初期状態 u = np.empty(36, np.int) s = input("パターン番号と修正ユニット数 ").split() pn = int(s[0]); m = int(s[1]) for i1 in range(0, n) : u[i1] = a[pn][i1] for i1 in range(0, m) : k = int(random() * n) if k >= n : k = n - 1 if u[k] > 0 : u[k] = 0 else : u[k] = 1 print("初期状態:") k = 0 for i1 in range(0, 6) : for i2 in range(0, 6) : print(" " + str(u[k]), end="") k += 1 print() # 更新 count1 = 0 count2 = 0 count3 = 0 while count1 < 100 : count2 += 1 sw = 0 k = int(random() * n) if k >= n : k = n - 1 s = 0 for i1 in range(0, n) : s += (W[k][i1] * u[i1]) if s >= 0 : if u[k] == 0 : sw = 1 u[k] = 1 else : if u[k] > 0 : sw = 1 u[k] = 0 if sw > 0 : count1 = 0 count3 += 1 else : count1 += 1 # 結果 print("試行回数 = " + str(count2) + ",更新回数 = " + str(count3)) k = 0 for i1 in range(0, 6) : for i2 in range(0, 6) : print(" " + str(u[k]), end="") k += 1 print("")