0% found this document useful (0 votes)
24 views2 pages

Ml-Exp-4 - Jupyter Notebook

Uploaded by

engageelite1407
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)
24 views2 pages

Ml-Exp-4 - Jupyter Notebook

Uploaded by

engageelite1407
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/ 2

10/20/24, 11:18 PM ml-exp-4 - Jupyter Notebook

In [1]:  import numpy as np


import matplotlib.pyplot as plt

# Step 1: Define the function
def f(x):
return (x + 3)**2

# Step 2: Define the derivative of the function
def df(x):
return 2 * (x + 3)

# Step 3: Implement Gradient Descent
def gradient_descent(starting_point, learning_rate, num_iterations):
x = starting_point
x_values = [x] # To store the path of x values

for _ in range(num_iterations):
x = x - learning_rate * df(x) # Update the value of x
x_values.append(x)

return x, x_values # Return the final x value and the path

# Parameters for Gradient Descent
starting_point = 2.0 # Initial x value
learning_rate = 0.1 # Learning rate
num_iterations = 20 # Number of iterations

# Run Gradient Descent
final_x, x_values = gradient_descent(starting_point, learning_rate, num

# Step 4: Plotting the function and the path taken by Gradient Descent
x = np.linspace(-10, 4, 100) # Create an array of x values for plottin
y = f(x) # Calculate y values for the function

plt.figure(figsize=(10, 6))
plt.plot(x, y, label='y = (x + 3)²', color='blue')
plt.scatter(x_values, f(np.array(x_values)), color='red', label='Gradie
plt.title('Gradient Descent to Find Local Minima')
plt.xlabel('x')
plt.ylabel('y')
plt.legend()
plt.grid()
plt.show()

print(f"Final x value after Gradient Descent: {final_x}")
print(f"Minimum y value: {f(final_x)}")

localhost:8888/notebooks/Downloads/ml-exp-4.ipynb 2/3
10/20/24, 11:18 PM ml-exp-4 - Jupyter Notebook

Final x value after Gradient Descent: -2.9423539247696575


Minimum y value: 0.0033230699894623056

localhost:8888/notebooks/Downloads/ml-exp-4.ipynb 3/3

You might also like