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

Assignment4 SourceCode 1

Source of code and

Uploaded by

Omkar Kamble
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)
8 views3 pages

Assignment4 SourceCode 1

Source of code and

Uploaded by

Omkar Kamble
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

8/17/23, 11:23 PM Untitled25 - Jupyter Notebook

In [1]: import numpy as np


import matplotlib.pyplot as plt

In [2]: def gradient_descent(starting_x, learning_rate, num_iterations):


x = starting_x
x_history = [x] # Store the history of x values
y_history = [(x + 3)**2] # Store the history of y values

for i in range(num_iterations):
gradient = 2 * (x + 3)
x = x - learning_rate * gradient
x_history.append(x)
y_history.append((x + 3)**2)

return x_history, y_history

In [3]: starting_x = 2
learning_rate = 0.1
num_iterations = 10

x_history, y_history = gradient_descent(starting_x, learning_rate, num_iteratio

localhost:8888/notebooks/Untitled25.ipynb?kernel_name=python3 1/3
8/17/23, 11:23 PM Untitled25 - Jupyter Notebook

In [4]: # Plot the function y = (x + 3)^2


x_vals = np.linspace(-10, 5, 400)
y_vals = (x_vals + 3)**2
plt.plot(x_vals, y_vals, label='y = (x + 3)^2')

Out[4]: [<matplotlib.lines.Line2D at 0x14046916990>]

localhost:8888/notebooks/Untitled25.ipynb?kernel_name=python3 2/3
8/17/23, 11:23 PM Untitled25 - Jupyter Notebook

In [5]: # Plot the gradient descent steps


plt.scatter(x_history, y_history, color='red', marker='x', label='Gradient Desc

plt.xlabel('x')
plt.ylabel('y')
plt.title('Gradient Descent for y = (x + 3)^2')
plt.legend()
plt.grid(True)
plt.show()

In [ ]: ​

localhost:8888/notebooks/Untitled25.ipynb?kernel_name=python3 3/3

You might also like