Aluode/PerceptionLabPortable
0
1"""Global configuration state and functions for management"""
2
3# Authors: The scikit-learn developers
4# SPDX-License-Identifier: BSD-3-Clause
5
6import os
7import threading
8from contextlib import contextmanager as contextmanager
9
10_global_config = {
11 "assume_finite": bool(os.environ.get("SKLEARN_ASSUME_FINITE", False)),
12 "working_memory": int(os.environ.get("SKLEARN_WORKING_MEMORY", 1024)),
13 "print_changed_only": True,
14 "display": "diagram",
15 "pairwise_dist_chunk_size": int(
16 os.environ.get("SKLEARN_PAIRWISE_DIST_CHUNK_SIZE", 256)
17 ),
18 "enable_cython_pairwise_dist": True,
19 "array_api_dispatch": False,
20 "transform_output": "default",
21 "enable_metadata_routing": False,
22 "skip_parameter_validation": False,
23}
24_threadlocal = threading.local()
25
26
27def _get_threadlocal_config():
28 """Get a threadlocal **mutable** configuration. If the configuration
29 does not exist, copy the default global configuration."""
30 if not hasattr(_threadlocal, "global_config"):
31 _threadlocal.global_config = _global_config.copy()
32 return _threadlocal.global_config
33
34
35def get_config():
36 """Retrieve the current scikit-learn configuration.
37
38 This reflects the effective global configurations as established by default upon
39 library import, or modified via :func:`set_config` or :func:`config_context`.
40
41 Returns
42 -------
43 config : dict
44 Keys are parameter names that can be passed to :func:`set_config`.
45
46 See Also
47 --------
48 config_context : Context manager for global scikit-learn configuration.
49 set_config : Set global scikit-learn configuration.
50
51 Examples
52 --------
53 >>> import sklearn
54 >>> config = sklearn.get_config()
55 >>> config.keys()
56 dict_keys([...])
57 """
58 # Return a copy of the threadlocal configuration so that users will
59 # not be able to modify the configuration with the returned dict.
60 return _get_threadlocal_config().copy()
61
62
63def set_config(
64 assume_finite=None,
65 working_memory=None,
66 print_changed_only=None,
67 display=None,
68 pairwise_dist_chunk_size=None,
69 enable_cython_pairwise_dist=None,
70 array_api_dispatch=None,
71 transform_output=None,
72 enable_metadata_routing=None,
73 skip_parameter_validation=None,
74):
75 """Set global scikit-learn configuration.
76
77 These settings control the behaviour of scikit-learn functions during a library
78 usage session. Global configuration defaults (as described in the parameter list
79 below) take effect when scikit-learn is imported.
80
81 This function can be used to modify the global scikit-learn configuration at
82 runtime. Passing `None` as an argument (the default) leaves the corresponding
83 setting unchanged. This allows users to selectively update the global configuration
84 values without affecting the others.
85
86 .. versionadded:: 0.19
87
88 Parameters
89 ----------
90 assume_finite : bool, default=None
91 If True, validation for finiteness will be skipped,
92 saving time, but leading to potential crashes. If
93 False, validation for finiteness will be performed,
94 avoiding error. Global default: False.
95
96 .. versionadded:: 0.19
97
98 working_memory : int, default=None
99 If set, scikit-learn will attempt to limit the size of temporary arrays
100 to this number of MiB (per job when parallelised), often saving both
101 computation time and memory on expensive operations that can be
102 performed in chunks. Global default: 1024.
103
104 .. versionadded:: 0.20
105
106 print_changed_only : bool, default=None
107 If True, only the parameters that were set to non-default
108 values will be printed when printing an estimator. For example,
109 ``print(SVC())`` while True will only print 'SVC()' while the default
110 behaviour would be to print 'SVC(C=1.0, cache_size=200, ...)' with
111 all the non-changed parameters. Global default: True.
112
113 .. versionadded:: 0.21
114 .. versionchanged:: 0.23
115 Global default configuration changed from False to True.
116
117 display : {'text', 'diagram'}, default=None
118 If 'diagram', estimators will be displayed as a diagram in a Jupyter
119 lab or notebook context. If 'text', estimators will be displayed as
120 text. Global default: 'diagram'.
121
122 .. versionadded:: 0.23
123
124 pairwise_dist_chunk_size : int, default=None
125 The number of row vectors per chunk for the accelerated pairwise-
126 distances reduction backend. Global default: 256 (suitable for most of
127 modern laptops' caches and architectures).
128
129 Intended for easier benchmarking and testing of scikit-learn internals.
130 End users are not expected to benefit from customizing this configuration
131 setting.
132
133 .. versionadded:: 1.1
134
135 enable_cython_pairwise_dist : bool, default=None
136 Use the accelerated pairwise-distances reduction backend when
137 possible. Global default: True.
138
139 Intended for easier benchmarking and testing of scikit-learn internals.
140 End users are not expected to benefit from customizing this configuration
141 setting.
142
143 .. versionadded:: 1.1
144
145 array_api_dispatch : bool, default=None
146 Use Array API dispatching when inputs follow the Array API standard.
147 Global default: False.
148
149 See the :ref:`User Guide <array_api>` for more details.
150
151 .. versionadded:: 1.2
152
153 transform_output : str, default=None
154 Configure output of `transform` and `fit_transform`.
155
156 See :ref:`sphx_glr_auto_examples_miscellaneous_plot_set_output.py`
157 for an example on how to use the API.
158
159 - `"default"`: Default output format of a transformer
160 - `"pandas"`: DataFrame output
161 - `"polars"`: Polars output
162 - `None`: Transform configuration is unchanged
163
164 Global default: "default".
165
166 .. versionadded:: 1.2
167 .. versionadded:: 1.4
168 `"polars"` option was added.
169
170 enable_metadata_routing : bool, default=None
171 Enable metadata routing. By default this feature is disabled.
172
173 Refer to :ref:`metadata routing user guide <metadata_routing>` for more
174 details.
175
176 - `True`: Metadata routing is enabled
177 - `False`: Metadata routing is disabled, use the old syntax.
178 - `None`: Configuration is unchanged
179
180 Global default: False.
181
182 .. versionadded:: 1.3
183
184 skip_parameter_validation : bool, default=None
185 If `True`, disable the validation of the hyper-parameters' types and values in
186 the fit method of estimators and for arguments passed to public helper
187 functions. It can save time in some situations but can lead to low level
188 crashes and exceptions with confusing error messages.
189 Global default: False.
190
191 Note that for data parameters, such as `X` and `y`, only type validation is
192 skipped but validation with `check_array` will continue to run.
193
194 .. versionadded:: 1.3
195
196 See Also
197 --------
198 config_context : Context manager for global scikit-learn configuration.
199 get_config : Retrieve current values of the global configuration.
200
201 Examples
202 --------
203 >>> from sklearn import set_config
204 >>> set_config(display='diagram') # doctest: +SKIP
205 """
206 local_config = _get_threadlocal_config()
207
208 if assume_finite is not None:
209 local_config["assume_finite"] = assume_finite
210 if working_memory is not None:
211 local_config["working_memory"] = working_memory
212 if print_changed_only is not None:
213 local_config["print_changed_only"] = print_changed_only
214 if display is not None:
215 local_config["display"] = display
216 if pairwise_dist_chunk_size is not None:
217 local_config["pairwise_dist_chunk_size"] = pairwise_dist_chunk_size
218 if enable_cython_pairwise_dist is not None:
219 local_config["enable_cython_pairwise_dist"] = enable_cython_pairwise_dist
220 if array_api_dispatch is not None:
221 from .utils._array_api import _check_array_api_dispatch
222
223 _check_array_api_dispatch(array_api_dispatch)
224 local_config["array_api_dispatch"] = array_api_dispatch
225 if transform_output is not None:
226 local_config["transform_output"] = transform_output
227 if enable_metadata_routing is not None:
228 local_config["enable_metadata_routing"] = enable_metadata_routing
229 if skip_parameter_validation is not None:
230 local_config["skip_parameter_validation"] = skip_parameter_validation
231
232
233@contextmanager
234def config_context(
235 *,
236 assume_finite=None,
237 working_memory=None,
238 print_changed_only=None,
239 display=None,
240 pairwise_dist_chunk_size=None,
241 enable_cython_pairwise_dist=None,
242 array_api_dispatch=None,
243 transform_output=None,
244 enable_metadata_routing=None,
245 skip_parameter_validation=None,
246):
247 """Context manager to temporarily change the global scikit-learn configuration.
248
249 This context manager can be used to apply scikit-learn configuration changes within
250 the scope of the with statement. Once the context exits, the global configuration is
251 restored again.
252
253 The default global configurations (which take effect when scikit-learn is imported)
254 are defined below in the parameter list.
255
256 Parameters
257 ----------
258 assume_finite : bool, default=None
259 If True, validation for finiteness will be skipped,
260 saving time, but leading to potential crashes. If
261 False, validation for finiteness will be performed,
262 avoiding error. If None, the existing configuration won't change.
263 Global default: False.
264
265 working_memory : int, default=None
266 If set, scikit-learn will attempt to limit the size of temporary arrays
267 to this number of MiB (per job when parallelised), often saving both
268 computation time and memory on expensive operations that can be
269 performed in chunks. If None, the existing configuration won't change.
270 Global default: 1024.
271
272 print_changed_only : bool, default=None
273 If True, only the parameters that were set to non-default
274 values will be printed when printing an estimator. For example,
275 ``print(SVC())`` while True will only print 'SVC()', but would print
276 'SVC(C=1.0, cache_size=200, ...)' with all the non-changed parameters
277 when False. If None, the existing configuration won't change.
278 Global default: True.
279
280 .. versionchanged:: 0.23
281 Global default configuration changed from False to True.
282
283 display : {'text', 'diagram'}, default=None
284 If 'diagram', estimators will be displayed as a diagram in a Jupyter
285 lab or notebook context. If 'text', estimators will be displayed as
286 text. If None, the existing configuration won't change.
287 Global default: 'diagram'.
288
289 .. versionadded:: 0.23
290
291 pairwise_dist_chunk_size : int, default=None
292 The number of row vectors per chunk for the accelerated pairwise-
293 distances reduction backend. Global default: 256 (suitable for most of
294 modern laptops' caches and architectures).
295
296 Intended for easier benchmarking and testing of scikit-learn internals.
297 End users are not expected to benefit from customizing this configuration
298 setting.
299
300 .. versionadded:: 1.1
301
302 enable_cython_pairwise_dist : bool, default=None
303 Use the accelerated pairwise-distances reduction backend when
304 possible. Global default: True.
305
306 Intended for easier benchmarking and testing of scikit-learn internals.
307 End users are not expected to benefit from customizing this configuration
308 setting.
309
310 .. versionadded:: 1.1
311
312 array_api_dispatch : bool, default=None
313 Use Array API dispatching when inputs follow the Array API standard.
314 Global default: False.
315
316 See the :ref:`User Guide <array_api>` for more details.
317
318 .. versionadded:: 1.2
319
320 transform_output : str, default=None
321 Configure output of `transform` and `fit_transform`.
322
323 See :ref:`sphx_glr_auto_examples_miscellaneous_plot_set_output.py`
324 for an example on how to use the API.
325
326 - `"default"`: Default output format of a transformer
327 - `"pandas"`: DataFrame output
328 - `"polars"`: Polars output
329 - `None`: Transform configuration is unchanged
330
331 Global default: "default".
332
333 .. versionadded:: 1.2
334 .. versionadded:: 1.4
335 `"polars"` option was added.
336
337 enable_metadata_routing : bool, default=None
338 Enable metadata routing. By default this feature is disabled.
339
340 Refer to :ref:`metadata routing user guide <metadata_routing>` for more
341 details.
342
343 - `True`: Metadata routing is enabled
344 - `False`: Metadata routing is disabled, use the old syntax.
345 - `None`: Configuration is unchanged
346
347 Global default: False.
348
349 .. versionadded:: 1.3
350
351 skip_parameter_validation : bool, default=None
352 If `True`, disable the validation of the hyper-parameters' types and values in
353 the fit method of estimators and for arguments passed to public helper
354 functions. It can save time in some situations but can lead to low level
355 crashes and exceptions with confusing error messages.
356 Global default: False.
357
358 Note that for data parameters, such as `X` and `y`, only type validation is
359 skipped but validation with `check_array` will continue to run.
360
361 .. versionadded:: 1.3
362
363 Yields
364 ------
365 None.
366
367 See Also
368 --------
369 set_config : Set global scikit-learn configuration.
370 get_config : Retrieve current values of the global configuration.
371
372 Notes
373 -----
374 All settings, not just those presently modified, will be returned to
375 their previous values when the context manager is exited.
376
377 Examples
378 --------
379 >>> import sklearn
380 >>> from sklearn.utils.validation import assert_all_finite
381 >>> with sklearn.config_context(assume_finite=True):
382 ... assert_all_finite([float('nan')])
383 >>> with sklearn.config_context(assume_finite=True):
384 ... with sklearn.config_context(assume_finite=False):
385 ... assert_all_finite([float('nan')])
386 Traceback (most recent call last):
387 ...
388 ValueError: Input contains NaN...
389 """
390 old_config = get_config()
391 set_config(
392 assume_finite=assume_finite,
393 working_memory=working_memory,
394 print_changed_only=print_changed_only,
395 display=display,
396 pairwise_dist_chunk_size=pairwise_dist_chunk_size,
397 enable_cython_pairwise_dist=enable_cython_pairwise_dist,
398 array_api_dispatch=array_api_dispatch,
399 transform_output=transform_output,
400 enable_metadata_routing=enable_metadata_routing,
401 skip_parameter_validation=skip_parameter_validation,
402 )
403
404 try:
405 yield
406 finally:
407 set_config(**old_config)
408 