Skip to content

TST use global_random_seed in sklearn/utils/tests/test_optimize.py #30112

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 14 commits into from
Apr 10, 2025
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 9 additions & 5 deletions sklearn/utils/tests/test_optimize.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,14 +3,14 @@
from scipy.optimize import fmin_ncg

from sklearn.exceptions import ConvergenceWarning
from sklearn.utils._testing import assert_array_almost_equal
from sklearn.utils._testing import assert_allclose
from sklearn.utils.optimize import _newton_cg


def test_newton_cg():
def test_newton_cg(global_random_seed):
# Test that newton_cg gives same result as scipy's fmin_ncg

rng = np.random.RandomState(0)
rng = np.random.RandomState(global_random_seed)
A = rng.normal(size=(10, 10))
x0 = np.ones(10)

Expand All @@ -27,9 +27,13 @@ def hess(x, p):
def grad_hess(x):
return grad(x), lambda x: A.T.dot(A.dot(x))

assert_array_almost_equal(
_newton_cg(grad_hess, func, grad, x0, tol=1e-10)[0],
# func is a definite positive quadratic form, so the minimum is at x = 0
# hence the use of absolute tolerance.
assert np.all(np.abs(_newton_cg(grad_hess, func, grad, x0, tol=1e-10)[0]) <= 1e-7)
assert_allclose(
_newton_cg(grad_hess, func, grad, x0, tol=1e-7)[0],
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

With a tolerance of 1e-10 I had two test failures. I was able to resolve these by reducing the threshold to 1e-7. It's not an optimal solution but the default of tol is 1e-4. So I think this solution should be acceptable.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think it's an okay solution. Both functions don't have the same parameters so it's hard to find the right combination such that they have the same behavior.

I replaced with assert_allclose and added a comment to add a bit more explanation.

fmin_ncg(f=func, x0=x0, fprime=grad, fhess_p=hess),
atol=1e-5,
)


Expand Down