examples (use cases) of sklearn.utils.check_X_y?

Viewed 521

sklearn.utils.check_X_y Checks X and y for consistent length, enforces X to be 2D and y 1D.

To understand this, I wrote this piece of code.

X = np.arange(27).reshape((3,9))
y = np.arange(3)
X, y = check_X_y(X, y)

nothing happened to X or y, I assume this means X, y passed the examine.

and this one

X = np.arange(27).reshape((9,3))
y = np.arange(3)
X, y = check_X_y(X, y)

raise this error

--------------------------------------------------------------------------
ValueError                               Traceback (most recent call last)
<ipython-input-5-b723382efd67> in <module>()
      1 X = np.arange(27).reshape((9,3))
      2 y = np.arange(3)
----> 3 X, y = check_X_y(X, y)

~/anaconda3/envs/tf11/lib/python3.6/site-packages/sklearn/utils/validation.py in check_X_y(X, y, accept_sparse, accept_large_sparse, dtype, order, copy, force_all_finite, ensure_2d, allow_nd, multi_output, ensure_min_samples, ensure_min_features, y_numeric, warn_on_dtype, estimator)
    727         y = y.astype(np.float64)
    728 
--> 729     check_consistent_length(X, y)
    730 
    731     return X, y

~/anaconda3/envs/tf11/lib/python3.6/site-packages/sklearn/utils/validation.py in check_consistent_length(*arrays)
    203     if len(uniques) > 1:
    204         raise ValueError("Found input variables with inconsistent numbers of"
--> 205                          " samples: %r" % [int(l) for l in lengths])
    206 
    207 

ValueError: Found input variables with inconsistent numbers of samples: [9, 3]

Is this check_X_y designed for? enforces X to be 2D by raising error?

1 Answers

In your second example, X satisfies 2D condition but there is a difference in number of samples between X and y i.e. X has 9 samples and y has 3 samples.

Remember, the shape of X is expected to be (n_samples, n_features). Unfortunately this is not mentioned explicitly in the documentation.

Related