Advertisement
Guest User

Untitled

a guest
Jan 17th, 2018
94
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.21 KB | None | 0 0
  1. import numpy as np
  2. #prevent numpy expotential notation on print, default False
  3. np.set_printoptions(suppress=True)
  4. # HOPEFIELD!
  5. # HOPEFIELD!
  6. # HOPEFIELD!
  7. # HOPEFIELD!
  8.  
  9.  
  10. class Neuron:
  11.  
  12.     def __init__(self, size):
  13.         self.size = size
  14.  
  15.         self.bias = 0
  16.         self.spin = 1.0
  17.  
  18.         self.weights = np.zeros(size)
  19.  
  20.     def updateSpin(self, spins):
  21.         # print(self.weights)
  22.         for i in range(self.size):
  23.             value = self.weights[i] * spins[i] + self.bias
  24.  
  25.         oldSpin = self.spin
  26.  
  27.         self.spin = 1.0 if value >= 0.0 else -1.0
  28.         return self.spin != oldSpin
  29.  
  30.  
  31. class Network:
  32.     def __init__(self, size):
  33.         self.stableCount = 10000
  34.  
  35.         self.neurons = []
  36.         # dla obrazka 50x50 size wynosi 2500
  37.         self.size = size
  38.  
  39.         for i in range(self.size):
  40.             self.neurons.append(Neuron(self.size))
  41.  
  42.     def learn(self, examples):
  43.         example = []
  44.         result = np.zeros(self.size)
  45.  
  46.         for e in examples:
  47.             tmp = []
  48.             for i in range(len(e)):
  49.                 # tmp.append(np.multiply(e, e[i]))
  50.                 tmp.append(e[i]*np.array(e))
  51.  
  52.             result = result + np.array(tmp)
  53.  
  54.         print(result)
  55.         for i, row in enumerate(result):
  56.             self.neurons[i].weights = row
  57.  
  58.     def recognize(self, image):
  59.         correctCounter = 0
  60.  
  61.         for i in range(self.size):
  62.             self.neurons[i].spin = image[i]
  63.  
  64.         while correctCounter != self.stableCount:
  65.             randomNeuron = np.random.randint(self.size, size=1)[0]
  66.             spins = []
  67.             for neuron in self.neurons:
  68.                 spins.append(neuron.spin)
  69.  
  70.             # print(spins)
  71.             correctCounter += 1.0
  72.  
  73.             if self.neurons[randomNeuron].updateSpin(spins):
  74.                 correctCounter = 0.0
  75.  
  76.         # return map(lambda x: x.spin == 1.0, self.neurons)
  77.         result = []
  78.         for neuron in self.neurons:
  79.             if neuron.spin == 1.0:
  80.                 result.append(1)
  81.             else:
  82.                 result.append(0)
  83.         return result
  84.  
  85. #
  86. # examples = [
  87. #     [1, 2, 3, 4],
  88. #     [1, 2, 3, 4],
  89. # ]
  90. #
  91. # net = Network(4)
  92. # net.learn(examples)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement