##################################### # Hopfieldネットワーク(連想記憶) # Coded by Y.Suganuma ##################################### a = [[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]] w = Array.new(36) for i1 in 0 ... 36 w[i1] = Array.new(36) end n = 36 p = 3 # 重みの設定(学習) for i1 in 0 ... n-1 for i2 in i1+1 ... n w[i1][i2] = 0 for i3 in 0 ... p w[i1][i2] += (2 * a[i3][i1] - 1) * (2 * a[i3][i2] - 1) end w[i2][i1] = w[i1][i2] end end for i1 in 0 ... n w[i1][i1] = 0 end # 初期状態 srand(); u = Array.new(36) print("パターン番号と修正ユニット数 ") s = gets().split(" ") pn = Integer(s[0]); m = Integer(s[1]) for i1 in 0 ... n u[i1] = a[pn][i1] end for i1 in 0 ... m k = Integer(rand(0) * n) if k >= n k = n - 1 end if u[k] > 0 u[k] = 0 else u[k] = 1 end end print("初期状態:\n") k = 0 for i1 in 0 ... 6 for i2 in 0 ... 6 print(" " + String(u[k])) k += 1 end print("\n") end # 更新 count1 = 0 count2 = 0 count3 = 0 while count1 < 100 count2 += 1 sw = 0 k = Integer(rand(0) * n) if k >= n k = n - 1 end s = 0 for i1 in 0 ... n s += (w[k][i1] * u[i1]) end if s >= 0 if u[k] == 0 sw = 1 u[k] = 1 end else if u[k] > 0 sw = 1 u[k] = 0 end end if sw > 0 count1 = 0 count3 += 1 else count1 += 1 end end # 結果 print("試行回数 = " + String(count2) + ",更新回数 = " + String(count3) + "\n") k = 0 for i1 in 0 ... 6 for i2 in 0 ... 6 print(" " + String(u[k])) k += 1 end print("\n") end