sliceline 0.0.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,858 @@
1
+ """
2
+ Overwritten sklearn validation file to handle string values.
3
+
4
+ Utilities for input validation
5
+ Authors: Olivier Grisel
6
+ Gael Varoquaux
7
+ Andreas Mueller
8
+ Lars Buitinck
9
+ Alexandre Gramfort
10
+ Nicolas Tresegnie
11
+ Sylvain Marie
12
+ License: BSD 3 clause
13
+ """
14
+
15
+ import numbers
16
+ import warnings
17
+ from contextlib import suppress
18
+
19
+ import numpy as np
20
+ import scipy.sparse as sp
21
+
22
+ # mypy error: Module 'numpy.core.numeric' has no attribute 'ComplexWarning'
23
+ from numpy.core.numeric import ComplexWarning # type: ignore
24
+ from sklearn._config import get_config as _get_config
25
+ from sklearn.exceptions import DataConversionWarning
26
+ from sklearn.utils.fixes import _object_dtype_isnan
27
+
28
+
29
+ def _assert_all_finite(
30
+ X, allow_nan=False, msg_dtype=None, estimator_name=None, input_name=""
31
+ ):
32
+ """Like assert_all_finite, but only for ndarray."""
33
+ # validation is also imported in extmath
34
+ from sklearn.utils.extmath import _safe_accumulator_op
35
+
36
+ if _get_config()["assume_finite"]:
37
+ return
38
+ X = np.asanyarray(X)
39
+ # First try an O(n) time, O(1) space solution for the common case that
40
+ # everything is finite; fall back to O(n) space np.isfinite to prevent
41
+ # false positives from overflow in sum method. The sum is also calculated
42
+ # safely to reduce dtype induced overflows.
43
+ is_float = X.dtype.kind in "fc"
44
+ if is_float and (np.isfinite(_safe_accumulator_op(np.sum, X))):
45
+ pass
46
+ elif is_float:
47
+ if (
48
+ allow_nan
49
+ and np.isinf(X).any()
50
+ or not allow_nan
51
+ and not np.isfinite(X).all()
52
+ ):
53
+ if not allow_nan and np.isnan(X).any():
54
+ type_err = "NaN"
55
+ else:
56
+ msg_dtype = msg_dtype if msg_dtype is not None else X.dtype
57
+ type_err = f"infinity or a value too large for {msg_dtype!r}"
58
+ padded_input_name = input_name + " " if input_name else ""
59
+ msg_err = f"Input {padded_input_name}contains {type_err}."
60
+ if (
61
+ not allow_nan
62
+ and estimator_name
63
+ and input_name == "X"
64
+ and np.isnan(X).any()
65
+ ):
66
+ # Improve the error message on how to handle missing values in
67
+ # scikit-learn.
68
+ msg_err += (
69
+ f"\n{estimator_name} does not accept missing values"
70
+ " encoded as NaN natively. For supervised learning, you might want"
71
+ " to consider sklearn.ensemble.HistGradientBoostingClassifier and"
72
+ " Regressor which accept missing values encoded as NaNs natively."
73
+ " Alternatively, it is possible to preprocess the data, for"
74
+ " instance by using an imputer transformer in a pipeline or drop"
75
+ " samples with missing values. See"
76
+ " https://scikit-learn.org/stable/modules/impute.html"
77
+ )
78
+ raise ValueError(msg_err)
79
+
80
+ # for object dtype data, we only check for NaNs (GH-13254)
81
+ elif X.dtype == np.dtype("object") and not allow_nan:
82
+ if _object_dtype_isnan(X).any():
83
+ raise ValueError("Input contains NaN")
84
+
85
+
86
+ def _num_samples(x):
87
+ """Return number of samples in array-like x."""
88
+ message = "Expected sequence or array-like, got %s" % type(x)
89
+ if hasattr(x, "fit") and callable(x.fit):
90
+ # Don't get num_samples from an ensembles length!
91
+ raise TypeError(message)
92
+
93
+ if not hasattr(x, "__len__") and not hasattr(x, "shape"):
94
+ if hasattr(x, "__array__"):
95
+ x = np.asarray(x)
96
+ else:
97
+ raise TypeError(message)
98
+
99
+ if hasattr(x, "shape") and x.shape is not None:
100
+ if len(x.shape) == 0:
101
+ raise TypeError(
102
+ "Singleton array %r cannot be considered a valid collection."
103
+ % x
104
+ )
105
+ # Check that shape is returning an integer or default to len
106
+ # Dask dataframes may not return numeric shape[0] value
107
+ if isinstance(x.shape[0], numbers.Integral):
108
+ return x.shape[0]
109
+
110
+ try:
111
+ return len(x)
112
+ except TypeError as type_error:
113
+ raise TypeError(message) from type_error
114
+
115
+
116
+ def check_consistent_length(*arrays):
117
+ """Check that all arrays have consistent first dimensions.
118
+
119
+ Checks whether all objects in arrays have the same shape or length.
120
+
121
+ Parameters
122
+ ----------
123
+ *arrays : list or tuple of input objects.
124
+ Objects that will be checked for consistent length.
125
+ """
126
+
127
+ lengths = [_num_samples(X) for X in arrays if X is not None]
128
+ uniques = np.unique(lengths)
129
+ if len(uniques) > 1:
130
+ int_lengths = [int(length) for length in lengths]
131
+ raise ValueError(
132
+ f"Found input variables with inconsistent numbers of samples: {int_lengths!r}"
133
+ )
134
+
135
+
136
+ def _ensure_sparse_format(
137
+ spmatrix,
138
+ accept_sparse,
139
+ dtype,
140
+ copy,
141
+ force_all_finite,
142
+ accept_large_sparse,
143
+ estimator_name=None,
144
+ input_name="",
145
+ ):
146
+ """Convert a sparse matrix to a given format.
147
+
148
+ Checks the sparse format of spmatrix and converts if necessary.
149
+
150
+ Parameters
151
+ ----------
152
+ spmatrix : sparse matrix
153
+ Input to validate and convert.
154
+
155
+ accept_sparse : str, bool or list/tuple of str
156
+ String[s] representing allowed sparse matrix formats ('csc',
157
+ 'csr', 'coo', 'dok', 'bsr', 'lil', 'dia'). If the input is sparse but
158
+ not in the allowed format, it will be converted to the first listed
159
+ format. True allows the input to be any format. False means
160
+ that a sparse matrix input will raise an error.
161
+
162
+ dtype : str, type or None
163
+ Data type of result. If None, the dtype of the input is preserved.
164
+
165
+ copy : bool
166
+ Whether a forced copy will be triggered. If copy=False, a copy might
167
+ be triggered by a conversion.
168
+
169
+ force_all_finite : bool or 'allow-nan'
170
+ Whether to raise an error on np.inf, np.nan, pd.NA in X. The
171
+ possibilities are:
172
+
173
+ - True: Force all values of X to be finite.
174
+ - False: accepts np.inf, np.nan, pd.NA in X.
175
+ - 'allow-nan': accepts only np.nan and pd.NA values in X. Values cannot
176
+ be infinite.
177
+
178
+ .. versionadded:: 0.20
179
+ ``force_all_finite`` accepts the string ``'allow-nan'``.
180
+
181
+ .. versionchanged:: 0.23
182
+ Accepts `pd.NA` and converts it into `np.nan`
183
+
184
+
185
+ estimator_name : str, default=None
186
+ The estimator name, used to construct the error message.
187
+
188
+ input_name : str, default=""
189
+ The data name used to construct the error message. In particular
190
+ if `input_name` is "X" and the data has NaN values and
191
+ allow_nan is False, the error message will link to the imputer
192
+ documentation.
193
+
194
+ Returns
195
+ -------
196
+ spmatrix_converted : sparse matrix.
197
+ Matrix that is ensured to have an allowed type.
198
+ """
199
+ if dtype is None:
200
+ dtype = spmatrix.dtype
201
+
202
+ changed_format = False
203
+
204
+ if isinstance(accept_sparse, str):
205
+ accept_sparse = [accept_sparse]
206
+
207
+ # Indices dtype validation
208
+ _check_large_sparse(spmatrix, accept_large_sparse)
209
+
210
+ if accept_sparse is False:
211
+ raise TypeError(
212
+ "A sparse matrix was passed, but dense "
213
+ "data is required. Use X.toarray() to "
214
+ "convert to a dense numpy array."
215
+ )
216
+ if isinstance(accept_sparse, (list, tuple)):
217
+ if len(accept_sparse) == 0:
218
+ raise ValueError(
219
+ "When providing 'accept_sparse' "
220
+ "as a tuple or list, it must contain at "
221
+ "least one string value."
222
+ )
223
+ # ensure correct sparse format
224
+ if spmatrix.format not in accept_sparse:
225
+ # create new with correct sparse
226
+ spmatrix = spmatrix.asformat(accept_sparse[0])
227
+ changed_format = True
228
+ elif accept_sparse is not True:
229
+ # any other type
230
+ raise ValueError(
231
+ "Parameter 'accept_sparse' should be a string, "
232
+ "boolean or list of strings. You provided "
233
+ f"'accept_sparse={accept_sparse}'."
234
+ )
235
+
236
+ if dtype != spmatrix.dtype:
237
+ # convert dtype
238
+ spmatrix = spmatrix.astype(dtype)
239
+ elif copy and not changed_format:
240
+ # force copy
241
+ spmatrix = spmatrix.copy()
242
+
243
+ if force_all_finite:
244
+ if not hasattr(spmatrix, "data"):
245
+ warnings.warn(
246
+ "Can't check %s sparse matrix for nan or inf."
247
+ % spmatrix.format,
248
+ stacklevel=2,
249
+ )
250
+ else:
251
+ _assert_all_finite(
252
+ spmatrix.data,
253
+ allow_nan=force_all_finite == "allow-nan",
254
+ estimator_name=estimator_name,
255
+ input_name=input_name,
256
+ )
257
+
258
+ return spmatrix
259
+
260
+
261
+ def _ensure_no_complex_data(array):
262
+ if (
263
+ hasattr(array, "dtype")
264
+ and array.dtype is not None
265
+ and hasattr(array.dtype, "kind")
266
+ and array.dtype.kind == "c"
267
+ ):
268
+ raise ValueError(f"Complex data not supported\n{array}\n")
269
+
270
+
271
+ def _check_estimator_name(estimator):
272
+ if estimator is not None:
273
+ if isinstance(estimator, str):
274
+ return estimator
275
+ return estimator.__class__.__name__
276
+ return None
277
+
278
+
279
+ def _pandas_dtype_needs_early_conversion(pd_dtype):
280
+ """Return True if pandas extension pd_dtype need to be converted early."""
281
+ # Check these early for pandas versions without extension dtypes
282
+ from pandas.api.types import (
283
+ is_bool_dtype,
284
+ is_float_dtype,
285
+ is_integer_dtype,
286
+ is_sparse,
287
+ )
288
+
289
+ if is_bool_dtype(pd_dtype):
290
+ # bool and extension booleans need early converstion because __array__
291
+ # converts mixed dtype dataframes into object dtypes
292
+ return True
293
+
294
+ if is_sparse(pd_dtype):
295
+ # Sparse arrays will be converted later in `check_array`
296
+ return False
297
+
298
+ try:
299
+ from pandas.api.types import is_extension_array_dtype
300
+ except ImportError:
301
+ return False
302
+
303
+ if is_sparse(pd_dtype) or not is_extension_array_dtype(pd_dtype):
304
+ # Sparse arrays will be converted later in `check_array`
305
+ # Only handle extension arrays for integer and floats
306
+ return False
307
+ elif is_float_dtype(pd_dtype):
308
+ # Float ndarrays can normally support nans. They need to be converted
309
+ # first to map pd.NA to np.nan
310
+ return True
311
+ elif is_integer_dtype(pd_dtype):
312
+ return True
313
+
314
+ return False
315
+
316
+
317
+ def check_array(
318
+ array,
319
+ accept_sparse=False,
320
+ *,
321
+ accept_large_sparse=True,
322
+ dtype="numeric",
323
+ order=None,
324
+ copy=False,
325
+ force_all_finite=True,
326
+ ensure_2d=True,
327
+ allow_nd=False,
328
+ ensure_min_samples=1,
329
+ ensure_min_features=1,
330
+ estimator=None,
331
+ input_name="",
332
+ ):
333
+ """Input validation on an array, list, sparse matrix or similar.
334
+
335
+ By default, the input is checked to be a non-empty 2D array containing
336
+ only finite values. If the dtype of the array is object, attempt
337
+ converting to float, raising on failure.
338
+
339
+ Parameters
340
+ ----------
341
+ array : object
342
+ Input object to check / convert.
343
+
344
+ accept_sparse : str, bool or list/tuple of str, default=False
345
+ String[s] representing allowed sparse matrix formats, such as 'csc',
346
+ 'csr', etc. If the input is sparse but not in the allowed format,
347
+ it will be converted to the first listed format. True allows the input
348
+ to be any format. False means that a sparse matrix input will
349
+ raise an error.
350
+
351
+ accept_large_sparse : bool, default=True
352
+ If a CSR, CSC, COO or BSR sparse matrix is supplied and accepted by
353
+ accept_sparse, accept_large_sparse=False will cause it to be accepted
354
+ only if its indices are stored with a 32-bit dtype.
355
+
356
+ .. versionadded:: 0.20
357
+
358
+ dtype : 'numeric', type, list of type or None, default='numeric'
359
+ Data type of result. If None, the dtype of the input is preserved.
360
+ If "numeric", dtype is preserved unless array.dtype is object.
361
+ If dtype is a list of types, conversion on the first type is only
362
+ performed if the dtype of the input is not in the list.
363
+
364
+ order : {'F', 'C'} or None, default=None
365
+ Whether an array will be forced to be fortran or c-style.
366
+ When order is None (default), then if copy=False, nothing is ensured
367
+ about the memory layout of the output array; otherwise (copy=True)
368
+ the memory layout of the returned array is kept as close as possible
369
+ to the original array.
370
+
371
+ copy : bool, default=False
372
+ Whether a forced copy will be triggered. If copy=False, a copy might
373
+ be triggered by a conversion.
374
+
375
+ force_all_finite : bool or 'allow-nan', default=True
376
+ Whether to raise an error on np.inf, np.nan, pd.NA in array. The
377
+ possibilities are:
378
+
379
+ - True: Force all values of array to be finite.
380
+ - False: accepts np.inf, np.nan, pd.NA in array.
381
+ - 'allow-nan': accepts only np.nan and pd.NA values in array. Values
382
+ cannot be infinite.
383
+
384
+ .. versionadded:: 0.20
385
+ ``force_all_finite`` accepts the string ``'allow-nan'``.
386
+
387
+ .. versionchanged:: 0.23
388
+ Accepts `pd.NA` and converts it into `np.nan`
389
+
390
+ ensure_2d : bool, default=True
391
+ Whether to raise a value error if array is not 2D.
392
+
393
+ allow_nd : bool, default=False
394
+ Whether to allow array.ndim > 2.
395
+
396
+ ensure_min_samples : int, default=1
397
+ Make sure that the array has a minimum number of samples in its first
398
+ axis (rows for a 2D array). Setting to 0 disables this check.
399
+
400
+ ensure_min_features : int, default=1
401
+ Make sure that the 2D array has some minimum number of features
402
+ (columns). The default value of 1 rejects empty datasets.
403
+ This check is only enforced when the input data has effectively 2
404
+ dimensions or is originally 1D and ``ensure_2d`` is True. Setting to 0
405
+ disables this check.
406
+
407
+ estimator : str or estimator instance, default=None
408
+ If passed, include the name of the estimator in warning messages.
409
+
410
+ input_name : str, default=""
411
+ The data name used to construct the error message. In particular
412
+ if `input_name` is "X" and the data has NaN values and
413
+ allow_nan is False, the error message will link to the imputer
414
+ documentation.
415
+
416
+ .. versionadded:: 1.1.0
417
+
418
+ Returns
419
+ -------
420
+ array_converted : object
421
+ The converted and validated array.
422
+ """
423
+ if isinstance(array, np.matrix):
424
+ warnings.warn(
425
+ "np.matrix usage is deprecated in 1.0 and will raise a TypeError "
426
+ "in 1.2. Please convert to a numpy array with np.asarray. For "
427
+ "more information see: "
428
+ "https://numpy.org/doc/stable/reference/generated/numpy.matrix.html", # noqa
429
+ FutureWarning,
430
+ )
431
+
432
+ # store reference to original array to check if copy is needed when
433
+ # function returns
434
+ array_orig = array
435
+
436
+ # store whether originally we wanted numeric dtype
437
+ dtype_numeric = isinstance(dtype, str) and dtype == "numeric"
438
+
439
+ dtype_orig = getattr(array, "dtype", None)
440
+ if not hasattr(dtype_orig, "kind"):
441
+ # not a data type (e.g. a column named dtype in a pandas DataFrame)
442
+ dtype_orig = None
443
+
444
+ # check if the object contains several dtypes (typically a pandas
445
+ # DataFrame), and store them. If not, store None.
446
+ dtypes_orig = None
447
+ pandas_requires_conversion = False
448
+ if hasattr(array, "dtypes") and hasattr(array.dtypes, "__array__"):
449
+ # throw warning if columns are sparse. If all columns are sparse, then
450
+ # array.sparse exists and sparsity will be preserved (later).
451
+ with suppress(ImportError):
452
+ from pandas.api.types import is_sparse
453
+
454
+ if (
455
+ not hasattr(array, "sparse")
456
+ and array.dtypes.apply(is_sparse).any()
457
+ ):
458
+ warnings.warn(
459
+ "pandas.DataFrame with sparse columns found."
460
+ "It will be converted to a dense numpy array."
461
+ )
462
+
463
+ dtypes_orig = list(array.dtypes)
464
+ pandas_requires_conversion = any(
465
+ _pandas_dtype_needs_early_conversion(i) for i in dtypes_orig
466
+ )
467
+ if all(isinstance(dtype_iter, np.dtype) for dtype_iter in dtypes_orig):
468
+ dtype_orig = np.result_type(*dtypes_orig)
469
+
470
+ if dtype_numeric:
471
+ if dtype_orig is not None and dtype_orig.kind == "O":
472
+ # if input is object, convert to float.
473
+ dtype = np.float64
474
+ else:
475
+ dtype = None
476
+
477
+ if isinstance(dtype, (list, tuple)):
478
+ if dtype_orig is not None and dtype_orig in dtype:
479
+ # no dtype conversion required
480
+ dtype = None
481
+ else:
482
+ # dtype conversion required. Let's select the first element of the
483
+ # list of accepted types.
484
+ dtype = dtype[0]
485
+
486
+ if pandas_requires_conversion:
487
+ # pandas dataframe requires conversion earlier to handle extension dtypes with
488
+ # nans
489
+ # Use the original dtype for conversion if dtype is None
490
+ new_dtype = dtype_orig if dtype is None else dtype
491
+ array = array.astype(new_dtype)
492
+ # Since we converted here, we do not need to convert again later
493
+ dtype = None
494
+
495
+ if force_all_finite not in (True, False, "allow-nan"):
496
+ raise ValueError(
497
+ f'force_all_finite should be a bool or "allow-nan". Got {force_all_finite!r} instead'
498
+ )
499
+
500
+ estimator_name = _check_estimator_name(estimator)
501
+ context = " by %s" % estimator_name if estimator is not None else ""
502
+
503
+ # When all dataframe columns are sparse, convert to a sparse array
504
+ if hasattr(array, "sparse") and array.ndim > 1:
505
+ # DataFrame.sparse only supports `to_coo`
506
+ array = array.sparse.to_coo()
507
+ if array.dtype == np.dtype("object"):
508
+ unique_dtypes = set([dt.subtype.name for dt in array_orig.dtypes])
509
+ if len(unique_dtypes) > 1:
510
+ raise ValueError(
511
+ "Pandas DataFrame with mixed sparse extension arrays "
512
+ "generated a sparse matrix with object dtype which "
513
+ "can not be converted to a scipy sparse matrix."
514
+ "Sparse extension arrays should all have the same "
515
+ "numeric type."
516
+ )
517
+
518
+ if sp.issparse(array):
519
+ _ensure_no_complex_data(array)
520
+ array = _ensure_sparse_format(
521
+ array,
522
+ accept_sparse=accept_sparse,
523
+ dtype=dtype,
524
+ copy=copy,
525
+ force_all_finite=force_all_finite,
526
+ accept_large_sparse=accept_large_sparse,
527
+ estimator_name=estimator_name,
528
+ input_name=input_name,
529
+ )
530
+ else:
531
+ # If np.array(..) gives ComplexWarning, then we convert the warning
532
+ # to an error. This is needed because specifying a non complex
533
+ # dtype to the function converts complex to real dtype,
534
+ # thereby passing the test made in the lines following the scope
535
+ # of warnings context manager.
536
+ with warnings.catch_warnings():
537
+ try:
538
+ warnings.simplefilter("error", ComplexWarning)
539
+ if dtype is not None and np.dtype(dtype).kind in "iu":
540
+ # Conversion float -> int should not contain NaN or
541
+ # inf (numpy#14412). We cannot use casting='safe' because
542
+ # then conversion float -> int would be disallowed.
543
+ array = np.asarray(array, order=order)
544
+ if array.dtype.kind == "f":
545
+ _assert_all_finite(
546
+ array,
547
+ allow_nan=False,
548
+ msg_dtype=dtype,
549
+ estimator_name=estimator_name,
550
+ input_name=input_name,
551
+ )
552
+ array = array.astype(dtype, casting="unsafe", copy=False)
553
+ else:
554
+ # Overwritten line to accept string input
555
+ array = np.asarray(array, order=order)
556
+ except ComplexWarning as complex_warning:
557
+ raise ValueError(
558
+ f"Complex data not supported\n{array}\n"
559
+ ) from complex_warning
560
+
561
+ # It is possible that the np.array(..) gave no warning. This happens
562
+ # when no dtype conversion happened, for example dtype = None. The
563
+ # result is that np.array(..) produces an array of complex dtype
564
+ # and we need to catch and raise exception for such cases.
565
+ _ensure_no_complex_data(array)
566
+
567
+ if ensure_2d:
568
+ # If input is scalar raise error
569
+ if array.ndim == 0:
570
+ raise ValueError(
571
+ f"Expected 2D array, got scalar array instead:\narray={array}.\n"
572
+ "Reshape your data either using array.reshape(-1, 1) if "
573
+ "your data has a single feature or array.reshape(1, -1) "
574
+ "if it contains a single sample."
575
+ )
576
+ # If input is 1D raise error
577
+ if array.ndim == 1:
578
+ raise ValueError(
579
+ f"Expected 2D array, got 1D array instead:\narray={array}.\n"
580
+ "Reshape your data either using array.reshape(-1, 1) if "
581
+ "your data has a single feature or array.reshape(1, -1) "
582
+ "if it contains a single sample."
583
+ )
584
+
585
+ if dtype_numeric and array.dtype.kind in "USV":
586
+ raise ValueError(
587
+ "dtype='numeric' is not compatible with arrays of bytes/strings."
588
+ "Convert your data to numeric values explicitly instead."
589
+ )
590
+
591
+ if not allow_nd and array.ndim >= 3:
592
+ raise ValueError(
593
+ f"Found array with dim {array.ndim}. {estimator_name} expected <= 2."
594
+ )
595
+
596
+ if force_all_finite:
597
+ _assert_all_finite(
598
+ array,
599
+ input_name=input_name,
600
+ estimator_name=estimator_name,
601
+ allow_nan=force_all_finite == "allow-nan",
602
+ )
603
+
604
+ if ensure_min_samples > 0:
605
+ n_samples = _num_samples(array)
606
+ if n_samples < ensure_min_samples:
607
+ raise ValueError(
608
+ "Found array with %d sample(s) (shape=%s) while a"
609
+ " minimum of %d is required%s."
610
+ % (n_samples, array.shape, ensure_min_samples, context)
611
+ )
612
+
613
+ if ensure_min_features > 0 and array.ndim == 2:
614
+ n_features = array.shape[1]
615
+ if n_features < ensure_min_features:
616
+ raise ValueError(
617
+ "Found array with %d feature(s) (shape=%s) while"
618
+ " a minimum of %d is required%s."
619
+ % (n_features, array.shape, ensure_min_features, context)
620
+ )
621
+
622
+ if copy and np.may_share_memory(array, array_orig):
623
+ array = np.array(array, dtype=dtype, order=order)
624
+
625
+ return array
626
+
627
+
628
+ def _check_large_sparse(X, accept_large_sparse=False):
629
+ """Raise a ValueError if X has 64bit indices and accept_large_sparse=False"""
630
+ if not accept_large_sparse:
631
+ supported_indices = ["int32"]
632
+ if X.getformat() == "coo":
633
+ index_keys = ["col", "row"]
634
+ elif X.getformat() in ["csr", "csc", "bsr"]:
635
+ index_keys = ["indices", "indptr"]
636
+ else:
637
+ return
638
+ for key in index_keys:
639
+ indices_datatype = getattr(X, key).dtype
640
+ if indices_datatype not in supported_indices:
641
+ raise ValueError(
642
+ "Only sparse matrices with 32-bit integer"
643
+ " indices are accepted. Got %s indices." % indices_datatype
644
+ )
645
+
646
+
647
+ def check_X_e(
648
+ X,
649
+ y,
650
+ accept_sparse=False,
651
+ *,
652
+ accept_large_sparse=True,
653
+ dtype="numeric",
654
+ order=None,
655
+ copy=False,
656
+ force_all_finite=True,
657
+ ensure_2d=True,
658
+ allow_nd=False,
659
+ multi_output=False,
660
+ ensure_min_samples=1,
661
+ ensure_min_features=1,
662
+ y_numeric=False,
663
+ estimator=None,
664
+ ):
665
+ """Input validation for standard estimators.
666
+
667
+ Checks X and y for consistent length, enforces X to be 2D and y 1D. By
668
+ default, X is checked to be non-empty and containing only finite values.
669
+ Standard input checks are also applied to y, such as checking that y
670
+ does not have np.nan or np.inf targets. For multi-label y, set
671
+ multi_output=True to allow 2D and sparse y. If the dtype of X is
672
+ object, attempt converting to float, raising on failure.
673
+
674
+ Parameters
675
+ ----------
676
+ X : {ndarray, list, sparse matrix}
677
+ Input data.
678
+
679
+ y : {ndarray, list, sparse matrix}
680
+ Labels.
681
+
682
+ accept_sparse : str, bool or list of str, default=False
683
+ String[s] representing allowed sparse matrix formats, such as 'csc',
684
+ 'csr', etc. If the input is sparse but not in the allowed format,
685
+ it will be converted to the first listed format. True allows the input
686
+ to be any format. False means that a sparse matrix input will
687
+ raise an error.
688
+
689
+ accept_large_sparse : bool, default=True
690
+ If a CSR, CSC, COO or BSR sparse matrix is supplied and accepted by
691
+ accept_sparse, accept_large_sparse will cause it to be accepted only
692
+ if its indices are stored with a 32-bit dtype.
693
+
694
+ .. versionadded:: 0.20
695
+
696
+ dtype : 'numeric', type, list of type or None, default='numeric'
697
+ Data type of result. If None, the dtype of the input is preserved.
698
+ If "numeric", dtype is preserved unless array.dtype is object.
699
+ If dtype is a list of types, conversion on the first type is only
700
+ performed if the dtype of the input is not in the list.
701
+
702
+ order : {'F', 'C'}, default=None
703
+ Whether an array will be forced to be fortran or c-style.
704
+
705
+ copy : bool, default=False
706
+ Whether a forced copy will be triggered. If copy=False, a copy might
707
+ be triggered by a conversion.
708
+
709
+ force_all_finite : bool or 'allow-nan', default=True
710
+ Whether to raise an error on np.inf, np.nan, pd.NA in X. This parameter
711
+ does not influence whether y can have np.inf, np.nan, pd.NA values.
712
+ The possibilities are:
713
+
714
+ - True: Force all values of X to be finite.
715
+ - False: accepts np.inf, np.nan, pd.NA in X.
716
+ - 'allow-nan': accepts only np.nan or pd.NA values in X. Values cannot
717
+ be infinite.
718
+
719
+ .. versionadded:: 0.20
720
+ ``force_all_finite`` accepts the string ``'allow-nan'``.
721
+
722
+ .. versionchanged:: 0.23
723
+ Accepts `pd.NA` and converts it into `np.nan`
724
+
725
+ ensure_2d : bool, default=True
726
+ Whether to raise a value error if X is not 2D.
727
+
728
+ allow_nd : bool, default=False
729
+ Whether to allow X.ndim > 2.
730
+
731
+ multi_output : bool, default=False
732
+ Whether to allow 2D y (array or sparse matrix). If false, y will be
733
+ validated as a vector. y cannot have np.nan or np.inf values if
734
+ multi_output=True.
735
+
736
+ ensure_min_samples : int, default=1
737
+ Make sure that X has a minimum number of samples in its first
738
+ axis (rows for a 2D array).
739
+
740
+ ensure_min_features : int, default=1
741
+ Make sure that the 2D array has some minimum number of features
742
+ (columns). The default value of 1 rejects empty datasets.
743
+ This check is only enforced when X has effectively 2 dimensions or
744
+ is originally 1D and ``ensure_2d`` is True. Setting to 0 disables
745
+ this check.
746
+
747
+ y_numeric : bool, default=False
748
+ Whether to ensure that y has a numeric type. If dtype of y is object,
749
+ it is converted to float64. Should only be used for regression
750
+ algorithms.
751
+
752
+ estimator : str or estimator instance, default=None
753
+ If passed, include the name of the estimator in warning messages.
754
+
755
+ Returns
756
+ -------
757
+ X_converted : object
758
+ The converted and validated X.
759
+
760
+ y_converted : object
761
+ The converted and validated y.
762
+ """
763
+ if y is None:
764
+ if estimator is None:
765
+ estimator_name = "estimator"
766
+ else:
767
+ estimator_name = _check_estimator_name(estimator)
768
+ raise ValueError(
769
+ f"{estimator_name} requires y to be passed, but the target y is None"
770
+ )
771
+
772
+ X = check_array(
773
+ X,
774
+ accept_sparse=accept_sparse,
775
+ accept_large_sparse=accept_large_sparse,
776
+ dtype=dtype,
777
+ order=order,
778
+ copy=copy,
779
+ force_all_finite=force_all_finite,
780
+ ensure_2d=ensure_2d,
781
+ allow_nd=allow_nd,
782
+ ensure_min_samples=ensure_min_samples,
783
+ ensure_min_features=ensure_min_features,
784
+ estimator=estimator,
785
+ input_name="X",
786
+ )
787
+
788
+ y = _check_y(
789
+ y, multi_output=multi_output, y_numeric=y_numeric, estimator=estimator
790
+ )
791
+
792
+ check_consistent_length(X, y)
793
+
794
+ return X, y
795
+
796
+
797
+ def _check_y(y, multi_output=False, y_numeric=False, estimator=None):
798
+ """Isolated part of check_X_e dedicated to y validation"""
799
+ if multi_output:
800
+ y = check_array(
801
+ y,
802
+ accept_sparse="csr",
803
+ force_all_finite=True,
804
+ ensure_2d=False,
805
+ dtype=None,
806
+ input_name="y",
807
+ estimator=estimator,
808
+ )
809
+ else:
810
+ estimator_name = _check_estimator_name(estimator)
811
+ y = column_or_1d(y, warn=True)
812
+ _assert_all_finite(y, input_name="y", estimator_name=estimator_name)
813
+ _ensure_no_complex_data(y)
814
+ if y_numeric and y.dtype.kind in ("O", "b"):
815
+ y = y.astype(np.float32)
816
+
817
+ return y
818
+
819
+
820
+ def column_or_1d(y, *, warn=False):
821
+ """Ravel column or 1d numpy array, else raises an error.
822
+
823
+ Parameters
824
+ ----------
825
+ y : array-like
826
+ Input data.
827
+
828
+ warn : bool, default=False
829
+ To control display of warnings.
830
+
831
+ Returns
832
+ -------
833
+ y : ndarray
834
+ Output data.
835
+
836
+ Raises
837
+ ------
838
+ ValueError
839
+ If `y` is not a 1D array or a 2D array with a single row or column.
840
+ """
841
+ y = np.asarray(y)
842
+ shape = np.shape(y)
843
+ if len(shape) == 1:
844
+ return np.ravel(y)
845
+ if len(shape) == 2 and shape[1] == 1:
846
+ if warn:
847
+ warnings.warn(
848
+ "A column-vector y was passed when a 1d array was"
849
+ " expected. Please change the shape of y to "
850
+ "(n_samples, ), for example using ravel().",
851
+ DataConversionWarning,
852
+ stacklevel=2,
853
+ )
854
+ return np.ravel(y)
855
+
856
+ raise ValueError(
857
+ f"y should be a 1d array, got an array of shape {shape} instead."
858
+ )