How to fix hopfield library errors in python - python

I have some code about hopfield network. I am trying to train some letters with hebbian training and then add noise and denoise them. However, I have problem with libraries. I did a search but I cant find the right answer to my problem. Hopfieldnet library is not working and if I try to replace it I take other errors. Can u help me?
from random import randint
import numpy as np
import HopfieldNetwork
from hopfieldnet.trainers import hebbian_training
from matplotlib import pyplot as plt
# Create the training patterns
j_pattern = np.array([[1, 1, 1, 1, 1],
[0, 0, 1, 0, 0],
[0, 0, 1, 0, 0],
[0, 0, 1, 0, 0],
[0, 0, 1, 0, 0],
[1, 0, 1, 0, 0],
[1, 1, 1, 0, 0]])
a_pattern = np.array([[0, 0, 1, 0, 0],
[0, 1, 0, 1, 0],
[1, 0, 0, 0, 1],
[1, 1, 1, 1, 1],
[1, 0, 0, 0, 1],
[1, 0, 0, 0, 1],
[1, 0, 0, 0, 1]])
m_pattern = np.array([[1, 0, 0, 0, 1],
[1, 1, 0, 1, 1],
[1, 0, 1, 0, 1],
[1, 0, 0, 0, 1],
[1, 0, 0, 0, 1],
[1, 0, 0, 0, 1],
[1, 0, 0, 0, 1]])
e_pattern = np.array([[1, 1, 1, 1, 1],
[1, 0, 0, 0, 0],
[1, 0, 0, 0, 0],
[1, 1, 1, 1, 1],
[1, 0, 0, 0, 0],
[1, 0, 0, 0, 0],
[1, 1, 1, 1, 1]])
s_pattern = np.array([[1, 1, 1, 1, 1],
[1, 0, 0, 0, 0],
[0, 1, 0, 0, 0],
[0, 0, 1, 0, 0],
[0, 0, 0, 1, 0],
[0, 0, 0, 0, 1],
[1, 1, 1, 1, 1]])
j_pattern *= 2
j_pattern -= 1
a_pattern *= 2
a_pattern -= 1
m_pattern *= 2
m_pattern -= 1
e_pattern *= 2
e_pattern -= 1
s_pattern *= 2
s_pattern -= 1
input_patterns = np.array([j_pattern.flatten(), a_pattern.flatten(), m_pattern.flatten(), e_pattern.flatten(), s_pattern.flatten()])
# Create the neural network and train it using the training patterns
network = HopfieldNetwork(35)
hebbian_training(network, input_patterns)
# Create the test patterns by using the training patterns and adding some noise to them
# and use the neural network to denoise them
j_test = j_pattern.flatten()
for i in range(4):
p = randint(0, 34)
j_test[p] *= -1
j_result = network.run(j_test)
j_result.shape = (7, 5)
j_test.shape = (7, 5)
a_test = a_pattern.flatten()
for i in range(4):
p = randint(0, 34)
a_test[p] *= -1
a_result = network.run(a_test)
a_result.shape = (7, 5)
a_test.shape = (7, 5)
m_test = m_pattern.flatten()
for i in range(4):
p = randint(0, 34)
m_test[p] *= -1
m_result = network.run(m_test)
m_result.shape = (7, 5)
m_test.shape = (7, 5)
e_test = e_pattern.flatten()
for i in range(4):
p = randint(0, 34)
e_test[p] *= -1
e_result = network.run(e_test)
e_result.shape = (7, 5)
e_test.shape = (7, 5)
s_test = s_pattern.flatten()
for i in range(4):
p = randint(0, 34)
s_test[p] *= -1
s_result = network.run(s_test)
s_result.shape = (7, 5)
s_test.shape = (7, 5)
# Show the results
plt.subplot(3, 2, 1)
plt.imshow(j_test, interpolation="nearest")
plt.subplot(3, 2, 2)
plt.imshow(j_result, interpolation="nearest")
plt.subplot(3, 2, 3)
plt.imshow(a_test, interpolation="nearest")
plt.subplot(3, 2, 4)
plt.imshow(a_result, interpolation="nearest")
plt.subplot(3, 2, 5)
plt.imshow(m_test, interpolation="nearest")
plt.subplot(3, 2, 6)
plt.imshow(m_result, interpolation="nearest")
plt.subplot(3, 2, 7)
plt.imshow(e_test, interpolation="nearest")
plt.subplot(3, 2, 8)
plt.imshow(e_result, interpolation="nearest")
plt.subplot(3, 2, 9)
plt.imshow(s_test, interpolation="nearest")
plt.subplot(3, 2, 10)
plt.imshow(s_result, interpolation="nearest")
plt.show()
The error:
"C:/Users/chriss/PycharmProjects/untitled3/hopfield.py", line 3, in <module> import HopfieldNetwork ModuleNotFoundError: No module named 'HopfieldNetwork'

