<__main__.Find_Adj_node object at 0x0DE643E8> , class called under def function - python

I have following code where the class and def is defined.
Here we are reading a file which has start node, end node and distance between two nodes.
Example:
1 3 100
2 4 200
..so on..
import numpy as np
import pandas as pd
# STEP 1: Get the inout options to choose between shortest path and all configuration
path_type = int(input("Choose the option1 or option2 "))
if path_type == 1:
st_nd = int(input("Enter the start node: "))
ed_nd = int(input("Enter the end node: "))
# STEP 2: Import the data file
def import_data():
global data_points_df # Data_points
global data_points_max # NN
global Dist # Dist
global data_points_arr # NData_points
# Read the data as data frame
data_points_df = pd.read_csv('./Exercises/dp.txt', delimiter="\t")
data_points_arr = np.array(data_points_df)
data_points_max = np.max(data_points_arr[:, 0:2])
print(data_points_df)
print(data_points_arr)
print(data_points_max)
def Find_Adjacent_Nodes():
global K
global data_points_max # NN
K = np.array([]) # Empty Array
for i in range(data_points_max + 1):
result = np.where(data_points_arr[:, 0:2] == i)
print(i, result)
temp = data_points_arr[result[0], (result[1] + 1) % 2]
print(temp)
dst = data_points_arr[result[0], (result[1]) % 1 + 2]
print(dst)
print(Find_Adj_node(temp, dst))
K = np.append(K, Find_Adj_node(temp, dst))
return K
class Find_Adj_node:
Adj_nod = []
Nod_dist = []
def __init__(self, M, N):
self.Adj_nod = M
self.Nod_dist = N
if path_type == 1:
import_data()
Find_Adjacent_Nodes()
'''
when I run the command I see the following message.
9 (array([5, 7], dtype=int32), array([1, 1], dtype=int32))
[7 6]
[ 200 2000]
<__main__.Find_Adj_node object at 0x0DE643E8>
I would like to check what is inside K and how it is assigned. Logically I understand the it has [7,6] and the corresponding distance value as [200 2000]. The thing is how to print it and see.
Tried with k.* some options, but could not figure out.
BR,
SemiCode

Related

k means algorithm python

Whenever k = 2, the code runs in a loop
if k > 2 it sets all, but one of the centroids location to 0,0
I've reviewed it a couple of times , and it doesn't seem like there are any errors probably some sort of logic flaw. The code starts by having a class and its methods which initiate the centroids, calculate the Euclidean distance, and reassign centroids to the average positions of the points that are in the cluster. It then runs a loop that consists of reassigning and calculating distance until a list of the assignments are equal and then plots it.
class Kmeans:
def __init__(self, K, dataset, centroids, sorting):
self.K = K
self.dataset = dataset
self.centroids = centroids
self.sorting = sorting
#sets starting position of centroids
def initializeCentroids(self):
bigX = 0
bigY = 0
self.centroids = []
for i in self.dataset:
if i[0] > bigX:
bigX = i[0]
if i[1] > bigY:
bigY = i[1]
for q in range(self.K):
self.centroids.append([random.randint(0, bigX), random.randint(0, bigY)])
plt.scatter((self.centroids[0][0], self.centroids[1][0]), (self.centroids[0][1], self.centroids[1][1]))
return self.centroids
#calculates euclidean distance
def calcDistance(self):
self.sorting = []
for w in self.dataset:
print(w)
distances = []
counter = 0
for centr in self.centroids:
distances.append(math.sqrt(abs((centr[0] - w[0] * centr[0] - w[0]) + (centr[1] - w[1] * centr[1] - w[1]))))
counter += 1
if counter > 0:
try:
if distances[0] > distances[1]:
distances.pop(0)
if distances[1] > distances[0]:
distances.pop(1)
counter -= 1
except IndexError:
pass
self.sorting.append([w, counter, distances[0]])
return self.sorting
def reassignCentroids(self):
counter3 = 1
for r in range(len(self.centroids)):
positionsX = []
positionsY = []
for t in self.sorting:
if t[1] == counter3:
positionsX.append(t[0][0])
positionsY.append(t[0][1])
population = len(positionsY)
if population == 0:
population = 1
self.centroids.append([sum(positionsX) / population, sum(positionsY) / population])
counter3 += 1
self.centroids.pop(0)
return
k = 4
dataSetSize = input("Enter the amount of tuples you want generated: ")
data_set = []
for o in range(int(dataSetSize)):
data_set.append((random.randint(0, 1000), random.randint(0, 1000)))
attempt = Kmeans(k, data_set, 0, 0)
attempt.initializeCentroids()
xvals = []
yvals = []
sortCompare = []
# plots
for p in data_set:
xvals.append(p[0])
yvals.append(p[1])
running = True
while running:
if len(sortCompare) > 1:
centroidChoice0 = []
centroidChoice1 = []
for p in sortCompare[0]:
centroidChoice0.append(p[1])
for d in sortCompare[1]:
centroidChoice1.append(d[1])
print(centroidChoice1)
print(attempt.centroids)
if centroidChoice1 == centroidChoice0:
running = False
for m in attempt.centroids:
plt.scatter((attempt.centroids[0][0], attempt.centroids[1][0]), (attempt.centroids[0][1], attempt.centroids[1][1]))
running = False
sortCompare.pop(0)
attempt.calcDistance()
sortCompare.append(attempt.sorting)
attempt.reassignCentroids()

Using if condition for successive states coming across

I want to print 'double' when x equals 'ok' two times consecutively in the while loop.
My script below:
import random
import time
a = 5
while True:
b = random.randint(0, 10)
print(b)
if a > b:
x = 'ok'
print(x)
You need to track your state.
import random
import time
a = 5
prev = False
while True:
b = random.randint(0, 10)
print(b)
if a > b:
if prev:
print('double')
x = 'ok'
prev = True
else:
x = 'ko'
prev = False
This answer is for a triple version of my question:
import random
import time
a = 5
i=0
rec=[]
while True:
b = random.randint(0, 10)
print(b)
if a > b:
x = 'ok'
# print(x)
rec.append(str(x))
i=i+1
else:
x='ko'
# print(x)
rec.append(str(x))
i=i+1
if i>=3 and (rec[i-1]=='ok' and rec[i-2]=='ok' and rec[i-3]=='ok'):
print('trible')
time.sleep(1)

Value error - Balancing game input before training Neural Network

After collecting game input in the form of key combinations of w a s d and the corresponding screen image, when I try to balance the data there's a few issues. The original code had just 3 inputs of just w, a or d. I scaled this up to 9 possibilities like aw, sd or nokeys for example. Part of balancing the data is having all input vectors of the same length. But this is is where it seems to go wrong. The original code is commented out.
The balancing code:
# balance_data.py
import numpy as np
import pandas as pd
from collections import Counter
from random import shuffle
import sys
train_data = np.load('training_data-1.npy')
df = pd.DataFrame(train_data)
print(df.head())
print(Counter(df[1].apply(str)))
##lefts = []
##rights = []
##forwards = []
##
##shuffle(train_data)
##
##for data in train_data:
## img = data[0]
## choice = data[1]
##
## if choice == [1,0,0]:
## lefts.append([img,choice])
## elif choice == [0,1,0]:
## forwards.append([img,choice])
## elif choice == [0,0,1]:
## rights.append([img,choice])
## else:
## print('no matches')
##
##
##forwards = forwards[:len(lefts)][:len(rights)]
##lefts = lefts[:len(forwards)]
##rights = rights[:len(forwards)]
##
##final_data = forwards + lefts + rights
##shuffle(final_data)
w = []
a = []
d = []
s = []
wa = []
wd = []
sd = []
sa = []
nk = []
shuffle(train_data)
for data in train_data:
img = data[0]
choice = data[1]
print(choice)
if choice == [0,1,0,0]:
w.append([img,choice])
elif choice == [1,0,0,0]:
a.append([img,choice])
elif choice == [0,0,1,0]:
d.append([img,choice])
elif choice == [0,0,0,1]:
s.append([img,choice])
elif choice == [1,1,0,0]:
wa.append([img,choice])
elif choice == [0,1,1,0]:
wd.append([img,choice])
elif choice == [0,0,1,1]:
sd.append([img,choice])
elif choice == [1,0,0,1]:
sa.append([img,choice])
elif choice == [0,0,0,0]:
nk.append([img,choice])
else:
print('no matches')
min_length = 10000
print (len(w))
print (len(a))
print (len(d))
print (len(s))
print (len(wa))
print (len(wd))
print (len(sd))
print (len(sa))
print (len(nk))
if len(w) < min_length:
min_length = len(w)
if len(a) < min_length:
min_length = len(a)
if len(d) < min_length:
min_length = len(d)
if len(s) < min_length:
min_length = len(s)
if len(wa) < min_length:
min_length = len(wa)
if len(wd) < min_length:
min_length = len(wd)
if len(sd) < min_length:
min_length = len(sd)
if len(sa) < min_length:
min_length = len(sa)
w = w[min_length]
a = a[min_length]
d = d[min_length]
s = s[min_length]
wa = wa[min_length]
wd = wd[min_length]
sd = sd[min_length]
sa = sa[min_length]
nk = nk[min_length]
final_data = w + a + d + s + wa + wd + sd + sa + nk
shuffle(final_data)
np.save('training_data-1-balanced.npy', final_data)
And the vector lengths and error after it.
9715
920
510
554
887
1069
132
128
6085
Traceback (most recent call last):
File "C:\Users\StefBrands\Documents\GitHub\pygta5 - Copy\balance_data.py", line 115, in <module>
sa = sa[min_length]
IndexError: list index out of range
So now mainly two things:
1. Did I make a mistake somewhere, probably yes :)
2. Is there a better way of balancing?
You're not considering the difference between the length of a list and its maximum index - for example, the list [0, 5, 1] has length 3, but maximum index 2. As such, you should reduce the calculation of min_length by 1.
We can neaten the calculations up significantly. The lines from if if len(w) < min_length... to final_data = ... can be replaced with the following:
key_lists = (w, a, d, s, wa, wd, sd, sa, nk)
min_length = min(len(x)-1 for x in key_lists)
final_data = sum(x[min_length] for x in key_lists)
We create a tuple containing each of the lists for each key. We can then use generator expressions to find our min_length and then again to sum the values. The advantage of this is that if an additional key combo is added, we can just append its list variable to key_lists.

IndexError: index 0 is out of bounds for axis 0 with size 0

I am trying to write a code to divide two polynomials given in binary form (newdata and proofin, respectively). When I run the code, however, I get:
IndexError: index 0 is out of bounds for axis 0 with size 0
This is the code:
import numpy as np
def transformation_for_numpy_of_o():
newdata = ("101001")
freshdata = list(newdata)
freshdatapoly = []
for n in freshdata:
if n == 1:
freshdatapoly.append(1.0)
if n == 0:
freshdatapoly.append(0.0)
freshdatapoly = np.array(freshdatapoly)
return freshdatapoly
def transformation_for_numpy_of_proof():
proofin = ("101001")
proofing = list(proofin)
proofpoly = []
for n in proofing:
if n == 1:
proofpoly.append(1.0)
if n == 0:
proofpoly.append(0.0)
proofpoly = np.array(proofpoly)
return proofpoly
def total():
# Based on http://docs.scipy.org/doc/numpy-1.10.1/reference/generated/numpy.polydiv.html
o_transformed = transformation_for_numpy_of_o()
proof_transformed = transformation_for_numpy_of_proof()
numer = np.array(o_transformed)
denomin = np.array(proof_transformed)
answer = np.polydiv(numer, denomin)
print (answer)
total()
I am new to numpy and don't understand this error. How can I fix this?
*EDIT: Entire Traceback, as requested:
/Users/M/anaconda/envs/Invictus/bin/python/Users/Max/PycharmProjects/1/Origin
Traceback (most recent call last):
File "/Users/M/PycharmProjects/1/Origin", line 49, in <module>
total()
File "/Users/M/PycharmProjects/1/Origin", line 46, in total
answer = np.polydiv(numer, denomin)
File "/Users/M/anaconda/envs/Invictus/lib/python3.5/site-packages/numpy/lib/polynomial.py", line 895, in polydiv
w = u[0] + v[0]
IndexError: index 0 is out of bounds for axis 0 with size 0
Process finished with exit code 1
You are comparing ints and string so your if's never evaluate to True therefore proofpoly is always empty when you np.array(proofpoly) the same applies to freshdatapoly:
Change freshdata and proofing:
freshdata = map(int,"101001")
proofing = list(map(int,"101001"))
Since you create them just make each a list of ints:
import numpy as np
def transformation_for_numpy_of_o():
freshdata = [1,0,1,0,0,1]
freshdatapoly = []
for n in freshdata:
if n == 1:
freshdatapoly.append(1.0)
if n == 0:
freshdatapoly.append(0.0)
return np.array(freshdatapoly)
def transformation_for_numpy_of_proof():
proofing = [1, 0, 1, 0, 0, 1]
proofpoly = []
for n in proofing:
if n == 1:
proofpoly.append(1.0)
if n == 0:
proofpoly.append(0.0)
return np.array(proofpoly)
Now when you run it you get a result:
In [2]: total()
(array([ 1.]), array([ 0.]))
Maybe there is more we cannot see but currently the code is equivalent to:
def transformation_for_numpy_of_o():
freshdata = [1,0,1,0,0,1]
return np.array(freshdata)
def transformation_for_numpy_of_proof():
proofing = [1, 0, 1, 0, 0, 1]
return np.array(proofing)
If there are other possible values you can still use a list comp:
def transformation_for_numpy_of_proof():
proofing = [1, 0, 4,5,1, 0, 0, 1, 4,3,5]
return np.array([i for i in proofing if i in {1,0}])

How do I get my data in my heatmap?

I've programmed Conways Game of Life in Python and now I'm trying to display the simple data that it gives me as an output in a heat map.
This is my current code:
from Tkinter import *
import matplotlib.pyplot as plt
import time
import numpy as np
import random
size_x = 100
size_y = 10
# create the matrices
cell = [[0 for row in range(0, size_y)] for col in range(0, size_x)]
live = [[0 for row in range(0, size_y)] for col in range(0, size_x)]
temp = [[0 for row in range(0, size_y)] for col in range(0, size_x)]
# process and draw the next frame
def frame():
process()
draw()
root.after(100, frame)
# load the initial data
def load(initial=0.5):
for y in range(0, size_y):
for x in range(0, size_x):
if random.random()<initial: live[x][y] = 1
temp[x][y] = 0
# Applying rules
def process():
for y in range(0, size_y):
for x in range(0, size_x):
lives = live_neighbors(x,y)
if live[x][y] == 1:
if lives < 2 or lives > 3:
temp[x][y] = 0
else:
temp[x][y] = 1
if live[x][y] == 0:
if lives == 3:
temp[x][y] = 1
else:
temp[x][y] = 0
for y in range(0, size_y):
for x in range(0, size_x):
live[x][y] = temp[x][y]
# live = temp
# Count live neighbors
def live_neighbors(a,b):
lives = 0
if live[a][(b+1)%size_y] == 1: lives += 1
if live[a][(b-1)%size_y] == 1: lives += 1
if live[(a+1)%size_x][b] == 1: lives += 1
if live[(a+1)%size_x][(b+1)%size_y] == 1: lives += 1
if live[(a+1)%size_x][(b-1)%size_y] == 1: lives += 1
if live[(a-1)%size_x][b] == 1: lives += 1
if live[(a-1)%size_x][(b+1)%size_y] == 1: lives += 1
if live[(a-1)%size_x][(b-1)%size_y] == 1: lives += 1
return lives
# Draw all cells
def draw():
nLiving = 0
nDead = 0
for y in range(size_y):
for x in range(size_x):
if live[x][y]==0:
canvas.itemconfig(cell[x][y], fill="black")
nDead+=1
if live[x][y]==1:
canvas.itemconfig(cell[x][y], fill="white")
nLiving+=1
print nLiving,nDead
# count cells
def count():
nLiving = 0
nDead = 0
for y in range(size_y):
for x in range(size_x):
if live[x][y]==0:
nDead+=1
if live[x][y]==1:
nLiving+=1
z = nLiving / 10.0
print z,
print "%"
def one_game(initial):
load(initial)
for gen in range(1, 101):
print str(gen) + ":",
count()
process()
def many_games():
numbers = range(1,51)
for initial in numbers:
print initial/100.0
one_game(initial/100.0)
many_games()
#one_game(0.5)
The code for making a normal heat map with given input would be:
fig, ax = plt.subplots(1)
x = np.array( [[11,12,13], [21,22,23], [31,32,33]] )
p = ax.pcolormesh(x)
fig.colorbar(p)
plt.show()
How do I get my data (which in this case would be, the generations, the value which initializes the one_game() function, and nLiving) into an array?
I'm not 100% sure this is what you're intending, but it produced a pretty output heat map :)
def count():
nLiving = 0
nDead = 0
for y in range(size_y):
for x in range(size_x):
if live[x][y]==0:
nDead+=1
if live[x][y]==1:
nLiving+=1
z = nLiving / 10.0
print("nLiving over ten is: ", z,)
print("%")
return nLiving
def one_game(initial):
load(initial)
gen_array = []
for gen in range(1, 101):
print("Gen: ", str(gen) + ":",)
nLiving = count()
process()
gen_array.append(nLiving)
return gen_array
def many_games():
gen_output = []
numbers = range(1,51)
for initial in numbers:
print(initial/100.0)
gen_array = one_game(initial/100.0)
gen_output.append(gen_array)
return gen_output
gen_output = many_games()
#one_game(0.5)
fig, ax = plt.subplots(1)
x = np.array( gen_output )
p = ax.pcolormesh(x)
fig.colorbar(p)
plt.show()
That is just code modified from your count function to the end of the file. Basically you just need to return the output from the functions that you're calling into the right kind of data structures, I think...

Categories