-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathcheckgrad.py
More file actions
executable file
·39 lines (26 loc) · 827 Bytes
/
Copy pathcheckgrad.py
File metadata and controls
executable file
·39 lines (26 loc) · 827 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
#!/usr/bin/env python
import numpy
def checkgrad(func, x, params=[], e=1e-6):
N = len(x)
d = (2 * e * numpy.random.random_sample((N,))) - e
_, gx = func(x, *params)
x2, gx2 = func(x + d, *params)
x1, gx1 = func(x - d, *params)
r = (x2 - x1) / (2 * gx.dot(d) )
return r
def checkgrad_random(func, D=5, params=[], scale=1e-6):
for i in xrange(10):
xr = scale * numpy.random.random_sample((D, ))
print checkgrad(func, xr, params=params)
if __name__ == '__main__':
def f(x):
return numpy.sum(x ** 2), 2 * x
x1 = numpy.array([3, 4, 5])
print checkgrad(f, x1)
checkgrad_random(f)
# this one should be wrong
def g(x):
return numpy.sum(x ** 2), 3 * x
x1 = numpy.array([3, 4, 5])
print checkgrad(g, x1)
checkgrad_random(g)