Not sure if it is actual solution to the problem. I cannot reproduce the error. Code works for me after 3 slight modifications.
(1) Imports
from random import randint
import numpy as np
from hopfieldnet.net import HopfieldNetwork # modified import
from hopfieldnet.trainers import hebbian_training
from matplotlib import pyplot as plt
(2) Drawing
plt.subplot(3, 4, ...) # 3 * 4 = 12 places for 10 plots
(3) hopfieldnet module -> net.py -> class HopfieldNetwork -> method run
update_list = list(range(self._num_inputs)) # list(range(...)) instead of just range(...)

Related

Separating specific values from a list in python

I have a list of lists(called table):
table = [[0, 1, 2], [1, 2, 1], [2, 3, 2], [0, 2, 3], [0, 3, 2], [1, 3, 3]]
where the first element of each sub list is the start point, the second is the endpoint and the third is the distance between the two points. So e.g. [0,1,2] means the gap between the point 0 and 1 is 2.
Now I want to use the information in table, to construct another list of lists(called distances) containing all the distances between all the points. So that, I could for example, call distances[0][2] (meaning I want the distance between point 0 and point 2, so the output should be 3).
However I am having trouble correctly separating the date from table and putting it into distances.
My code so far is this:
dstFromOnePoint = []
distances = []
numberOfPoints = 4 #0,1,2,3
for i in range(numberOfPoints): #loops through all start points
for j in range(numberOfPoints): # loops through all endpoints
for val in table:
if (val[0] == i and val[1] == j) or (val[0] == j and val[1] == i): # checks start node , end node
dst = val[2]
dstFromOnePoint.append(dst)
elif (i==j): #distance from one point to itself will be 0
dstFromOnePoint.append(0)
distances.append(dstFromOnePoint)
print(distances)
print(distances[0][2])
The output I get:
[[0, 0, 0, 0, 0, 0, 2, 3, 2, 2, 0, 0, 0, 0, 0, 0, 1, 3, 3, 1, 0, 0, 0, 0, 0, 0, 2, 2, 3, 2, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 2, 3, 2, 2, 0, 0, 0, 0, 0, 0, 1, 3, 3, 1, 0, 0, 0, 0, 0, 0, 2, 2, 3, 2, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 2, 3, 2, 2, 0, 0, 0, 0, 0, 0, 1, 3, 3, 1, 0, 0, 0, 0, 0, 0, 2, 2, 3, 2, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 2, 3, 2, 2, 0, 0, 0, 0, 0, 0, 1, 3, 3, 1, 0, 0, 0, 0, 0, 0, 2, 2, 3, 2, 0, 0, 0, 0, 0, 0]]
0
The output I should get:
[[0,2,3,2], [2,0,1,3], [3,1,0,2], [2,3,2,0]]
3
I think I'm using my loops incorrectly because I end up appending the same list multiple times, but even just looking at one individual sub list, I don't have the correct values, so I probably have more issues that I don't know how to fix?
Here is a correct and more compact solution:
numberOfPoints = 4
distances = [numberOfPoints * [0] for _ in range(numberOfPoints)]
for x, y, d in table:
distances[x][y] = d
distances[y][x] = d
You need to pre-populate the distance matrix and then assign per [i][j]
Fixes on your original solutions:
table = [[0, 1, 2], [1, 2, 1], [2, 3, 2], [0, 2, 3], [0, 3, 2], [1, 3, 3]]
distances = []
numberOfPoints = 4 #0,1,2,3
distances = [[0 for _ in range(numberOfPoints)] for _ in range(numberOfPoints)]
for i in range(numberOfPoints): #loops through all start points
for j in range(numberOfPoints): # loops through all endpoints
for val in table:
if (val[0] == i and val[1] == j) or (val[0] == j and val[1] == i): # checks start node , end node
dst = val[2]
distances[i][j] = dst
# actually you can drop this elif as distances is intitalized to 0
elif (i==j): #distance from one point to itself will be 0
# dstFromOnePoint.append(0)
distances[i][j] = 0
# distances.append(dstFromOnePoint)
print(distances)
print(distances[0][2])
gives:
[[0, 2, 3, 2], [2, 0, 1, 3], [3, 1, 0, 2], [2, 3, 2, 0]]
3
here is one line using itertools.groupby:
from itertools import groupby
[[next(g)[2] if j!=i else 0 for j in range(len(table[0]) + 1 )] for i, (k, g) in enumerate(groupby(sorted(e for f, s, t in table for e in [[f, s, t], [s, f, t]]), key=lambda x: x[0]))]
output:
[[0, 2, 3, 2], [2, 0, 1, 3], [3, 1, 0, 2], [2, 3, 2, 0]]

