Skip to content

Commit 0cf41c8

Browse files
committed
Moved optimize test to a new file
simplified code Used fhess_p Added RandomState Added tol=1e-10 to newton_cg Added RandomState with seed 0
1 parent 12b2f16 commit 0cf41c8

File tree

2 files changed

+30
-17
lines changed

2 files changed

+30
-17
lines changed

sklearn/utils/optimize.py

Lines changed: 0 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -157,20 +157,3 @@ def newton_cg(func_grad_hess, func, grad, x0, args=(), eps=1e-4, tol=1e-4,
157157
warnings.warn("newton-cg failed to converge. Increase the "
158158
"number of iterations.")
159159
return xk
160-
161-
162-
###############################################################################
163-
# Tests
164-
165-
if __name__ == "__main__":
166-
A = np.random.normal(size=(10, 10))
167-
168-
def func(x):
169-
Ax = A.dot(x)
170-
return .5*(Ax).dot(Ax)
171-
172-
def func_grad_hess(x):
173-
return func(x), A.T.dot(A.dot(x)), lambda x: A.T.dot(A.dot(x))
174-
175-
x0 = np.ones(10)
176-
out = newton_cg(func_grad_hess, func, x0)
Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
import numpy as np
2+
3+
from sklearn.utils.optimize import newton_cg
4+
from scipy.optimize import fmin_ncg
5+
6+
from sklearn.utils.testing import assert_array_almost_equal
7+
8+
9+
def test_newton_cg():
10+
# Test that newton_cg gives same result as scipy's fmin_ncg
11+
12+
rng = np.random.RandomState(0)
13+
A = rng.normal(size=(10, 10))
14+
x0 = np.ones(10)
15+
16+
def func(x):
17+
Ax = A.dot(x)
18+
return .5 * (Ax).dot(Ax)
19+
20+
def grad(x):
21+
return A.T.dot(A.dot(x))
22+
23+
def hess(x, p):
24+
return p.dot(A.T.dot(A.dot(x.all())))
25+
26+
def func_grad_hess(x):
27+
return func(x), grad(x), lambda x: A.T.dot(A.dot(x))
28+
29+
assert_array_almost_equal(newton_cg(func_grad_hess, func, grad, x0, tol=1e-10),
30+
fmin_ncg(f=func, x0=x0, fprime=grad, fhess_p=hess))

0 commit comments

Comments
 (0)