Answered step by step
Verified Expert Solution
Link Copied!

Question

1 Approved Answer

hi I got the following feedback message regarding the following code ( I checked your code . You only have a simple error on calculating

hi I got the following feedback message regarding the following code

( I checked your code . You only have a simple error on calculating objective value of Sphere function. The function should take only one solution as parameter and calculate sum of squares of vector elements )

please can you update the code according to the above feedback message give me excutable code without error messages please with explanations

=================================================================================== import numpy as np from matplotlib import pyplot as plt

class GradientDescent: def __init__(self, function, gradient, initial_solution, learning_rate=0.1, max_iter=100, tolerance=0.0000001): self.function = function self.gradient = gradient self.solution = initial_solution self.learning_rate = learning_rate self.max_iter = max_iter self.tolerance = tolerance

def run(self): t = 0 while t < self.max_iter: diff = -self.learning_rate * self.gradient(*self.solution) if np.linalg.norm(diff) < self.tolerance: break self.solution = tuple([self.solution[i] + diff[i] for i in range(len(diff))]) t += 1 return self.solution, self.function(*self.solution)

def fun1(x, y): return x ** 2 + y ** 2

def gradient1(x, y): return np.array([2 * x, 2 * y])

bounds = [-3, 3]

plt.figure()

x, y = np.meshgrid(np.linspace(bounds[0], bounds[1], 100), np.linspace(bounds[0], bounds[1], 100)) z = fun1(x, y) plt.contour(x, y, z,levels=20)

random_solution = np.random.uniform(bounds[0], bounds[1], size=2)

gd = GradientDescent(fun1, gradient1, random_solution)

best_solution, best_value = gd.run()

plt.plot(best_solution[0], best_solution[1], marker='o') plt.plot(best_solution[0], best_solution[1])

plt.show()

Step by Step Solution

There are 3 Steps involved in it

Step: 1

blur-text-image

Get Instant Access to Expert-Tailored Solutions

See step-by-step solutions with expert insights and AI powered tools for academic success

Step: 2

blur-text-image

Step: 3

blur-text-image

Ace Your Homework with AI

Get the answers you need in no time with our AI-driven, step-by-step assistance

Get Started

Recommended Textbook for

C++ Database Development

Authors: Al Stevens

1st Edition

1558283579, 978-1558283572

More Books

Students also viewed these Databases questions