MatPlotLib printing out graphs on the same line next to each other

So I am making a program that reads in multiple two dimensional lists and plots them as step graph functions. I want to print out each set of graphs side by side like so (I made the graphs different colors just to differentiate the two):
Desired Output
However my code right now makes these two sets overlap each other instead, like so:
Actual Output
I believe it might have something to do with my "t" variable in plotPoints but I am not sure what I need to do. Any help would be greatly appreciated.
# supress warning message
import warnings; warnings.simplefilter("ignore")
# extension libraries
import matplotlib.pyplot as plt
import numpy as np
def plotPoints(bits, color):
for i in range(len(bits)):
data = np.repeat(bits[i], 2)
t = 0.5 * np.arange(len(data))
plt.step(t, data + i * 3, linewidth=1.5, where='post', color=color)
# Labels the graphs with binary sequence
for tbit, bit in enumerate(bits[i]):
plt.text(tbit + 0.3, 0.1 + i * 3, str(bit), fontsize=6, color=color)
def main():
plt.ylim([-1, 32])
set1 = [[0, 0, 0, 1, 1, 0, 1, 1], [0, 0, 1, 0, 1, 1, 0, 0], [1, 1, 0, 0, 1, 0, 0, 0]]
set2 = [[1, 1, 1, 0, 0, 1, 0, 0], [1, 1, 0, 1, 0, 0, 1, 1], [0, 0, 1, 1, 0, 1, 1, 1]]
plotPoints(set1, 'g')
plotPoints(set2, 'b')
# removes the built in graph axes and prints line every interation
plt.gca().axis('off')
plt.ylim([-1, 10])
plt.show()
main()
You can add some offset to t.
import matplotlib.pyplot as plt
import numpy as np
def plotPoints(bits, color, offset=0):
for i in range(len(bits)):
data = np.repeat(bits[i], 2)
t = 0.5 * np.arange(len(data)) + offset
plt.step(t, data + i * 3, linewidth=1.5, where='post', color=color)
# Labels the graphs with binary sequence
for tbit, bit in enumerate(bits[i]):
plt.text(tbit + 0.3 +offset, 0.1 + i * 3, str(bit), fontsize=6, color=color)
def main():
set1 = [[0, 0, 0, 1, 1, 0, 1, 1], [0, 0, 1, 0, 1, 1, 0, 0], [1, 1, 0, 0, 1, 0, 0, 0]]
set2 = [[1, 1, 1, 0, 0, 1, 0, 0], [1, 1, 0, 1, 0, 0, 1, 1], [0, 0, 1, 1, 0, 1, 1, 1]]
plotPoints(set1, 'g')
plotPoints(set2, 'b', offset=len(set1[0]))
# removes the built in graph axes and prints line every interation
plt.gca().axis('off')
plt.ylim([-1, 10])
plt.show()
main()

simple matrix type rotation (without numpy or pandas)

