How to create a vertical graph using lists - python

number_iterations = input('enter how many times: ')
list_2 = []
list_3 = []
list_4 = []
list_5 = []
list_6 = []
list_7 = []
list_8 = []
list_9 = []
list_10 = []
list_11 = []
list_12 = []
n = int(number_iterations)
for i in range (1, n):
x = random.randint(1,6)
y = random.randint(1,6)
sum_num = x + y
if sum_num == 2:
list_2.append(1)
elif sum_num == 3:
list_3.append(1)
elif sum_num == 4:
list_4.append(1)
elif sum_num == 5:
list_5.append(1)
elif sum_num == 6:
list_6.append(1)
elif sum_num == 7:
list_7.append(1)
elif sum_num == 8:
list_8.append(1)
elif sum_num == 9:
list_9.append(1)
elif sum_num == 10:
list_10.append(1)
elif sum_num == 11:
list_11.append(1)
elif sum_num == 12:
list_12.append(1)
two = '* ' * (len(list_2))
three = '* ' * (len(list_3))
four = '* ' * (len(list_4))
five = '* ' * (len(list_5))
six = '* ' * (len(list_6))
seven = '* ' * (len(list_7))
eight = '* ' * (len(list_8))
nine = '* ' * (len(list_9))
ten = '* ' * (len(list_10))
eleven = '* ' * (len(list_11))
twelve = '* ' * (len(list_12))
print('2 : ' + two)
print('3 : ' + three)
print('4 : ' + four)
print('5 : ' + five)
print('6 : ' + six)
print('7 : ' + seven)
print('8 : ' + eight)
print('9 : ' + nine)
print('10: ' + ten)
print('11: ' + eleven)
print('12: ' + twelve)
Basically what the code does is simulate the rolling of two dice a user defined number of times. The goal is to graph these results. An example output would look like:
enter how many times: 100
2 : * * *
3 : * * * * * *
4 : * * * * * * *
5 : * * * * * * * * * * * * * *
6 : * * * * * * * * * * * * * * * * *
7 : * * * * * * * * * *
8 : * * * * * * * * * * * * *
9 : * * * * * * * * * * * * * * *
10: * * * * * *
11: * * * * * *
12: * *
This of course is a horizontal bar graph. I was wondering if there was a way to make it so that it was a vertical one, with the bars displaying vertically? I've tried using itertools and .zip_longest but it doesn't work at all. Any help would be appreciated, thanks !

You could try to first find the maximum number of asterisks. Then, iterate row in range(max_asterisks, 0, -1).
For each row, you go over your lists, and print an asterisk if the count exceeds the row number, or print a space if not.
For example, this is what I came up with:
# counts is the number of elements in each of your lists
# print(*counts, sep='\t')
for lineno in range(max(counts), 0, -1):
# 2-12: eleven elements
for item in range(11):
# Print only if the count in this column is large enough
if counts[item] >= lineno:
print('*', end='')
# TABs just make formatting easier
print('\t', end='')
# Add newline
print()
# Add the column label
print(*range(2, 13), sep='\t')
And the result:
*
*
* *
* * *
* * * * *
* * * * * *
* * * * * *
* * * * * * *
* * * * * * * *
* * * * * * * *
* * * * * * * * *
* * * * * * * * * *
* * * * * * * * * * *
* * * * * * * * * * *
* * * * * * * * * * *
2 3 4 5 6 7 8 9 10 11 12

Related

how to speed up master.scene._render_pygame_def_update() time

