Skip to content

Commit 7c589a6

Browse files
authored
added gradient descent calculator
1 parent 4e3d987 commit 7c589a6

File tree

1 file changed

+31
-0
lines changed

1 file changed

+31
-0
lines changed

gradient_descent.py

+31
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
from numpy import asarray
2+
from numpy.random import rand
3+
4+
# objective function
5+
def objective(x):
6+
return x**2.0
7+
8+
def derivative(x):
9+
return x * 2.0
10+
11+
def gradient_descent(objective, derivative, bounds, n_iter, step_size):
12+
solution = bounds[:, 0] + rand(len(bounds)) * (bounds[:, 1] - bounds[:, 0])
13+
for i in range(n_iter):
14+
# calculate gradient
15+
gradient = derivative(solution)
16+
# take a step
17+
solution = solution - step_size * gradient
18+
# evaluate candidate point
19+
solution_eval = objective(solution)
20+
# report progress
21+
print('>%d f(%s) = %.5f' % (i, solution, solution_eval))
22+
return [solution, solution_eval]
23+
24+
# Driver Code:
25+
26+
bounds = asarray([[-1.0, 1.0]])
27+
n_iter = 30
28+
step_size = 0.1
29+
best, score = gradient_descent(objective, derivative, bounds, n_iter, step_size)
30+
print('Done!')
31+
print('f(%s) = %f' % (best, score))

0 commit comments

Comments
 (0)