This must be something that is really simple, but I could not fix it.
I want to do a matrix type transpose with native python list of list (i.e., without using numpy or pandas). Code is show following. I am having a hard time trying to figure out where it is wrong.
raw_matrix_list = [[1, 0, 1, 0, 1, 0],
[1, 0, 0, 0, 1, 0],
[0, 0, 0, 0, 0, 1],
[1, 0, 0, 0, 1, 1]]
def rotate_matrix_list(raw_matrix_list):
rows = len(raw_matrix_list)
cols = len(raw_matrix_list[0])
new_matrix_list = [[0] * rows] * cols
for ii in xrange(cols):
for jj in xrange(rows):
# print str(ii) + ', ' + str(jj) + ', ' + str(rows)
new_matrix_list[ii][jj] = raw_matrix_list[rows-jj - 1][ii]
return(new_matrix_list)
rotate_matrix_list(raw_matrix_list)
The result I get is
[[1, 1, 0, 0], [1, 1, 0, 0], [1, 1, 0, 0], [1, 1, 0, 0], [1, 1, 0, 0], [1, 1, 0, 0]]
What I want to get is:
[[1, 0, 1, 1], [0, 0, 0, 0], [0, 0, 0, 1], [0, 0, 0, 0], [1, 0, 1, 1], [1, 1, 0, 0]]
===
$ python --version
Python 2.7.12 :: Anaconda 2.3.0 (x86_64)
===
update 2
Now I got the answer of how to do it in python with zip function. But I just failed to see why my code did not work.
Well, doing a transpose with vanilla lists in Python is pretty easy: use zip and the splat operator:
>>> raw_matrix_list = [[1, 0, 1, 0, 1, 0],
... [1, 0, 0, 0, 1, 0],
... [0, 0, 0, 0, 0, 1],
... [1, 0, 0, 0, 1, 1]]
>>> transpose = list(zip(*raw_matrix_list))
>>> transpose
[(1, 1, 0, 1), (0, 0, 0, 0), (1, 0, 0, 0), (0, 0, 0, 0), (1, 1, 0, 1), (0, 0, 1, 1)]
>>> from pprint import pprint
>>> pprint(transpose)
[(1, 1, 0, 1),
(0, 0, 0, 0),
(1, 0, 0, 0),
(0, 0, 0, 0),
(1, 1, 0, 1),
(0, 0, 1, 1)]
For python 2, you only need zip(*raw_matrix_list)) rather than list(zip(*raw_matrix_list)))
If a list of tuples won't do:
>>> transpose = [list(t) for t in zip(*raw_matrix_list)]
>>> pprint(transpose)
[[1, 1, 0, 1],
[0, 0, 0, 0],
[1, 0, 0, 0],
[0, 0, 0, 0],
[1, 1, 0, 1],
[0, 0, 1, 1]]
The problem with your solution is that you use:
new_matrix_list = [[0] * rows] * cols
This makes every list the same object.
See this example for the problem:
>>> x = [[0]*3] * 4
>>> x
[[0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0]]
>>> x[0][0] = 1
>>> x
[[1, 0, 0], [1, 0, 0], [1, 0, 0], [1, 0, 0]]
Use something like:
new_matrix_list = [[0 for _ in range(rows)] for _ in range(cols)]
And you should be well on your way.
Using a nested list comprehension:
rows, cols = len(raw_matrix_list), len(raw_matrix_list[0])
>>> [[raw_matrix_list[i][j] for i in range(rows)] for j in range(cols)]
[[1, 1, 0, 1],
[0, 0, 0, 0],
[1, 0, 0, 0],
[0, 0, 0, 0],
[1, 1, 0, 1],
[0, 0, 1, 1]]
There are already answers that help solve your problem. As to why your code doesn't work, shouldn't it be this (by definition of matrix transpose):
new_matrix_list[ii][jj] = raw_matrix_list[jj][ii]

Create a matrix with every possible column

