test_gpr.py 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853
  1. """Testing for Gaussian process regression """
  2. # Author: Jan Hendrik Metzen <jhm@informatik.uni-bremen.de>
  3. # Modified by: Pete Green <p.l.green@liverpool.ac.uk>
  4. # License: BSD 3 clause
  5. import re
  6. import sys
  7. import warnings
  8. import numpy as np
  9. import pytest
  10. from scipy.optimize import approx_fprime
  11. from sklearn.exceptions import ConvergenceWarning
  12. from sklearn.gaussian_process import GaussianProcessRegressor
  13. from sklearn.gaussian_process.kernels import (
  14. RBF,
  15. DotProduct,
  16. ExpSineSquared,
  17. WhiteKernel,
  18. )
  19. from sklearn.gaussian_process.kernels import (
  20. ConstantKernel as C,
  21. )
  22. from sklearn.gaussian_process.tests._mini_sequence_kernel import MiniSeqKernel
  23. from sklearn.utils._testing import (
  24. assert_allclose,
  25. assert_almost_equal,
  26. assert_array_almost_equal,
  27. assert_array_less,
  28. )
  29. def f(x):
  30. return x * np.sin(x)
  31. X = np.atleast_2d([1.0, 3.0, 5.0, 6.0, 7.0, 8.0]).T
  32. X2 = np.atleast_2d([2.0, 4.0, 5.5, 6.5, 7.5]).T
  33. y = f(X).ravel()
  34. fixed_kernel = RBF(length_scale=1.0, length_scale_bounds="fixed")
  35. kernels = [
  36. RBF(length_scale=1.0),
  37. fixed_kernel,
  38. RBF(length_scale=1.0, length_scale_bounds=(1e-3, 1e3)),
  39. C(1.0, (1e-2, 1e2)) * RBF(length_scale=1.0, length_scale_bounds=(1e-3, 1e3)),
  40. C(1.0, (1e-2, 1e2)) * RBF(length_scale=1.0, length_scale_bounds=(1e-3, 1e3))
  41. + C(1e-5, (1e-5, 1e2)),
  42. C(0.1, (1e-2, 1e2)) * RBF(length_scale=1.0, length_scale_bounds=(1e-3, 1e3))
  43. + C(1e-5, (1e-5, 1e2)),
  44. ]
  45. non_fixed_kernels = [kernel for kernel in kernels if kernel != fixed_kernel]
  46. @pytest.mark.parametrize("kernel", kernels)
  47. def test_gpr_interpolation(kernel):
  48. if sys.maxsize <= 2**32:
  49. pytest.xfail("This test may fail on 32 bit Python")
  50. # Test the interpolating property for different kernels.
  51. gpr = GaussianProcessRegressor(kernel=kernel).fit(X, y)
  52. y_pred, y_cov = gpr.predict(X, return_cov=True)
  53. assert_almost_equal(y_pred, y)
  54. assert_almost_equal(np.diag(y_cov), 0.0)
  55. def test_gpr_interpolation_structured():
  56. # Test the interpolating property for different kernels.
  57. kernel = MiniSeqKernel(baseline_similarity_bounds="fixed")
  58. X = ["A", "B", "C"]
  59. y = np.array([1, 2, 3])
  60. gpr = GaussianProcessRegressor(kernel=kernel).fit(X, y)
  61. y_pred, y_cov = gpr.predict(X, return_cov=True)
  62. assert_almost_equal(
  63. kernel(X, eval_gradient=True)[1].ravel(), (1 - np.eye(len(X))).ravel()
  64. )
  65. assert_almost_equal(y_pred, y)
  66. assert_almost_equal(np.diag(y_cov), 0.0)
  67. @pytest.mark.parametrize("kernel", non_fixed_kernels)
  68. def test_lml_improving(kernel):
  69. if sys.maxsize <= 2**32:
  70. pytest.xfail("This test may fail on 32 bit Python")
  71. # Test that hyperparameter-tuning improves log-marginal likelihood.
  72. gpr = GaussianProcessRegressor(kernel=kernel).fit(X, y)
  73. assert gpr.log_marginal_likelihood(gpr.kernel_.theta) > gpr.log_marginal_likelihood(
  74. kernel.theta
  75. )
  76. @pytest.mark.parametrize("kernel", kernels)
  77. def test_lml_precomputed(kernel):
  78. # Test that lml of optimized kernel is stored correctly.
  79. gpr = GaussianProcessRegressor(kernel=kernel).fit(X, y)
  80. assert gpr.log_marginal_likelihood(gpr.kernel_.theta) == pytest.approx(
  81. gpr.log_marginal_likelihood()
  82. )
  83. @pytest.mark.parametrize("kernel", kernels)
  84. def test_lml_without_cloning_kernel(kernel):
  85. # Test that lml of optimized kernel is stored correctly.
  86. gpr = GaussianProcessRegressor(kernel=kernel).fit(X, y)
  87. input_theta = np.ones(gpr.kernel_.theta.shape, dtype=np.float64)
  88. gpr.log_marginal_likelihood(input_theta, clone_kernel=False)
  89. assert_almost_equal(gpr.kernel_.theta, input_theta, 7)
  90. @pytest.mark.parametrize("kernel", non_fixed_kernels)
  91. def test_converged_to_local_maximum(kernel):
  92. # Test that we are in local maximum after hyperparameter-optimization.
  93. gpr = GaussianProcessRegressor(kernel=kernel).fit(X, y)
  94. lml, lml_gradient = gpr.log_marginal_likelihood(gpr.kernel_.theta, True)
  95. assert np.all(
  96. (np.abs(lml_gradient) < 1e-4)
  97. | (gpr.kernel_.theta == gpr.kernel_.bounds[:, 0])
  98. | (gpr.kernel_.theta == gpr.kernel_.bounds[:, 1])
  99. )
  100. @pytest.mark.parametrize("kernel", non_fixed_kernels)
  101. def test_solution_inside_bounds(kernel):
  102. # Test that hyperparameter-optimization remains in bounds#
  103. gpr = GaussianProcessRegressor(kernel=kernel).fit(X, y)
  104. bounds = gpr.kernel_.bounds
  105. max_ = np.finfo(gpr.kernel_.theta.dtype).max
  106. tiny = 1e-10
  107. bounds[~np.isfinite(bounds[:, 1]), 1] = max_
  108. assert_array_less(bounds[:, 0], gpr.kernel_.theta + tiny)
  109. assert_array_less(gpr.kernel_.theta, bounds[:, 1] + tiny)
  110. @pytest.mark.parametrize("kernel", kernels)
  111. def test_lml_gradient(kernel):
  112. # Compare analytic and numeric gradient of log marginal likelihood.
  113. gpr = GaussianProcessRegressor(kernel=kernel).fit(X, y)
  114. lml, lml_gradient = gpr.log_marginal_likelihood(kernel.theta, True)
  115. lml_gradient_approx = approx_fprime(
  116. kernel.theta, lambda theta: gpr.log_marginal_likelihood(theta, False), 1e-10
  117. )
  118. assert_almost_equal(lml_gradient, lml_gradient_approx, 3)
  119. @pytest.mark.parametrize("kernel", kernels)
  120. def test_prior(kernel):
  121. # Test that GP prior has mean 0 and identical variances.
  122. gpr = GaussianProcessRegressor(kernel=kernel)
  123. y_mean, y_cov = gpr.predict(X, return_cov=True)
  124. assert_almost_equal(y_mean, 0, 5)
  125. if len(gpr.kernel.theta) > 1:
  126. # XXX: quite hacky, works only for current kernels
  127. assert_almost_equal(np.diag(y_cov), np.exp(kernel.theta[0]), 5)
  128. else:
  129. assert_almost_equal(np.diag(y_cov), 1, 5)
  130. @pytest.mark.parametrize("kernel", kernels)
  131. def test_sample_statistics(kernel):
  132. # Test that statistics of samples drawn from GP are correct.
  133. gpr = GaussianProcessRegressor(kernel=kernel).fit(X, y)
  134. y_mean, y_cov = gpr.predict(X2, return_cov=True)
  135. samples = gpr.sample_y(X2, 300000)
  136. # More digits accuracy would require many more samples
  137. assert_almost_equal(y_mean, np.mean(samples, 1), 1)
  138. assert_almost_equal(
  139. np.diag(y_cov) / np.diag(y_cov).max(),
  140. np.var(samples, 1) / np.diag(y_cov).max(),
  141. 1,
  142. )
  143. def test_no_optimizer():
  144. # Test that kernel parameters are unmodified when optimizer is None.
  145. kernel = RBF(1.0)
  146. gpr = GaussianProcessRegressor(kernel=kernel, optimizer=None).fit(X, y)
  147. assert np.exp(gpr.kernel_.theta) == 1.0
  148. @pytest.mark.parametrize("kernel", kernels)
  149. @pytest.mark.parametrize("target", [y, np.ones(X.shape[0], dtype=np.float64)])
  150. def test_predict_cov_vs_std(kernel, target):
  151. if sys.maxsize <= 2**32:
  152. pytest.xfail("This test may fail on 32 bit Python")
  153. # Test that predicted std.-dev. is consistent with cov's diagonal.
  154. gpr = GaussianProcessRegressor(kernel=kernel).fit(X, y)
  155. y_mean, y_cov = gpr.predict(X2, return_cov=True)
  156. y_mean, y_std = gpr.predict(X2, return_std=True)
  157. assert_almost_equal(np.sqrt(np.diag(y_cov)), y_std)
  158. def test_anisotropic_kernel():
  159. # Test that GPR can identify meaningful anisotropic length-scales.
  160. # We learn a function which varies in one dimension ten-times slower
  161. # than in the other. The corresponding length-scales should differ by at
  162. # least a factor 5
  163. rng = np.random.RandomState(0)
  164. X = rng.uniform(-1, 1, (50, 2))
  165. y = X[:, 0] + 0.1 * X[:, 1]
  166. kernel = RBF([1.0, 1.0])
  167. gpr = GaussianProcessRegressor(kernel=kernel).fit(X, y)
  168. assert np.exp(gpr.kernel_.theta[1]) > np.exp(gpr.kernel_.theta[0]) * 5
  169. def test_random_starts():
  170. # Test that an increasing number of random-starts of GP fitting only
  171. # increases the log marginal likelihood of the chosen theta.
  172. n_samples, n_features = 25, 2
  173. rng = np.random.RandomState(0)
  174. X = rng.randn(n_samples, n_features) * 2 - 1
  175. y = (
  176. np.sin(X).sum(axis=1)
  177. + np.sin(3 * X).sum(axis=1)
  178. + rng.normal(scale=0.1, size=n_samples)
  179. )
  180. kernel = C(1.0, (1e-2, 1e2)) * RBF(
  181. length_scale=[1.0] * n_features, length_scale_bounds=[(1e-4, 1e2)] * n_features
  182. ) + WhiteKernel(noise_level=1e-5, noise_level_bounds=(1e-5, 1e1))
  183. last_lml = -np.inf
  184. for n_restarts_optimizer in range(5):
  185. gp = GaussianProcessRegressor(
  186. kernel=kernel,
  187. n_restarts_optimizer=n_restarts_optimizer,
  188. random_state=0,
  189. ).fit(X, y)
  190. lml = gp.log_marginal_likelihood(gp.kernel_.theta)
  191. assert lml > last_lml - np.finfo(np.float32).eps
  192. last_lml = lml
  193. @pytest.mark.parametrize("kernel", kernels)
  194. def test_y_normalization(kernel):
  195. """
  196. Test normalization of the target values in GP
  197. Fitting non-normalizing GP on normalized y and fitting normalizing GP
  198. on unnormalized y should yield identical results. Note that, here,
  199. 'normalized y' refers to y that has been made zero mean and unit
  200. variance.
  201. """
  202. y_mean = np.mean(y)
  203. y_std = np.std(y)
  204. y_norm = (y - y_mean) / y_std
  205. # Fit non-normalizing GP on normalized y
  206. gpr = GaussianProcessRegressor(kernel=kernel)
  207. gpr.fit(X, y_norm)
  208. # Fit normalizing GP on unnormalized y
  209. gpr_norm = GaussianProcessRegressor(kernel=kernel, normalize_y=True)
  210. gpr_norm.fit(X, y)
  211. # Compare predicted mean, std-devs and covariances
  212. y_pred, y_pred_std = gpr.predict(X2, return_std=True)
  213. y_pred = y_pred * y_std + y_mean
  214. y_pred_std = y_pred_std * y_std
  215. y_pred_norm, y_pred_std_norm = gpr_norm.predict(X2, return_std=True)
  216. assert_almost_equal(y_pred, y_pred_norm)
  217. assert_almost_equal(y_pred_std, y_pred_std_norm)
  218. _, y_cov = gpr.predict(X2, return_cov=True)
  219. y_cov = y_cov * y_std**2
  220. _, y_cov_norm = gpr_norm.predict(X2, return_cov=True)
  221. assert_almost_equal(y_cov, y_cov_norm)
  222. def test_large_variance_y():
  223. """
  224. Here we test that, when noramlize_y=True, our GP can produce a
  225. sensible fit to training data whose variance is significantly
  226. larger than unity. This test was made in response to issue #15612.
  227. GP predictions are verified against predictions that were made
  228. using GPy which, here, is treated as the 'gold standard'. Note that we
  229. only investigate the RBF kernel here, as that is what was used in the
  230. GPy implementation.
  231. The following code can be used to recreate the GPy data:
  232. --------------------------------------------------------------------------
  233. import GPy
  234. kernel_gpy = GPy.kern.RBF(input_dim=1, lengthscale=1.)
  235. gpy = GPy.models.GPRegression(X, np.vstack(y_large), kernel_gpy)
  236. gpy.optimize()
  237. y_pred_gpy, y_var_gpy = gpy.predict(X2)
  238. y_pred_std_gpy = np.sqrt(y_var_gpy)
  239. --------------------------------------------------------------------------
  240. """
  241. # Here we utilise a larger variance version of the training data
  242. y_large = 10 * y
  243. # Standard GP with normalize_y=True
  244. RBF_params = {"length_scale": 1.0}
  245. kernel = RBF(**RBF_params)
  246. gpr = GaussianProcessRegressor(kernel=kernel, normalize_y=True)
  247. gpr.fit(X, y_large)
  248. y_pred, y_pred_std = gpr.predict(X2, return_std=True)
  249. # 'Gold standard' mean predictions from GPy
  250. y_pred_gpy = np.array(
  251. [15.16918303, -27.98707845, -39.31636019, 14.52605515, 69.18503589]
  252. )
  253. # 'Gold standard' std predictions from GPy
  254. y_pred_std_gpy = np.array(
  255. [7.78860962, 3.83179178, 0.63149951, 0.52745188, 0.86170042]
  256. )
  257. # Based on numerical experiments, it's reasonable to expect our
  258. # GP's mean predictions to get within 7% of predictions of those
  259. # made by GPy.
  260. assert_allclose(y_pred, y_pred_gpy, rtol=0.07, atol=0)
  261. # Based on numerical experiments, it's reasonable to expect our
  262. # GP's std predictions to get within 15% of predictions of those
  263. # made by GPy.
  264. assert_allclose(y_pred_std, y_pred_std_gpy, rtol=0.15, atol=0)
  265. def test_y_multioutput():
  266. # Test that GPR can deal with multi-dimensional target values
  267. y_2d = np.vstack((y, y * 2)).T
  268. # Test for fixed kernel that first dimension of 2d GP equals the output
  269. # of 1d GP and that second dimension is twice as large
  270. kernel = RBF(length_scale=1.0)
  271. gpr = GaussianProcessRegressor(kernel=kernel, optimizer=None, normalize_y=False)
  272. gpr.fit(X, y)
  273. gpr_2d = GaussianProcessRegressor(kernel=kernel, optimizer=None, normalize_y=False)
  274. gpr_2d.fit(X, y_2d)
  275. y_pred_1d, y_std_1d = gpr.predict(X2, return_std=True)
  276. y_pred_2d, y_std_2d = gpr_2d.predict(X2, return_std=True)
  277. _, y_cov_1d = gpr.predict(X2, return_cov=True)
  278. _, y_cov_2d = gpr_2d.predict(X2, return_cov=True)
  279. assert_almost_equal(y_pred_1d, y_pred_2d[:, 0])
  280. assert_almost_equal(y_pred_1d, y_pred_2d[:, 1] / 2)
  281. # Standard deviation and covariance do not depend on output
  282. for target in range(y_2d.shape[1]):
  283. assert_almost_equal(y_std_1d, y_std_2d[..., target])
  284. assert_almost_equal(y_cov_1d, y_cov_2d[..., target])
  285. y_sample_1d = gpr.sample_y(X2, n_samples=10)
  286. y_sample_2d = gpr_2d.sample_y(X2, n_samples=10)
  287. assert y_sample_1d.shape == (5, 10)
  288. assert y_sample_2d.shape == (5, 2, 10)
  289. # Only the first target will be equal
  290. assert_almost_equal(y_sample_1d, y_sample_2d[:, 0, :])
  291. # Test hyperparameter optimization
  292. for kernel in kernels:
  293. gpr = GaussianProcessRegressor(kernel=kernel, normalize_y=True)
  294. gpr.fit(X, y)
  295. gpr_2d = GaussianProcessRegressor(kernel=kernel, normalize_y=True)
  296. gpr_2d.fit(X, np.vstack((y, y)).T)
  297. assert_almost_equal(gpr.kernel_.theta, gpr_2d.kernel_.theta, 4)
  298. @pytest.mark.parametrize("kernel", non_fixed_kernels)
  299. def test_custom_optimizer(kernel):
  300. # Test that GPR can use externally defined optimizers.
  301. # Define a dummy optimizer that simply tests 50 random hyperparameters
  302. def optimizer(obj_func, initial_theta, bounds):
  303. rng = np.random.RandomState(0)
  304. theta_opt, func_min = initial_theta, obj_func(
  305. initial_theta, eval_gradient=False
  306. )
  307. for _ in range(50):
  308. theta = np.atleast_1d(
  309. rng.uniform(np.maximum(-2, bounds[:, 0]), np.minimum(1, bounds[:, 1]))
  310. )
  311. f = obj_func(theta, eval_gradient=False)
  312. if f < func_min:
  313. theta_opt, func_min = theta, f
  314. return theta_opt, func_min
  315. gpr = GaussianProcessRegressor(kernel=kernel, optimizer=optimizer)
  316. gpr.fit(X, y)
  317. # Checks that optimizer improved marginal likelihood
  318. assert gpr.log_marginal_likelihood(gpr.kernel_.theta) > gpr.log_marginal_likelihood(
  319. gpr.kernel.theta
  320. )
  321. def test_gpr_correct_error_message():
  322. X = np.arange(12).reshape(6, -1)
  323. y = np.ones(6)
  324. kernel = DotProduct()
  325. gpr = GaussianProcessRegressor(kernel=kernel, alpha=0.0)
  326. message = (
  327. "The kernel, %s, is not returning a "
  328. "positive definite matrix. Try gradually increasing "
  329. "the 'alpha' parameter of your "
  330. "GaussianProcessRegressor estimator." % kernel
  331. )
  332. with pytest.raises(np.linalg.LinAlgError, match=re.escape(message)):
  333. gpr.fit(X, y)
  334. @pytest.mark.parametrize("kernel", kernels)
  335. def test_duplicate_input(kernel):
  336. # Test GPR can handle two different output-values for the same input.
  337. gpr_equal_inputs = GaussianProcessRegressor(kernel=kernel, alpha=1e-2)
  338. gpr_similar_inputs = GaussianProcessRegressor(kernel=kernel, alpha=1e-2)
  339. X_ = np.vstack((X, X[0]))
  340. y_ = np.hstack((y, y[0] + 1))
  341. gpr_equal_inputs.fit(X_, y_)
  342. X_ = np.vstack((X, X[0] + 1e-15))
  343. y_ = np.hstack((y, y[0] + 1))
  344. gpr_similar_inputs.fit(X_, y_)
  345. X_test = np.linspace(0, 10, 100)[:, None]
  346. y_pred_equal, y_std_equal = gpr_equal_inputs.predict(X_test, return_std=True)
  347. y_pred_similar, y_std_similar = gpr_similar_inputs.predict(X_test, return_std=True)
  348. assert_almost_equal(y_pred_equal, y_pred_similar)
  349. assert_almost_equal(y_std_equal, y_std_similar)
  350. def test_no_fit_default_predict():
  351. # Test that GPR predictions without fit does not break by default.
  352. default_kernel = C(1.0, constant_value_bounds="fixed") * RBF(
  353. 1.0, length_scale_bounds="fixed"
  354. )
  355. gpr1 = GaussianProcessRegressor()
  356. _, y_std1 = gpr1.predict(X, return_std=True)
  357. _, y_cov1 = gpr1.predict(X, return_cov=True)
  358. gpr2 = GaussianProcessRegressor(kernel=default_kernel)
  359. _, y_std2 = gpr2.predict(X, return_std=True)
  360. _, y_cov2 = gpr2.predict(X, return_cov=True)
  361. assert_array_almost_equal(y_std1, y_std2)
  362. assert_array_almost_equal(y_cov1, y_cov2)
  363. def test_warning_bounds():
  364. kernel = RBF(length_scale_bounds=[1e-5, 1e-3])
  365. gpr = GaussianProcessRegressor(kernel=kernel)
  366. warning_message = (
  367. "The optimal value found for dimension 0 of parameter "
  368. "length_scale is close to the specified upper bound "
  369. "0.001. Increasing the bound and calling fit again may "
  370. "find a better value."
  371. )
  372. with pytest.warns(ConvergenceWarning, match=warning_message):
  373. gpr.fit(X, y)
  374. kernel_sum = WhiteKernel(noise_level_bounds=[1e-5, 1e-3]) + RBF(
  375. length_scale_bounds=[1e3, 1e5]
  376. )
  377. gpr_sum = GaussianProcessRegressor(kernel=kernel_sum)
  378. with warnings.catch_warnings(record=True) as record:
  379. warnings.simplefilter("always")
  380. gpr_sum.fit(X, y)
  381. assert len(record) == 2
  382. assert issubclass(record[0].category, ConvergenceWarning)
  383. assert (
  384. record[0].message.args[0]
  385. == "The optimal value found for "
  386. "dimension 0 of parameter "
  387. "k1__noise_level is close to the "
  388. "specified upper bound 0.001. "
  389. "Increasing the bound and calling "
  390. "fit again may find a better value."
  391. )
  392. assert issubclass(record[1].category, ConvergenceWarning)
  393. assert (
  394. record[1].message.args[0]
  395. == "The optimal value found for "
  396. "dimension 0 of parameter "
  397. "k2__length_scale is close to the "
  398. "specified lower bound 1000.0. "
  399. "Decreasing the bound and calling "
  400. "fit again may find a better value."
  401. )
  402. X_tile = np.tile(X, 2)
  403. kernel_dims = RBF(length_scale=[1.0, 2.0], length_scale_bounds=[1e1, 1e2])
  404. gpr_dims = GaussianProcessRegressor(kernel=kernel_dims)
  405. with warnings.catch_warnings(record=True) as record:
  406. warnings.simplefilter("always")
  407. gpr_dims.fit(X_tile, y)
  408. assert len(record) == 2
  409. assert issubclass(record[0].category, ConvergenceWarning)
  410. assert (
  411. record[0].message.args[0]
  412. == "The optimal value found for "
  413. "dimension 0 of parameter "
  414. "length_scale is close to the "
  415. "specified lower bound 10.0. "
  416. "Decreasing the bound and calling "
  417. "fit again may find a better value."
  418. )
  419. assert issubclass(record[1].category, ConvergenceWarning)
  420. assert (
  421. record[1].message.args[0]
  422. == "The optimal value found for "
  423. "dimension 1 of parameter "
  424. "length_scale is close to the "
  425. "specified lower bound 10.0. "
  426. "Decreasing the bound and calling "
  427. "fit again may find a better value."
  428. )
  429. def test_bound_check_fixed_hyperparameter():
  430. # Regression test for issue #17943
  431. # Check that having a hyperparameter with fixed bounds doesn't cause an
  432. # error
  433. k1 = 50.0**2 * RBF(length_scale=50.0) # long term smooth rising trend
  434. k2 = ExpSineSquared(
  435. length_scale=1.0, periodicity=1.0, periodicity_bounds="fixed"
  436. ) # seasonal component
  437. kernel = k1 + k2
  438. GaussianProcessRegressor(kernel=kernel).fit(X, y)
  439. @pytest.mark.parametrize("kernel", kernels)
  440. def test_constant_target(kernel):
  441. """Check that the std. dev. is affected to 1 when normalizing a constant
  442. feature.
  443. Non-regression test for:
  444. https://github.com/scikit-learn/scikit-learn/issues/18318
  445. NaN where affected to the target when scaling due to null std. dev. with
  446. constant target.
  447. """
  448. y_constant = np.ones(X.shape[0], dtype=np.float64)
  449. gpr = GaussianProcessRegressor(kernel=kernel, normalize_y=True)
  450. gpr.fit(X, y_constant)
  451. assert gpr._y_train_std == pytest.approx(1.0)
  452. y_pred, y_cov = gpr.predict(X, return_cov=True)
  453. assert_allclose(y_pred, y_constant)
  454. # set atol because we compare to zero
  455. assert_allclose(np.diag(y_cov), 0.0, atol=1e-9)
  456. # Test multi-target data
  457. n_samples, n_targets = X.shape[0], 2
  458. rng = np.random.RandomState(0)
  459. y = np.concatenate(
  460. [
  461. rng.normal(size=(n_samples, 1)), # non-constant target
  462. np.full(shape=(n_samples, 1), fill_value=2), # constant target
  463. ],
  464. axis=1,
  465. )
  466. gpr.fit(X, y)
  467. Y_pred, Y_cov = gpr.predict(X, return_cov=True)
  468. assert_allclose(Y_pred[:, 1], 2)
  469. assert_allclose(np.diag(Y_cov[..., 1]), 0.0, atol=1e-9)
  470. assert Y_pred.shape == (n_samples, n_targets)
  471. assert Y_cov.shape == (n_samples, n_samples, n_targets)
  472. def test_gpr_consistency_std_cov_non_invertible_kernel():
  473. """Check the consistency between the returned std. dev. and the covariance.
  474. Non-regression test for:
  475. https://github.com/scikit-learn/scikit-learn/issues/19936
  476. Inconsistencies were observed when the kernel cannot be inverted (or
  477. numerically stable).
  478. """
  479. kernel = C(8.98576054e05, (1e-12, 1e12)) * RBF(
  480. [5.91326520e02, 1.32584051e03], (1e-12, 1e12)
  481. ) + WhiteKernel(noise_level=1e-5)
  482. gpr = GaussianProcessRegressor(kernel=kernel, alpha=0, optimizer=None)
  483. X_train = np.array(
  484. [
  485. [0.0, 0.0],
  486. [1.54919334, -0.77459667],
  487. [-1.54919334, 0.0],
  488. [0.0, -1.54919334],
  489. [0.77459667, 0.77459667],
  490. [-0.77459667, 1.54919334],
  491. ]
  492. )
  493. y_train = np.array(
  494. [
  495. [-2.14882017e-10],
  496. [-4.66975823e00],
  497. [4.01823986e00],
  498. [-1.30303674e00],
  499. [-1.35760156e00],
  500. [3.31215668e00],
  501. ]
  502. )
  503. gpr.fit(X_train, y_train)
  504. X_test = np.array(
  505. [
  506. [-1.93649167, -1.93649167],
  507. [1.93649167, -1.93649167],
  508. [-1.93649167, 1.93649167],
  509. [1.93649167, 1.93649167],
  510. ]
  511. )
  512. pred1, std = gpr.predict(X_test, return_std=True)
  513. pred2, cov = gpr.predict(X_test, return_cov=True)
  514. assert_allclose(std, np.sqrt(np.diagonal(cov)), rtol=1e-5)
  515. @pytest.mark.parametrize(
  516. "params, TypeError, err_msg",
  517. [
  518. (
  519. {"alpha": np.zeros(100)},
  520. ValueError,
  521. "alpha must be a scalar or an array with same number of entries as y",
  522. ),
  523. (
  524. {
  525. "kernel": WhiteKernel(noise_level_bounds=(-np.inf, np.inf)),
  526. "n_restarts_optimizer": 2,
  527. },
  528. ValueError,
  529. "requires that all bounds are finite",
  530. ),
  531. ],
  532. )
  533. def test_gpr_fit_error(params, TypeError, err_msg):
  534. """Check that expected error are raised during fit."""
  535. gpr = GaussianProcessRegressor(**params)
  536. with pytest.raises(TypeError, match=err_msg):
  537. gpr.fit(X, y)
  538. def test_gpr_lml_error():
  539. """Check that we raise the proper error in the LML method."""
  540. gpr = GaussianProcessRegressor(kernel=RBF()).fit(X, y)
  541. err_msg = "Gradient can only be evaluated for theta!=None"
  542. with pytest.raises(ValueError, match=err_msg):
  543. gpr.log_marginal_likelihood(eval_gradient=True)
  544. def test_gpr_predict_error():
  545. """Check that we raise the proper error during predict."""
  546. gpr = GaussianProcessRegressor(kernel=RBF()).fit(X, y)
  547. err_msg = "At most one of return_std or return_cov can be requested."
  548. with pytest.raises(RuntimeError, match=err_msg):
  549. gpr.predict(X, return_cov=True, return_std=True)
  550. @pytest.mark.parametrize("normalize_y", [True, False])
  551. @pytest.mark.parametrize("n_targets", [None, 1, 10])
  552. def test_predict_shapes(normalize_y, n_targets):
  553. """Check the shapes of y_mean, y_std, and y_cov in single-output
  554. (n_targets=None) and multi-output settings, including the edge case when
  555. n_targets=1, where the sklearn convention is to squeeze the predictions.
  556. Non-regression test for:
  557. https://github.com/scikit-learn/scikit-learn/issues/17394
  558. https://github.com/scikit-learn/scikit-learn/issues/18065
  559. https://github.com/scikit-learn/scikit-learn/issues/22174
  560. """
  561. rng = np.random.RandomState(1234)
  562. n_features, n_samples_train, n_samples_test = 6, 9, 7
  563. y_train_shape = (n_samples_train,)
  564. if n_targets is not None:
  565. y_train_shape = y_train_shape + (n_targets,)
  566. # By convention single-output data is squeezed upon prediction
  567. y_test_shape = (n_samples_test,)
  568. if n_targets is not None and n_targets > 1:
  569. y_test_shape = y_test_shape + (n_targets,)
  570. X_train = rng.randn(n_samples_train, n_features)
  571. X_test = rng.randn(n_samples_test, n_features)
  572. y_train = rng.randn(*y_train_shape)
  573. model = GaussianProcessRegressor(normalize_y=normalize_y)
  574. model.fit(X_train, y_train)
  575. y_pred, y_std = model.predict(X_test, return_std=True)
  576. _, y_cov = model.predict(X_test, return_cov=True)
  577. assert y_pred.shape == y_test_shape
  578. assert y_std.shape == y_test_shape
  579. assert y_cov.shape == (n_samples_test,) + y_test_shape
  580. @pytest.mark.parametrize("normalize_y", [True, False])
  581. @pytest.mark.parametrize("n_targets", [None, 1, 10])
  582. def test_sample_y_shapes(normalize_y, n_targets):
  583. """Check the shapes of y_samples in single-output (n_targets=0) and
  584. multi-output settings, including the edge case when n_targets=1, where the
  585. sklearn convention is to squeeze the predictions.
  586. Non-regression test for:
  587. https://github.com/scikit-learn/scikit-learn/issues/22175
  588. """
  589. rng = np.random.RandomState(1234)
  590. n_features, n_samples_train = 6, 9
  591. # Number of spatial locations to predict at
  592. n_samples_X_test = 7
  593. # Number of sample predictions per test point
  594. n_samples_y_test = 5
  595. y_train_shape = (n_samples_train,)
  596. if n_targets is not None:
  597. y_train_shape = y_train_shape + (n_targets,)
  598. # By convention single-output data is squeezed upon prediction
  599. if n_targets is not None and n_targets > 1:
  600. y_test_shape = (n_samples_X_test, n_targets, n_samples_y_test)
  601. else:
  602. y_test_shape = (n_samples_X_test, n_samples_y_test)
  603. X_train = rng.randn(n_samples_train, n_features)
  604. X_test = rng.randn(n_samples_X_test, n_features)
  605. y_train = rng.randn(*y_train_shape)
  606. model = GaussianProcessRegressor(normalize_y=normalize_y)
  607. # FIXME: before fitting, the estimator does not have information regarding
  608. # the number of targets and default to 1. This is inconsistent with the shape
  609. # provided after `fit`. This assert should be made once the following issue
  610. # is fixed:
  611. # https://github.com/scikit-learn/scikit-learn/issues/22430
  612. # y_samples = model.sample_y(X_test, n_samples=n_samples_y_test)
  613. # assert y_samples.shape == y_test_shape
  614. model.fit(X_train, y_train)
  615. y_samples = model.sample_y(X_test, n_samples=n_samples_y_test)
  616. assert y_samples.shape == y_test_shape
  617. @pytest.mark.parametrize("n_targets", [None, 1, 2, 3])
  618. @pytest.mark.parametrize("n_samples", [1, 5])
  619. def test_sample_y_shape_with_prior(n_targets, n_samples):
  620. """Check the output shape of `sample_y` is consistent before and after `fit`."""
  621. rng = np.random.RandomState(1024)
  622. X = rng.randn(10, 3)
  623. y = rng.randn(10, n_targets if n_targets is not None else 1)
  624. model = GaussianProcessRegressor(n_targets=n_targets)
  625. shape_before_fit = model.sample_y(X, n_samples=n_samples).shape
  626. model.fit(X, y)
  627. shape_after_fit = model.sample_y(X, n_samples=n_samples).shape
  628. assert shape_before_fit == shape_after_fit
  629. @pytest.mark.parametrize("n_targets", [None, 1, 2, 3])
  630. def test_predict_shape_with_prior(n_targets):
  631. """Check the output shape of `predict` with prior distribution."""
  632. rng = np.random.RandomState(1024)
  633. n_sample = 10
  634. X = rng.randn(n_sample, 3)
  635. y = rng.randn(n_sample, n_targets if n_targets is not None else 1)
  636. model = GaussianProcessRegressor(n_targets=n_targets)
  637. mean_prior, cov_prior = model.predict(X, return_cov=True)
  638. _, std_prior = model.predict(X, return_std=True)
  639. model.fit(X, y)
  640. mean_post, cov_post = model.predict(X, return_cov=True)
  641. _, std_post = model.predict(X, return_std=True)
  642. assert mean_prior.shape == mean_post.shape
  643. assert cov_prior.shape == cov_post.shape
  644. assert std_prior.shape == std_post.shape
  645. def test_n_targets_error():
  646. """Check that an error is raised when the number of targets seen at fit is
  647. inconsistent with n_targets.
  648. """
  649. rng = np.random.RandomState(0)
  650. X = rng.randn(10, 3)
  651. y = rng.randn(10, 2)
  652. model = GaussianProcessRegressor(n_targets=1)
  653. with pytest.raises(ValueError, match="The number of targets seen in `y`"):
  654. model.fit(X, y)
  655. class CustomKernel(C):
  656. """
  657. A custom kernel that has a diag method that returns the first column of the
  658. input matrix X. This is a helper for the test to check that the input
  659. matrix X is not mutated.
  660. """
  661. def diag(self, X):
  662. return X[:, 0]
  663. def test_gpr_predict_input_not_modified():
  664. """
  665. Check that the input X is not modified by the predict method of the
  666. GaussianProcessRegressor when setting return_std=True.
  667. Non-regression test for:
  668. https://github.com/scikit-learn/scikit-learn/issues/24340
  669. """
  670. gpr = GaussianProcessRegressor(kernel=CustomKernel()).fit(X, y)
  671. X2_copy = np.copy(X2)
  672. _, _ = gpr.predict(X2, return_std=True)
  673. assert_allclose(X2, X2_copy)