MCPcopy Create free account
hub / github.com/scikit-learn/scikit-learn / _encode

Function _encode

sklearn/utils/_encode.py:197–237  ·  view source on GitHub ↗

Helper function to encode values into [0, n_uniques - 1]. Uses pure python method for object dtype, and numpy method for all other dtypes. The numpy method has the limitation that the `uniques` need to be sorted. Importantly, this is not checked but assumed to already be the cas

(values, *, uniques, check_unknown=True)

Source from the content-addressed store, hash-verified

195
196
197def _encode(values, *, uniques, check_unknown=True):
198 """Helper function to encode values into [0, n_uniques - 1].
199
200 Uses pure python method for object dtype, and numpy method for
201 all other dtypes.
202 The numpy method has the limitation that the `uniques` need to
203 be sorted. Importantly, this is not checked but assumed to already be
204 the case. The calling method needs to ensure this for all non-object
205 values.
206
207 Parameters
208 ----------
209 values : ndarray
210 Values to encode.
211 uniques : ndarray
212 The unique values in `values`. If the dtype is not object, then
213 `uniques` needs to be sorted.
214 check_unknown : bool, default=True
215 If True, check for values in `values` that are not in `unique`
216 and raise an error. This is ignored for object dtype, and treated as
217 True in this case. This parameter is useful for
218 _BaseEncoder._transform() to avoid calling _check_unknown()
219 twice.
220
221 Returns
222 -------
223 encoded : ndarray
224 Encoded values
225 """
226 xp, _ = get_namespace(values, uniques)
227 if not xp.isdtype(values.dtype, "numeric"):
228 try:
229 return _map_to_integer(values, uniques)
230 except KeyError as e:
231 raise ValueError(f"y contains previously unseen labels: {e}")
232 else:
233 if check_unknown:
234 diff = _check_unknown(values, uniques)
235 if diff:
236 raise ValueError(f"y contains previously unseen labels: {diff}")
237 return xp.searchsorted(uniques, values)
238
239
240def _check_unknown(values, known_values, return_mask=False):

Callers 8

test_encode_utilFunction · 0.90
transformMethod · 0.90
_transformMethod · 0.90
top_k_accuracy_scoreFunction · 0.90

Calls 3

get_namespaceFunction · 0.90
_map_to_integerFunction · 0.85
_check_unknownFunction · 0.85

Used in the wild real call sites across dependent graphs

searching dependent graphs…