|
import matplotlib.pyplot as plt
|
|
import matplotlib.animation as animation
|
|
import numpy as np
|
|
import math
|
|
|
|
|
|
y_data=[]
|
|
x_data=[]
|
|
fig = plt.figure('c2')
|
|
ax = plt.axes()
|
|
line, = ax.plot([], [], lw=4)
|
|
def derivative(x):
|
|
x=3+2*x+1
|
|
return(x)
|
|
def function(x):
|
|
x=3*x+x**2+x
|
|
return(x)
|
|
error=5
|
|
starting_point=5
|
|
increment=.1
|
|
last=500
|
|
up_looper=starting_point*2
|
|
lw_loower=0-(starting_point*2)
|
|
range=up_looper-lw_loower
|
|
point=100
|
|
increment=range/point
|
|
plot_x=[]
|
|
plot_y=[]
|
|
x=0
|
|
|
|
while (x<point):
|
|
x=x+1
|
|
plot_x.append(lw_loower)
|
|
plot_y.append(function(lw_loower))
|
|
lw_loower=lw_loower+increment
|
|
plt.plot(plot_x,plot_y,'--')
|
|
increment=starting_point*2
|
|
y_data.append(function(starting_point))
|
|
x_data.append((starting_point))
|
|
counter=0
|
|
while(abs(error)>.05):
|
|
if((derivative(starting_point+increment))<-1*(derivative(starting_point-increment))):
|
|
starting_point=starting_point+increment
|
|
error= abs(derivative(starting_point))
|
|
last=starting_point
|
|
|
|
else:
|
|
starting_point=starting_point-increment
|
|
error= last-starting_point
|
|
last=starting_point
|
|
y_data.append(function(starting_point))
|
|
x_data.append((starting_point))
|
|
if starting_point==0:
|
|
break
|
|
counter=counter+1
|
|
increment=increment*(.75)
|
|
print(starting_point)
|
|
print(len(x_data))
|
|
|
|
def init():
|
|
|
|
line.set_data([], [])
|
|
return line,
|
|
|
|
|
|
xdata, ydata = [], []
|
|
|
|
|
|
def animate(i):
|
|
|
|
|
|
x = x_data[i]
|
|
y = y_data[i]
|
|
|
|
|
|
xdata.append(x)
|
|
ydata.append(y)
|
|
|
|
|
|
line.set_data(xdata, ydata)
|
|
|
|
|
|
return line,
|
|
|
|
|
|
plt.title('Gradient Descent!')
|
|
|
|
|
|
anim = animation.FuncAnimation(fig, animate, init_func=init, frames=int(len(y_data)), interval=1, blit=True)
|
|
|
|
|
|
writergif=animation.PillowWriter(fps=30)
|
|
anim.save('Visual.gif', writer =animation.PillowWriter(fps=10) )
|
|
|
|
|
|
plt.show()
|
|
|