im trying to make a 3d renderer but i can only get at most 20fps on idle.
i tried using #functools.lru_cache(maxsize=None) on project_and_rotate() and got it up to 40fps on idle.
is there any way i could make this any faster
im using a long math formula i found a few month ago but it seems to be to slow for the map in projected_des
from math import *
import pygame
import numpy
from functools import lru_cache
#lru_cache(maxsize=None)
def project_and_rotate(x, y, z,rotx,roty,rotz,posx,posy,posz,cx,cy,cz,scale,render_distance):
x,y,z=x-posx,y-posy,z-posz
if abs(x)>render_distance or abs(z)>render_distance:return None
px = (((x * cos(rotz) - sin(rotz) * y) * cos(roty) - z * sin(roty)) * (315 / ((((z * cos(roty) + (x * cos(rotz) - sin(rotz) * y) * sin(roty)) * cos(rotx) + (y * cos(rotz) + x * sin(rotz)) * sin(rotx)) + 5) + cz))) * scale + cx
py = (((y * cos(rotz) + x * sin(rotz)) * cos(rotx) - (z * cos(roty) + (x * cos(rotz) - sin(rotz) * y) * sin(roty)) * sin(rotx)) * (315 / ((((z * cos(roty) + (x * cos(rotz) - sin(rotz) * y) * sin(roty)) * cos(rotx) + (y * cos(rotz) + x * sin(rotz)) * sin(rotx)) + 5) + cz))) * scale + cy
return [round(px),round(py)]
class coordinate:
def __init__(self,x,y,z):
self.x=x
self.y=y
self.z=z
class verticies_structure:
def __init__(self):
self._verts=[]
def add_vert(self,x,y,z):
self._verts.append(coordinate(x,y,z))
def get_coords(self,indexes):
return self._verts[indexes[0]:indexes[1]]
class camera:
def __init__(self,w,h,render_distance,fov=45):
self.fov=360-fov
self.w=w
self.h=h
self.x=0
self.rx=0
self.cx=0
self.y=0
self.ry=0
self.cy=0
self.z=0
self.rz=0
self.cz=0
self.render_distance=render_distance
def false(f,value):
if value==f:
value=f+0.01
return value
def inf360(value):
if value>359:value=0
if value<0:value=359
return value
class mesh(object):
def __init__(self,file_obj,cam):
self.cam=cam
self.verts=verticies_structure()
self.source=file_obj
self.read_object_file()
self.verts=verticies_structure()
size=100
for x in range(size):
for z in range(size):
self.verts.add_vert(x-size//2,0,z-size//2)
self.w2s_vect=numpy.vectorize(self.w2s)
self.array_verts=numpy.array(self.verts._verts)
def w2s(self,coord):
cam=self.cam
return project_and_rotate(coord.x,coord.y,coord.z,cam.ry,cam.rx,cam.rz,cam.x,cam.y,cam.z,cam.cx,cam.cy,cam.cz,10,cam.render_distance)
def projected_des(self,cam):
#return self.w2s_vect(self.array_verts).tolist()
return map( lambda coord:project_and_rotate(coord.x,coord.y,coord.z,cam.ry,cam.rx,cam.rz,cam.x,cam.y,cam.z,cam.cx,cam.cy,cam.cz,10,cam.render_distance),self.verts.get_coords([0,-1]))
def read_object_file(self):
self.verts=verticies_structure()
import re
reComp = re.compile("(?<=^)(v |vn |vt |f )(.*)(?=$)", re.MULTILINE)
with open(self.source) as f:
data = [txt.group() for txt in reComp.finditer(f.read())]
v_arr, vn_arr, vt_arr, f_arr = [], [], [], []
for line in data:
tokens = line.split(' ')
if tokens[0] == 'v':
v_arr.append([float(c) for c in tokens[1:]])
elif tokens[0] == 'vn':
vn_arr.append([float(c) for c in tokens[1:]])
elif tokens[0] == 'vt':
vn_arr.append([float(c) for c in tokens[1:]])
elif tokens[0] == 'f':
f_arr.append([[int(i) if len(i) else 0 for i in c.split('/')] for c in tokens[1:]])
vertices, normals = [], []
for face in f_arr:
for tp in face:
self.verts.add_vert(*v_arr[tp[0]-1])
self.array_verts=numpy.array(self.verts._verts)
class draw:
class frame:
class pygame_uitl:
def grid(rowx,rowy,px,color=(255,255,255)):
display=pygame.display.get_surface()
for r in range(rowx):
r+=1
pygame.draw.line(display,color,(0,(display.get_height()/(rowx+1))*r),(display.get_width(),(display.get_height()/(rowx+1))*r),px)
for r in range(rowy):
r+=1
pygame.draw.line(display,color,((display.get_width()/(rowy+1))*r,0),((display.get_width()/(rowy+1))*r,display.get_height()),px)
class system:
class pygame_util:
def get_orientation():
inf=pygame.display.Info()
w,h=inf.current_w,inf.current_h
if w>h:
return 1
else:
return 0
class Drivers:
class Pygame:
DEFAULT="PG-default"
SDL2="PG-sdl2"
class master:
class scene:
def __init__(self,wh:list,display_driver:str,render_distance:int,fps:int):
self._model={
"class 1":[],
"class 2":[],
"class 3":[],
"class 4":[]}
self._fps=fps
self._window_wh=wh
self._driver=display_driver
self._camera=camera(*wh,render_distance)
self._mode="mesh"
self._super_ls=0
if display_driver==Drivers.Pygame.DEFAULT:
self._render_pygame_def_setup()
def add_model(self,file):
model=mesh(file,self._camera)
vertexes=len(model.verts._verts)
if vertexes>100:
self._model["class 4"].append(model)
elif vertexes>50:
self._model["class 3"].append(model)
elif vertexes>25:
self._model["class 2"].append(model)
else:
self._model["class 1"].append(model)
def regulate_camera(self):
self._camera.rx,self._camera.ry,self._camera.rz=false(0,self._camera.rx),false(0,self._camera.ry),false(0,self._camera.rz)
self._camera.cx,self._camera.cy,self._camera.cz=false(0,self._camera.cx),false(0,self._camera.cy),false(0,self._camera.cz)
def correct_camera(self,orient=1):
self._orient=orient
if orient:
self._camera.cx=self._window_wh[1]//2
self._camera.cy=self._window_wh[0]
self._camera.ry=0.4
else:
self._camera.cx=self._window_wh[0]//2
self._camera.cy=self._window_wh[1]
self._camera.ry=0.2
def auto_render_distance(self):
if self._driver==Drivers.Pygame.DEFAULT:
if self._pygame_clock.get_fps()+5>self._fps:
self._camera.render_distance+=1
else:
self._camera.render_distance-=1
def landscape_super(self):
self._super_ls=1
self._lss_hdri_file_jpg_surf=pygame.Surface([self._window_wh[0],self._window_wh[1]//2.01])
self._lss_hdri_file_jpg_surf.fill((200,220,255))
def _render_pygame_def_setup(self):
self._pygame_clock=pygame.time.Clock()
self._pygame_screen=pygame.display.set_mode((self._camera.w,self._camera.h),pygame.DOUBLEBUF|pygame.HWACCEL|pygame.HWSURFACE)
def _render_pygame_def_update(self):
self._pygame_screen.fill((0,70,0))
self.regulate_camera()
for idx,vclass in self._model.items():
for model in vclass:
for point in model.projected_des(self._camera):
if point!=None:
try:self._pygame_screen.set_at(point,(255,255,255))
except:pass
if self._super_ls:
self._pygame_screen.blit(self._lss_hdri_file_jpg_surf,(0,0))
def _render_pygame_def_finish(self):
pygame.display.flip()
self._pygame_clock.tick(self._fps)
scene=master.scene([2176,1080],Drivers.Pygame.DEFAULT,render_distance=25,fps=60)
scene.add_model("cube.obj")
scene.correct_camera(0)
scene.landscape_super()
#make the sky mapped to edge of render
pygame.font.init()
while 1:
rx,ry=pygame.mouse.get_rel()
scene._camera.rx+=rx/200
scene._render_pygame_def_update()
#scene.auto_render_distance()
scene._pygame_screen.blit(pygame.font.SysFont(None,60).render(str(scene._pygame_clock.get_fps()),None,(255,0,0)),(0,0))
scene._render_pygame_def_finish()
Something like this would reduce the number of math expressions in project_and_rotate
#lru_cache(maxsize=None)
def project_and_rotate(x, y, z,rotx,roty,rotz,posx,posy,posz,cx,cy,cz,scale,render_distance):
x,y,z=x-posx,y-posy,z-posz
if abs(x)>render_distance or abs(z)>render_distance:
return None
cos_rotz = cos(rotz)
sin_rotz = sin(rotz)
cos_roty = cos(roty)
sin_roty = sin(roty)
cos_rotx = cos(rotx)
sin_rotx = sin(rotx)
intermediate_1 = (x * cos_rotz - sin_rotz * y)
intermediate_2 = (z * cos_roty + intermediate_1 * sin_roty)
intermediate_3 = (y * cos_rotz + x * sin_rotz) * sin_rotx)
intermediate_4 = (315 / (((intermediate_2 * cos_rotx + intermediate_3 + 5) + cz))) * scale
px = ((intermediate_1 * cos_roty - z * sin_roty) * intermediate_4 + cx
py = (((y * cos_rotz + x * sin_rotz) * cos_rotx - intermediate_2 * sin_rotx) * intermediate_4 + cy
return [round(px), round(py)]
However, to fully improve your script -- it would be wise to profile the code to see where the script is taking the most time.
For a better discussion you should see https://codereview.stackexchange.com/

Printing multiple objects on the same line

I was wondering if anyone could help me create a star pattern of letters. I want to see to have either UP or DOWN on the same line. At the moment, however, the letters are printed underneath each other rather than next on the same line. Any help would be greatly appreciated thank you.
Sample the U function:
def u():
u_str = ''
for row in range (0,7):
for column in range (0,7):
if (((column == 1 or column==5) and row !=6) or ((column==2 or column ==3
or column==4) and row==6)) :
u_str += "*"
else:
u_str += " "
u_str += "\n"
return u_str
function for entering either up or down
def up_or_down():
if len(user_letters) ==4 and user_letters == "DOWN":
print(d()+o()+w()+n())
elif len(user_letters) ==2 and user_letters == "UP":
print(u()+p())
else:
pass
up_or_down()
First, I suggest that you use a dict to store letters ascii art, so you are not recomputing them multiple times:
ascii_letters = {
"D": d(),
"N": n(),
"O": o(),
"P": p(),
"U": u(),
"W": w(),
}
Then create a function that can horizontally concatenate multilines strings:
def hcat_strings(*strings):
"""`strings` must have the same number of lines"""
# in a single line
# return "\n".join((" ".join(l) for l in zip(*(s.splitlines() for s in strings))))
strings_lines = (s.splitlines() for s in strings)
lines_as_tuples = zip(*strings_lines)
lines = (" ".join(l) for l in lines_as_tuples)
return "\n".join(lines)
Which you can finally use as follows:
from operator import itemgetter
text = "UPPUPU"
letters = itemgetter(*text)(ascii_letters)
print(hcat_strings(*letters))
Result:
* * ***** ***** * * ***** * *
* * * * * * * * * * * *
* * * * * * * * * * * *
* * ***** ***** * * ***** * *
* * * * * * * * *
* * * * * * * * *
*** * * *** * ***

Issue printing out to terminal with correct format

I've written a very simple program that has multiple threads that is supposed to print out to the terminal. One thread prints out an array of 10 stars, where the other thread is supposed to run in the background waiting to detect any keyboard presses. What I cannot solve is the output in the terminal does not print out properly if the second thread is running. If the second thread is stopped then the output is what is desired.
Full code (as requested):
#ASCII Frogger
from random import randint
import time
import sys, termios, tty, os
import threading
def getch():
fd = sys.stdin.fileno()
old_settings = termios.tcgetattr(fd)
try:
tty.setraw(sys.stdin.fileno())
ch = sys.stdin.read(1)
finally:
termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)
return ch
def resetPositions():
pos = ["*", "*", "*", "*", "*", "*", "*", "*", "*", "*"]
return pos
def threadKeyPressDetection():
button_delay = 0.2
while True:
char = getch();
if (char == "p"):
#print("Stop!")
exit(0)
def threadGame():
positions = ["*", "*", "*", "*", "*", "*", "*", "*", "*", "*"]
startingPos = randint(0, 9)
frogPosition = startingPos
i = 0
ii = 0
while i < 10:
# if player press left go down in grid if space
# if player press right go up in grid if space
while ii < 10:
if i < 5:
positions[4] = (5 - i)
print positions[ii],
ii += 1
ii = 0
if i == 5:
print "\n\n\n GO "
print "\n"
positions = resetPositions()
if i > 5:
positions[frogPosition] = '!'
i += 1
time.sleep(1)
try:
t1 = threading.Thread(target=threadKeyPressDetection)
t2 = threading.Thread(target=threadGame)
t1.start()
t2.start()
t1.join()
t2.join()
except:
print("Error occured - unable to start thread")
Desired output:
* * * * 3 * * * * *
* * * * 2 * * * * *
* * * * 1 * * * * *
GO
* * * * * * * * * *
* * * * * * ! * * *
Current output:
* * * * 5 * * * * *
* * * * 4 * * * * *
* * * * 3 * * * * *
* * * * 2 * * * * *
* * * * 1 * * * * *
* * * * * * * * * *
GO
The problem occurs here:
tty.setraw(sys.stdin.fileno())
ch = sys.stdin.read(1)
The tty is set to raw mode and then told to wait to read a char. While this thread is waiting for input, the other thread continues to output. It continues to output with the tty in raw mode. You can check this is the error by changing getchr() to just
def getchr():
tty.setraw(sys.stdin.fileno())
exit(0)
This will put the tty in raw mode and then kill the thread immediately. Using this, you will still get the same, undesired output even though only 1 thread is running.
The easiest fix would be to use a method from here.
Need to change tty.setraw to tty.setcbreak

__init__() missing 1 required positional argument , but i think i put it?

I program an educational game where the user has to reproduce a piece of factory offered by the computer. When I instantiate objects in the Piece class in my Application class and use the drawPiece () method, I have this error:
Traceback (most recent call last):
File "/Users/boriselgareh/Downloads/DMV2 5/Application.py", line 32, in <module>
Application(8).mainloop()
File "/Users/boriselgareh/Downloads/DMV2 5/Application.py", line 12, in __init__
self.initPieces()
File "/Users/boriselgareh/Downloads/DMV2 5/Application.py", line 21, in initPieces
pieceModele=PieceModele(Canvas())
File "/Users/boriselgareh/Downloads/DMV2 5/Piece.py", line 82, in __init__
Piece.__init__(self)
TypeError: __init__() missing 1 required positional argument: 'can'
Here are the two classes that interest us,
The Piece and Application classes are contained in separate files :
from VueChaine import *
from Chaine import *
from tkinter import *
from Piece import *
class Application(Tk):
def __init__(self,nbCotes):
Tk.__init__(self)
self.nbCotes=nbCotes
self.initFenetre()
self.initPieces()
def initFenetre(self):
self.title("l'usine TTT")
self.chaine=Chaine((3*self.nbCotes-2)//2)
self.afficheChaine=VueChaine(self,self.nbCotes)
self.afficheChaine.grid()
def initPieces(self):
pieceModele=PieceModele(Canvas(self))
pieceUsine=PieceUsine(Canvas(self))
pieceModele.getCan().pack(self)
pieceUsine.getCan().pack(self)
pieceUsine.dessinerPieces()
pieceModele.dessinerPieces()
if __name__=="__main__":
Application(8).mainloop()
from random import *
from math import *
from tkinter import *
class Piece(object):
def __init__(self,can,x=100,y=100,r=100,nbCotes=8):
self.__nbCotes=nbCotes
self.__can=can
self.xCentre=x
self.yCentre=y
self.rayon=r
self.generer()
def dessinerPieces(self):
sommets=[]
for i in range(self.getNbCotes()):
sommets.append([self.xCentre+self.rayon * cos(2 * pi * (i+1/2) / self.getNbCotes()),
self.yCentre +self.rayon * sin(2 * pi * (i+1/2) / self.getNbCotes())])
self.getCan().create_polygon(sommets, outline='gray', fill='gray')
self.getCan().pack()
delta=self.rayon-self.rayon*cos(pi/self.getNbCotes())
angle = (2 * pi) / self.getNbCotes()
for i in range(self.getNbCotes()//2):
if self.traits[i] != 0:
x0 = self.xCentre + (self.rayon - delta) * cos(angle * i)
x1 = self.xCentre + (self.rayon - delta) * cos(angle * i + pi)
y0 = self.yCentre + (self.rayon - delta) * sin(angle * i)
y1 = self.yCentre + (self.rayon - delta) * sin(angle * i + pi)
self.getCan().create_line(x0, y0, x1, y1, width=self.traits[i]**2, fill='lightgrey')
if self.trous[i] == 2 or self.trous[i] == 3:
x0 = self.xCentre + (self.rayon - delta) / 1.25 * cos(angle * i) - 7
y0 = self.yCentre + (self.rayon - delta) / 1.25 * sin(angle * i) - 7
x1 = self.xCentre + (self.rayon - delta) / 1.25 * cos(angle * i) + 7
y1 = self.yCentre + (self.rayon - delta) / 1.25 * sin(angle * i) + 7
x2 = self.xCentre + (self.rayon - delta) / 1.25 * cos(angle * i + pi) - 7
y2 = self.yCentre + (self.rayon - delta) / 1.25 * sin(angle * i + pi) - 7
x3 = self.xCentre + (self.rayon - delta) / 1.25 * cos(angle * i + pi) + 7
y3 = self.yCentre + (self.rayon - delta) / 1.25 * sin(angle * i + pi) + 7
self.getCan().create_oval(x0, y0, x1, y1, fill='yellow')
self.getCan().create_oval(x2, y2, x3, y3, fill='yellow')
if 1 or 3 in self.traits :
x = self.xCentre
y = self.yCentre
self.getCan().create_oval(x - 7, y - 7, x + 7, y + 7, fill='yellow')
#mainloop()
def generer(self):
raise NotImplementedError('...')
def getNbCotes(self):
return self.__nbCotes
def setNbCotes(self,nbCotes):
self.__nbCotes=nbCotes
def getCan(self):
return self.__can
def __eq__(self, other):
nouveau_trous = self.trous
res=()
for i in range(len(nouveau_trous)):
if nouveau_trous[i] == 3 or nouveau_trous[i]==1:
nouveau_trous[i]=nouveau_trous[i]-1
retenue=1
res=(nouveau_trous,self.traits,retenue)
return res==other
class PieceModele(Piece):
def __init__(self,trous=[],traits=[]):
self.trous=trous
self.traits=traits
Piece.__init__(self)
def generer(self):
self.trous=[randint(0,3) for i in range(self.getNbCotes()//2)]
self.traits=[randint(0,3) for i in range(self.getNbCotes()//2)]
def __repr__(self):
return str(self.trous)+str(self.traits)+" "+str(self.getNbCotes())
class PieceUsine(Piece):
def __init__(self,trous=[],traits=[]):
self.trous=trous
self.traits=traits
Piece.__init__(self)
def generer(self):
self.trous=[ 0 for i in range(self.getNbCotes()//2)]
self.traits=[ 0 for i in range(self.getNbCotes()//2)]
def trouer(self,nb):
self.trous[0]=nb
def tracer(self,epaisseur):
self.traits[0]=epaisseur
def tourner(self,angle):
for i in range(angle):
self.trous.insert(0,self.trous.pop())
self.traits.insert(0,self.traits.pop())
def __repr__(self):
return str(self.trous) + str(self.traits) + " " + str(self.getNbCotes())
if __name__=="__main__":
p1=PieceModele()
p2=PieceUsine()
print(p1)
p1.dessinerPieces()
print(p1)
Piece class takes 1 positional argument namely can.
class Piece(object):
def __init__(self,can,x=100,y=100,r=100,nbCotes=8):
.....
PieceModel class extends piece and is trying to do a super initialize without passing value for can (see last line in this block of code)
class PieceModele(Piece):
def __init__(self,trous=[],traits=[]):
self.trous=trous
self.traits=traits
Piece.__init__(self)

Virtual Neural Network in Python

I just wrote up a simple neural network in python as I have been studying them recently. I am using backpropogation. The activation function is a sigmoid. The inputs and weights generate randomly and the ideal output is 0. I am new to python so the code is written very inefficiently, but it is readable. When I run the code, the output is always zero and I can't seem to find why. Also, I didn't use a module.
from random import uniform
input_one_input_value = 1
input_two_input_value = 0
bias_value = 1
#use global to globalize function-based variables
#use lists to store data in future
def hidden_One():
global weighted_sum_hidden_one
weighted_sum_hidden_one = (input_one_input_value * weights[0]) + (input_two_input_value * weights[1]) + (bias_value * weights[2])
hidden_one_output = activation(weighted_sum_hidden_one)
return hidden_one_output
def hidden_Two():
global weighted_sum_hidden_two
weighted_sum_hidden_two = (input_one_input_value * weights[3]) + (input_two_input_value * weights[4]) + (bias_value * weights[5])
hidden_two_output = activation(weighted_sum_hidden_two)
return hidden_two_output
def output_One():
weighted_sum = (hidden_One() * weights[6]) + (hidden_Two() * weights[7]) + (bias_value * weights[8])
return activation(weighted_sum)
def activation(x):
sigmoid_value = 1 / (1+(2.71828 ** x))
return sigmoid_value
def calculate_gradient():
E = ideal_output - actual_output
output_delta = -E * activation(weights[6] + weights[7] + weights[8])
h1_delta = activation(weighted_sum_hidden_one) * weights[6] * output_delta
h2_delta = activation(weighted_sum_hidden_two) * weights[7] * output_delta
b2_delta = activation(bias_value) * weights[8] * output_delta
i1_delta = activation(input_one_input_value) * ((weights[0] * h1_delta) + (weights[3] * h2_delta))
i2_delta = activation(input_one_input_value) * ((weights[1] * h1_delta) + (weights[4] * h2_delta))
b1_delta = activation(bias_value) * ((weights[2] * h1_delta) + (weights[5] * h2_delta))
global w1_gradient
global w2_gradient
global w3_gradient
global w4_gradient
global w5_gradient
global w6_gradient
global w7_gradient
global w8_gradient
global w9_gradient
w1_gradient = input_one_input_value * h1_delta
w2_gradient = input_two_input_value * h1_delta
w3_gradient = bias_value * h1_delta
w4_gradient = input_one_input_value * h2_delta
w5_gradient = input_two_input_value * h2_delta
w6_gradient = bias_value * h2_delta
w7_gradient = hidden_One() * output_delta
w8_gradient = hidden_Two() * output_delta
w9_gradient = bias_value * output_delta
def backpropogation():
E = .7 #learning rate
a = .3 #momentum to prevent settling for local minima
global weightchanges_previous
global weight_change
weightchanges_previous = []
weight_change = []
if len(weightchanges_previous) == 0:
weight_change.append((E * w1_gradient))
weight_change.append((E * w2_gradient))
weight_change.append((E * w3_gradient))
weight_change.append((E * w4_gradient))
weight_change.append((E * w5_gradient))
weight_change.append((E * w6_gradient))
weight_change.append((E * w7_gradient))
weight_change.append((E * w8_gradient))
weight_change.append((E * w9_gradient))
weightchanges_previous.append(weight_change[0])
weightchanges_previous.append(weight_change[1])
weightchanges_previous.append(weight_change[2])
weightchanges_previous.append(weight_change[3])
weightchanges_previous.append(weight_change[4])
weightchanges_previous.append(weight_change[5])
weightchanges_previous.append(weight_change[6])
weightchanges_previous.append(weight_change[7])
weightchanges_previous.append(weight_change[8])
elif len(weightchanges_previous) != 0:
weight_change[0] = (E * w1_gradient) + (a * weightchanges_previous[0])
weight_change[1] = (E * w2_gradient) + (a * weightchanges_previous[1])
weight_change[2] = (E * w3_gradient) + (a * weightchanges_previous[2])
weight_change[3] = (E * w4_gradient) + (a * weightchanges_previous[3])
weight_change[4] = (E * w5_gradient) + (a * weightchanges_previous[4])
weight_change[5] = (E * w6_gradient) + (a * weightchanges_previous[5])
weight_change[6] = (E * w7_gradient) + (a * weightchanges_previous[6])
weight_change[7] = (E * w8_gradient) + (a * weightchanges_previous[7])
weight_change[8] = (E * w9_gradient) + (a * weightchanges_previous[8])
while len(weightchanges_previous) > 0 : weightchanges_previous.pop()
weightchanges_previous.append((E * w1_gradient) + (a * weightchanges_previous[0]))
weightchanges_previous.append((E * w2_gradient) + (a * weightchanges_previous[1]))
weightchanges_previous.append((E * w3_gradient) + (a * weightchanges_previous[2]))
weightchanges_previous.append((E * w4_gradient) + (a * weightchanges_previous[3]))
weightchanges_previous.append((E * w5_gradient) + (a * weightchanges_previous[4]))
weightchanges_previous.append((E * w6_gradient) + (a * weightchanges_previous[5]))
weightchanges_previous.append((E * w7_gradient) + (a * weightchanges_previous[6]))
weightchanges_previous.append((E * w8_gradient) + (a * weightchanges_previous[7]))
weightchanges_previous.append((E * w9_gradient) + (a * weightchanges_previous[8]))
def edit_weights():
weights[0] += weight_change[0]
weights[1] += weight_change[1]
weights[2] += weight_change[2]
weights[3] += weight_change[3]
weights[4] += weight_change[4]
weights[5] += weight_change[5]
weights[6] += weight_change[6]
weights[7] += weight_change[7]
weights[8] += weight_change[8]
while len(weight_change) > 0 : weight_change.pop()
weights = []
x = 0
while x <=8:
weights.append(uniform(-10, 10))
x += 1
ideal_output = 0
actual_output = output_One()
print "Output %d" % output_One()
x = 0
while x <= 10:
output_One()
calculate_gradient()
backpropogation()
edit_weights()
print "Output %d" % output_One()
print "----------------------"
actual_output = output_One()
x += 1
print "FINAL WEIGHTS:"
print weights[0]
print weights[1]
print weights[2]
print weights[3]
print weights[4]
print weights[5]
print weights[6]
print weights[7]
print weights[8]
Your problem is the output line:
print "Output %d" % output_One()
You're using %d which prints integer values so it rounds float values down to the nearest integer (integer conversion). Use %f instead and you should get the floating point numbers correctly.

Categories