How can I make an n by 2^n matrix of 0 and 1 values where all the columns are distinct? For example, if n = 2 that would be
0011
0101 .
And I can use itertools to make all possible tuples.
list(itertools.product([0,1],repeat = 2))
But how do I make those the columns of my matrix?
Simply apply a np.matrix to your result:
>>> np.matrix(list(itertools.product([0,1],repeat = 2)))
matrix([[0, 0],
[0, 1],
[1, 0],
[1, 1]])
X = numpy.array(map(lambda x: list(x), itertools.product([0,1],repeat = 2)))
Takes your itertools result and turns every element into a list and then turns it into a numpy array. If that's not the direction that you want you can then use.
X = X.transpose()
For entertainment's sake, here's a pure-numpy way of doing it:
>>> n = 2
>>> (np.arange(2**n) // ((1 << np.arange(n)[::-1,None]))) & 1
array([[0, 0, 1, 1],
[0, 1, 0, 1]])
>>> n = 4
>>> (np.arange(2**n) // ((1 << np.arange(n)[::-1,None]))) & 1
array([[0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1],
[0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1],
[0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1],
[0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1]])
Some explanation (note that it's very unlikely I'd ever write anything like the above in production code):
First, we get the numbers we need the bits of:
>>> np.arange(2**n)
array([0, 1, 2, 3])
Then the exponents of the powers of 2 we care about:
>>> np.arange(n)
array([0, 1])
Bitshift 1 by these to get the powers of two:
>>> 1 << np.arange(n)
array([1, 2])
Swap the order for aesthetic purposes:
>>> (1 << np.arange(n))[::-1]
array([2, 1])
Use None to introduce an extra axis, so we can broadcast:
>>> (1 << np.arange(n))[::-1, None]
array([[2],
[1]])
Divide:
>>> np.arange(2**n) // (1 << np.arange(n))[::-1, None]
array([[0, 0, 1, 1],
[0, 1, 2, 3]])
Take only the first bit:
>>> (np.arange(2**n) // (1 << np.arange(n))[::-1, None]) & 1
array([[0, 0, 1, 1],
[0, 1, 0, 1]])
Just use list comprehension:
a = list(itertools.product([0,1],repeat = n))
[[p[i] for p in a] for i in xrange(n)]
Demo:
>>> n = 2
>>> a = list(itertools.product([0,1],repeat = n))
>>> M = [[p[i] for p in a] for i in xrange(0,n)]
>>> M
[[0, 0, 1, 1], [0, 1, 0, 1]]
>>> n = 4
>>> a = list(itertools.product([0,1],repeat = 4))
>>> M = [[p[i] for p in a] for i in xrange(0,4)]
>>> M
[[0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1],
[0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1],
[0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1],
[0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1]]

get all possible single bytes in python

I'm trying to generate all possible bytes to test for a machine learning algorithm (8-3-8 mural network encoder). is there a way to do this in python without having 8 loops?
Could permutations help?
I'd prefer an elegant way to do this, but I'll take what I can get at the moment.
desired output:
[0,0,0,0,0,0,0,0]
[0,0,0,0,0,0,0,1]
[0,0,0,0,0,0,1,0]
[0,0,0,0,0,0,1,1]
[0,0,0,0,0,1,0,0]
[0,0,0,0,0,1,0,1]
.
.
.
[1,1,1,1,1,1,1,1]
Yes, there is, itertools.product:
import itertools
itertools.product([0, 1], repeat=8)
>>> list(itertools.product([0, 1], repeat=8))
[(0, 0, 0, 0, 0, 0, 0, 0),
(0, 0, 0, 0, 0, 0, 0, 1),
[...]
(1, 1, 1, 1, 1, 1, 1, 0),
(1, 1, 1, 1, 1, 1, 1, 1)]
[[x>>b&1 for b in range(8)] for x in range(256)]
You could iterate over the numbers and then convert to binary:
[bin(x)[2:] for x in range(256)]
If you happen to be using numpy already...
In [48]: import numpy as np
In [49]: nbits = 4
In [50]: np.sign(np.bitwise_and(2 ** np.arange(nbits), np.arange(2 ** nbits).reshape(-1, 1)))
Out[50]:
array([[0, 0, 0, 0],
[1, 0, 0, 0],
[0, 1, 0, 0],
[1, 1, 0, 0],
[0, 0, 1, 0],
[1, 0, 1, 0],
[0, 1, 1, 0],
[1, 1, 1, 0],
[0, 0, 0, 1],
[1, 0, 0, 1],
[0, 1, 0, 1],
[1, 1, 0, 1],
[0, 0, 1, 1],
[1, 0, 1, 1],
[0, 1, 1, 1],
[1, 1, 1, 1]])

Categories