0% found this document useful (0 votes)
23 views3 pages

Gradient ml3 - Jupyter Notebook

gradient ml3 - Jupyter Notebook

Uploaded by

Arbaz Shaikh
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
23 views3 pages

Gradient ml3 - Jupyter Notebook

gradient ml3 - Jupyter Notebook

Uploaded by

Arbaz Shaikh
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 3

9/17/24, 8:44 PM gradient ml3 - Jupyter Notebook

In [1]:  import numpy as np


import pandas as pd
import sympy as sym
import matplotlib as pyplot
from matplotlib import pyplot

In [2]:  def objective(x):


return (x+3)**2

In [3]:  def derivative(x):


return 2*(x+3)

In [4]:  def gradient(alpha,start,max_iter):


x_list=list()
x=start
x_list.append(x)
for i in range(max_iter):
gradi=derivative(x)
x=x-(alpha*gradi)
x_list.append(x)
return x_list
x=sym.symbols('x')
expr=(x+3)**2.0
grad=sym.Derivative(expr,x)
print("{}".format(grad.doit()))
grad.doit().subs(x,2)

2.0*(x + 3)**1.0

Out[4]: 10.0

In [5]:  alpha=0.1
start=2
max_iter=30
x=sym.symbols('x')
expr=(x+3)**2

localhost:8888/notebooks/gradient ml3.ipynb 1/3


9/17/24, 8:44 PM gradient ml3 - Jupyter Notebook

In [6]:  x_cor=np.linspace(-15,15,100)
pyplot.plot(x_cor,objective(x_cor))
pyplot.plot(2,objective(2),'ro')

Out[6]: [<matplotlib.lines.Line2D at 0x2bd9335cfd0>]

localhost:8888/notebooks/gradient ml3.ipynb 2/3


9/17/24, 8:44 PM gradient ml3 - Jupyter Notebook

In [7]:  x=gradient(alpha,start,max_iter)
x_cor=np.linspace(-5,5,100)
pyplot.plot(x_cor,objective(x_cor))

x_arr=np.array(x)
pyplot.plot(x_arr,objective(x_arr),'.-',color='red')
pyplot.show()

localhost:8888/notebooks/gradient ml3.ipynb 3/3

You might also like