Skip to content

Instantly share code, notes, and snippets.

@macrat
Last active October 9, 2015 07:38
Show Gist options
  • Select an option

  • Save macrat/b0b4fa2ada5c41651bc0 to your computer and use it in GitHub Desktop.

Select an option

Save macrat/b0b4fa2ada5c41651bc0 to your computer and use it in GitHub Desktop.
ホップフィールドネットワークとやらを試してみた。hogeがhmgeになった。かなしい。
import numpy
def str2matrix(string):
return numpy.matrix(tuple(int(x)*2-1 for x in ''.join('{0:08b}'.format(ord(x)) for x in string))).T
def matrix2box(matrix):
return matrix * matrix.T - numpy.identity(matrix.shape[0])
def make_neural(*strings):
result = matrix2box(str2matrix(strings[0]))
for x in strings[1:]:
result += matrix2box(str2matrix(x))
return result
def remember(neural, key_matrix):
return numpy.matrix(tuple(int(x>=0)*2-1 for x in neural * key_matrix)).T
def matrix2str(matrix):
ls = tuple(int(int(x)>=0) for x in matrix)
result = []
for i in range(0, len(ls), 8):
result.append(chr(int(''.join(str(x) for x in ls[i:i+8]), 2)))
return ''.join(result)
if __name__ == '__main__':
neural_network = make_neural('hoge', 'huga', 'piyo')
print'poyo -> ', matrix2str(remember(neural_network, str2matrix('poyo'))) # piyo
print'hoge -> ', matrix2str(remember(neural_network, str2matrix('hoge'))) # hmge
import numpy
class BaseBrain:
def __init__(self, size):
self.neural = numpy.zeros((size, size), numpy.int8)
self.count = 0
def data2matrix(self, data):
assert isinstance(data, bytes)
return (numpy.matrix(numpy.unpackbits(numpy.array(tuple(data), numpy.uint8)), dtype=numpy.int8) * 2 - 1).T
def learn(self, data):
matrix = self.data2matrix(data)
self.neural += matrix * matrix.T
self.count += 1
def remember(self, key):
matrix = self.data2matrix(key)
result = (self.neural - numpy.identity(self.neural.shape[0])*self.count) * matrix
return numpy.packbits(result >= 0).tobytes()
if __name__ == '__main__':
brain = BaseBrain(4 * 8)
brain.learn(b'hoge')
brain.learn(b'piyo')
print(brain.remember(b'poyo'))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment