Boolean thresholding of array-like or scipy.sparse matrix. Read more in the :ref:`User Guide `. Parameters ---------- X : {array-like, sparse matrix} of shape (n_samples, n_features) The data to binarize, element by element. scipy.sparse
(X, *, threshold=0.0, copy=True)
| 2234 | prefer_skip_nested_validation=True, |
| 2235 | ) |
| 2236 | def binarize(X, *, threshold=0.0, copy=True): |
| 2237 | """Boolean thresholding of array-like or scipy.sparse matrix. |
| 2238 | |
| 2239 | Read more in the :ref:`User Guide <preprocessing_binarization>`. |
| 2240 | |
| 2241 | Parameters |
| 2242 | ---------- |
| 2243 | X : {array-like, sparse matrix} of shape (n_samples, n_features) |
| 2244 | The data to binarize, element by element. |
| 2245 | scipy.sparse matrices should be in CSR or CSC format to avoid an |
| 2246 | un-necessary copy. |
| 2247 | |
| 2248 | threshold : float, default=0.0 |
| 2249 | Feature values below or equal to this are replaced by 0, above it by 1. |
| 2250 | Threshold may not be less than 0 for operations on sparse matrices. |
| 2251 | |
| 2252 | copy : bool, default=True |
| 2253 | If False, try to avoid a copy and binarize in place. |
| 2254 | This is not guaranteed to always work in place; e.g. if the data is |
| 2255 | a numpy array with an object dtype, a copy will be returned even with |
| 2256 | copy=False. |
| 2257 | |
| 2258 | Returns |
| 2259 | ------- |
| 2260 | X_tr : {ndarray, sparse matrix} of shape (n_samples, n_features) |
| 2261 | The transformed data. |
| 2262 | |
| 2263 | See Also |
| 2264 | -------- |
| 2265 | Binarizer : Performs binarization using the Transformer API |
| 2266 | (e.g. as part of a preprocessing :class:`~sklearn.pipeline.Pipeline`). |
| 2267 | |
| 2268 | Examples |
| 2269 | -------- |
| 2270 | >>> from sklearn.preprocessing import binarize |
| 2271 | >>> X = [[0.4, 0.6, 0.5], [0.6, 0.1, 0.2]] |
| 2272 | >>> binarize(X, threshold=0.5) |
| 2273 | array([[0., 1., 0.], |
| 2274 | [1., 0., 0.]]) |
| 2275 | """ |
| 2276 | X = check_array(X, accept_sparse=["csr", "csc"], force_writeable=True, copy=copy) |
| 2277 | if sparse.issparse(X): |
| 2278 | if threshold < 0: |
| 2279 | raise ValueError("Cannot binarize a sparse matrix with threshold < 0") |
| 2280 | cond = X.data > threshold |
| 2281 | not_cond = np.logical_not(cond) |
| 2282 | X.data[cond] = 1 |
| 2283 | X.data[not_cond] = 0 |
| 2284 | X.eliminate_zeros() |
| 2285 | else: |
| 2286 | xp, _, device = get_namespace_and_device(X) |
| 2287 | float_dtype = _find_matching_floating_dtype(X, threshold, xp=xp) |
| 2288 | cond = xp.astype(X, float_dtype, copy=False) > threshold |
| 2289 | not_cond = xp.logical_not(cond) |
| 2290 | X[cond] = 1 |
| 2291 | X[not_cond] = 0 |
| 2292 | return X |
| 2293 |
no test coverage detected
searching dependent graphs…