code stringlengths 66 870k | docstring stringlengths 19 26.7k | func_name stringlengths 1 138 | language stringclasses 1
value | repo stringlengths 7 68 | path stringlengths 5 324 | url stringlengths 46 389 | license stringclasses 7
values |
|---|---|---|---|---|---|---|---|
def lazy_xp_function( # type: ignore[explicit-any]
func: Callable[..., Any],
*,
allow_dask_compute: int = 0,
jax_jit: bool = True,
static_argnums: int | Sequence[int] | None = None,
static_argnames: str | Iterable[str] | None = None,
) -> None: # numpydoc ignore=GL07
"""
Tag a function... |
Tag a function to be tested on lazy backends.
Tag a function so that when any tests are executed with ``xp=jax.numpy`` the
function is replaced with a jitted version of itself, and when it is executed with
``xp=dask.array`` the function will raise if it attempts to materialize the graph.
This will... | lazy_xp_function | python | scikit-learn/scikit-learn | sklearn/externals/array_api_extra/testing.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/externals/array_api_extra/testing.py | BSD-3-Clause |
def patch_lazy_xp_functions(
request: pytest.FixtureRequest, monkeypatch: pytest.MonkeyPatch, *, xp: ModuleType
) -> None:
"""
Test lazy execution of functions tagged with :func:`lazy_xp_function`.
If ``xp==jax.numpy``, search for all functions which have been tagged with
:func:`lazy_xp_function` i... |
Test lazy execution of functions tagged with :func:`lazy_xp_function`.
If ``xp==jax.numpy``, search for all functions which have been tagged with
:func:`lazy_xp_function` in the globals of the module that defines the current test,
as well as in the ``lazy_xp_modules`` list in the globals of the same m... | patch_lazy_xp_functions | python | scikit-learn/scikit-learn | sklearn/externals/array_api_extra/testing.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/externals/array_api_extra/testing.py | BSD-3-Clause |
def _dask_wrap(
func: Callable[P, T], n: int
) -> Callable[P, T]: # numpydoc ignore=PR01,RT01
"""
Wrap `func` to raise if it attempts to call `dask.compute` more than `n` times.
After the function returns, materialize the graph in order to re-raise exceptions.
"""
import dask
func_name = ... |
Wrap `func` to raise if it attempts to call `dask.compute` more than `n` times.
After the function returns, materialize the graph in order to re-raise exceptions.
| _dask_wrap | python | scikit-learn/scikit-learn | sklearn/externals/array_api_extra/testing.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/externals/array_api_extra/testing.py | BSD-3-Clause |
def isclose(
a: Array | complex,
b: Array | complex,
*,
rtol: float = 1e-05,
atol: float = 1e-08,
equal_nan: bool = False,
xp: ModuleType | None = None,
) -> Array:
"""
Return a boolean array where two arrays are element-wise equal within a tolerance.
The tolerance values are po... |
Return a boolean array where two arrays are element-wise equal within a tolerance.
The tolerance values are positive, typically very small numbers. The relative
difference ``(rtol * abs(b))`` and the absolute difference `atol` are added together
to compare against the absolute difference between `a` a... | isclose | python | scikit-learn/scikit-learn | sklearn/externals/array_api_extra/_delegation.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/externals/array_api_extra/_delegation.py | BSD-3-Clause |
def pad(
x: Array,
pad_width: int | tuple[int, int] | Sequence[tuple[int, int]],
mode: Literal["constant"] = "constant",
*,
constant_values: complex = 0,
xp: ModuleType | None = None,
) -> Array:
"""
Pad the input array.
Parameters
----------
x : array
Input array.
... |
Pad the input array.
Parameters
----------
x : array
Input array.
pad_width : int or tuple of ints or sequence of pairs of ints
Pad the input array with this many elements from each side.
If a sequence of tuples, ``[(before_0, after_0), ... (before_N, after_N)]``,
e... | pad | python | scikit-learn/scikit-learn | sklearn/externals/array_api_extra/_delegation.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/externals/array_api_extra/_delegation.py | BSD-3-Clause |
def __getitem__(self, idx: SetIndex, /) -> Self: # numpydoc ignore=PR01,RT01
"""
Allow for the alternate syntax ``at(x)[start:stop:step]``.
It looks prettier than ``at(x, slice(start, stop, step))``
and feels more intuitive coming from the JAX documentation.
"""
if self... |
Allow for the alternate syntax ``at(x)[start:stop:step]``.
It looks prettier than ``at(x, slice(start, stop, step))``
and feels more intuitive coming from the JAX documentation.
| __getitem__ | python | scikit-learn/scikit-learn | sklearn/externals/array_api_extra/_lib/_at.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/externals/array_api_extra/_lib/_at.py | BSD-3-Clause |
def _op(
self,
at_op: _AtOp,
in_place_op: Callable[[Array, Array | complex], Array] | None,
out_of_place_op: Callable[[Array, Array], Array] | None,
y: Array | complex,
/,
copy: bool | None,
xp: ModuleType | None,
) -> Array:
"""
Implem... |
Implement all update operations.
Parameters
----------
at_op : _AtOp
Method of JAX's Array.at[].
in_place_op : Callable[[Array, Array | complex], Array] | None
In-place operation to apply on mutable backends::
x[idx] = in_place_op(x[idx]... | _op | python | scikit-learn/scikit-learn | sklearn/externals/array_api_extra/_lib/_at.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/externals/array_api_extra/_lib/_at.py | BSD-3-Clause |
def set(
self,
y: Array | complex,
/,
copy: bool | None = None,
xp: ModuleType | None = None,
) -> Array: # numpydoc ignore=PR01,RT01
"""Apply ``x[idx] = y`` and return the update array."""
return self._op(_AtOp.SET, None, None, y, copy=copy, xp=xp) | Apply ``x[idx] = y`` and return the update array. | set | python | scikit-learn/scikit-learn | sklearn/externals/array_api_extra/_lib/_at.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/externals/array_api_extra/_lib/_at.py | BSD-3-Clause |
def add(
self,
y: Array | complex,
/,
copy: bool | None = None,
xp: ModuleType | None = None,
) -> Array: # numpydoc ignore=PR01,RT01
"""Apply ``x[idx] += y`` and return the updated array."""
# Note for this and all other methods based on _iop:
# ope... | Apply ``x[idx] += y`` and return the updated array. | add | python | scikit-learn/scikit-learn | sklearn/externals/array_api_extra/_lib/_at.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/externals/array_api_extra/_lib/_at.py | BSD-3-Clause |
def subtract(
self,
y: Array | complex,
/,
copy: bool | None = None,
xp: ModuleType | None = None,
) -> Array: # numpydoc ignore=PR01,RT01
"""Apply ``x[idx] -= y`` and return the updated array."""
return self._op(
_AtOp.SUBTRACT, operator.isub, op... | Apply ``x[idx] -= y`` and return the updated array. | subtract | python | scikit-learn/scikit-learn | sklearn/externals/array_api_extra/_lib/_at.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/externals/array_api_extra/_lib/_at.py | BSD-3-Clause |
def multiply(
self,
y: Array | complex,
/,
copy: bool | None = None,
xp: ModuleType | None = None,
) -> Array: # numpydoc ignore=PR01,RT01
"""Apply ``x[idx] *= y`` and return the updated array."""
return self._op(
_AtOp.MULTIPLY, operator.imul, op... | Apply ``x[idx] *= y`` and return the updated array. | multiply | python | scikit-learn/scikit-learn | sklearn/externals/array_api_extra/_lib/_at.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/externals/array_api_extra/_lib/_at.py | BSD-3-Clause |
def divide(
self,
y: Array | complex,
/,
copy: bool | None = None,
xp: ModuleType | None = None,
) -> Array: # numpydoc ignore=PR01,RT01
"""Apply ``x[idx] /= y`` and return the updated array."""
return self._op(
_AtOp.DIVIDE, operator.itruediv, op... | Apply ``x[idx] /= y`` and return the updated array. | divide | python | scikit-learn/scikit-learn | sklearn/externals/array_api_extra/_lib/_at.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/externals/array_api_extra/_lib/_at.py | BSD-3-Clause |
def power(
self,
y: Array | complex,
/,
copy: bool | None = None,
xp: ModuleType | None = None,
) -> Array: # numpydoc ignore=PR01,RT01
"""Apply ``x[idx] **= y`` and return the updated array."""
return self._op(_AtOp.POWER, operator.ipow, operator.pow, y, cop... | Apply ``x[idx] **= y`` and return the updated array. | power | python | scikit-learn/scikit-learn | sklearn/externals/array_api_extra/_lib/_at.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/externals/array_api_extra/_lib/_at.py | BSD-3-Clause |
def min(
self,
y: Array | complex,
/,
copy: bool | None = None,
xp: ModuleType | None = None,
) -> Array: # numpydoc ignore=PR01,RT01
"""Apply ``x[idx] = minimum(x[idx], y)`` and return the updated array."""
# On Dask, this function runs on the chunks, so we ... | Apply ``x[idx] = minimum(x[idx], y)`` and return the updated array. | min | python | scikit-learn/scikit-learn | sklearn/externals/array_api_extra/_lib/_at.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/externals/array_api_extra/_lib/_at.py | BSD-3-Clause |
def max(
self,
y: Array | complex,
/,
copy: bool | None = None,
xp: ModuleType | None = None,
) -> Array: # numpydoc ignore=PR01,RT01
"""Apply ``x[idx] = maximum(x[idx], y)`` and return the updated array."""
# See note on min()
xp = array_namespace(se... | Apply ``x[idx] = maximum(x[idx], y)`` and return the updated array. | max | python | scikit-learn/scikit-learn | sklearn/externals/array_api_extra/_lib/_at.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/externals/array_api_extra/_lib/_at.py | BSD-3-Clause |
def apply_where( # type: ignore[explicit-any] # numpydoc ignore=PR01,PR02
cond: Array,
args: Array | tuple[Array, ...],
f1: Callable[..., Array],
f2: Callable[..., Array] | None = None,
/,
*,
fill_value: Array | complex | None = None,
xp: ModuleType | None = None,
) -> Array:
"""
... |
Run one of two elementwise functions depending on a condition.
Equivalent to ``f1(*args) if cond else fill_value`` performed elementwise
when `fill_value` is defined, otherwise to ``f1(*args) if cond else f2(*args)``.
Parameters
----------
cond : array
The condition, expressed as a bo... | apply_where | python | scikit-learn/scikit-learn | sklearn/externals/array_api_extra/_lib/_funcs.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/externals/array_api_extra/_lib/_funcs.py | BSD-3-Clause |
def _apply_where( # type: ignore[explicit-any] # numpydoc ignore=PR01,RT01
cond: Array,
f1: Callable[..., Array],
f2: Callable[..., Array] | None,
fill_value: Array | int | float | complex | bool | None,
*args: Array,
xp: ModuleType,
) -> Array:
"""Helper of `apply_where`. On Dask, this ru... | Helper of `apply_where`. On Dask, this runs on a single chunk. | _apply_where | python | scikit-learn/scikit-learn | sklearn/externals/array_api_extra/_lib/_funcs.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/externals/array_api_extra/_lib/_funcs.py | BSD-3-Clause |
def atleast_nd(x: Array, /, *, ndim: int, xp: ModuleType | None = None) -> Array:
"""
Recursively expand the dimension of an array to at least `ndim`.
Parameters
----------
x : array
Input array.
ndim : int
The minimum number of dimensions for the result.
xp : array_namespac... |
Recursively expand the dimension of an array to at least `ndim`.
Parameters
----------
x : array
Input array.
ndim : int
The minimum number of dimensions for the result.
xp : array_namespace, optional
The standard-compatible namespace for `x`. Default: infer.
Retur... | atleast_nd | python | scikit-learn/scikit-learn | sklearn/externals/array_api_extra/_lib/_funcs.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/externals/array_api_extra/_lib/_funcs.py | BSD-3-Clause |
def broadcast_shapes(*shapes: tuple[float | None, ...]) -> tuple[int | None, ...]:
"""
Compute the shape of the broadcasted arrays.
Duplicates :func:`numpy.broadcast_shapes`, with additional support for
None and NaN sizes.
This is equivalent to ``xp.broadcast_arrays(arr1, arr2, ...)[0].shape``
... |
Compute the shape of the broadcasted arrays.
Duplicates :func:`numpy.broadcast_shapes`, with additional support for
None and NaN sizes.
This is equivalent to ``xp.broadcast_arrays(arr1, arr2, ...)[0].shape``
without needing to worry about the backend potentially deep copying
the arrays.
... | broadcast_shapes | python | scikit-learn/scikit-learn | sklearn/externals/array_api_extra/_lib/_funcs.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/externals/array_api_extra/_lib/_funcs.py | BSD-3-Clause |
def cov(m: Array, /, *, xp: ModuleType | None = None) -> Array:
"""
Estimate a covariance matrix.
Covariance indicates the level to which two variables vary together.
If we examine N-dimensional samples, :math:`X = [x_1, x_2, ... x_N]^T`,
then the covariance matrix element :math:`C_{ij}` is the cov... |
Estimate a covariance matrix.
Covariance indicates the level to which two variables vary together.
If we examine N-dimensional samples, :math:`X = [x_1, x_2, ... x_N]^T`,
then the covariance matrix element :math:`C_{ij}` is the covariance of
:math:`x_i` and :math:`x_j`. The element :math:`C_{ii}` ... | cov | python | scikit-learn/scikit-learn | sklearn/externals/array_api_extra/_lib/_funcs.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/externals/array_api_extra/_lib/_funcs.py | BSD-3-Clause |
def create_diagonal(
x: Array, /, *, offset: int = 0, xp: ModuleType | None = None
) -> Array:
"""
Construct a diagonal array.
Parameters
----------
x : array
An array having shape ``(*batch_dims, k)``.
offset : int, optional
Offset from the leading diagonal (default is ``0`... |
Construct a diagonal array.
Parameters
----------
x : array
An array having shape ``(*batch_dims, k)``.
offset : int, optional
Offset from the leading diagonal (default is ``0``).
Use positive ints for diagonals above the leading diagonal,
and negative ints for diag... | create_diagonal | python | scikit-learn/scikit-learn | sklearn/externals/array_api_extra/_lib/_funcs.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/externals/array_api_extra/_lib/_funcs.py | BSD-3-Clause |
def expand_dims(
a: Array, /, *, axis: int | tuple[int, ...] = (0,), xp: ModuleType | None = None
) -> Array:
"""
Expand the shape of an array.
Insert (a) new axis/axes that will appear at the position(s) specified by
`axis` in the expanded array shape.
This is ``xp.expand_dims`` for `axis` an... |
Expand the shape of an array.
Insert (a) new axis/axes that will appear at the position(s) specified by
`axis` in the expanded array shape.
This is ``xp.expand_dims`` for `axis` an int *or a tuple of ints*.
Roughly equivalent to ``numpy.expand_dims`` for NumPy arrays.
Parameters
--------... | expand_dims | python | scikit-learn/scikit-learn | sklearn/externals/array_api_extra/_lib/_funcs.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/externals/array_api_extra/_lib/_funcs.py | BSD-3-Clause |
def kron(
a: Array | complex,
b: Array | complex,
/,
*,
xp: ModuleType | None = None,
) -> Array:
"""
Kronecker product of two arrays.
Computes the Kronecker product, a composite array made of blocks of the
second array scaled by the first.
Equivalent to ``numpy.kron`` for NumP... |
Kronecker product of two arrays.
Computes the Kronecker product, a composite array made of blocks of the
second array scaled by the first.
Equivalent to ``numpy.kron`` for NumPy arrays.
Parameters
----------
a, b : Array | int | float | complex
Input arrays or scalars. At least o... | kron | python | scikit-learn/scikit-learn | sklearn/externals/array_api_extra/_lib/_funcs.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/externals/array_api_extra/_lib/_funcs.py | BSD-3-Clause |
def nunique(x: Array, /, *, xp: ModuleType | None = None) -> Array:
"""
Count the number of unique elements in an array.
Compatible with JAX and Dask, whose laziness would be otherwise
problematic.
Parameters
----------
x : Array
Input array.
xp : array_namespace, optional
... |
Count the number of unique elements in an array.
Compatible with JAX and Dask, whose laziness would be otherwise
problematic.
Parameters
----------
x : Array
Input array.
xp : array_namespace, optional
The standard-compatible namespace for `x`. Default: infer.
Returns... | nunique | python | scikit-learn/scikit-learn | sklearn/externals/array_api_extra/_lib/_funcs.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/externals/array_api_extra/_lib/_funcs.py | BSD-3-Clause |
def setdiff1d(
x1: Array | complex,
x2: Array | complex,
/,
*,
assume_unique: bool = False,
xp: ModuleType | None = None,
) -> Array:
"""
Find the set difference of two arrays.
Return the unique values in `x1` that are not in `x2`.
Parameters
----------
x1 : array | int... |
Find the set difference of two arrays.
Return the unique values in `x1` that are not in `x2`.
Parameters
----------
x1 : array | int | float | complex | bool
Input array.
x2 : array
Input comparison array.
assume_unique : bool
If ``True``, the input arrays are both... | setdiff1d | python | scikit-learn/scikit-learn | sklearn/externals/array_api_extra/_lib/_funcs.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/externals/array_api_extra/_lib/_funcs.py | BSD-3-Clause |
def _is_jax_jit_enabled(xp: ModuleType) -> bool: # numpydoc ignore=PR01,RT01
"""Return True if this function is being called inside ``jax.jit``."""
import jax # pylint: disable=import-outside-toplevel
x = xp.asarray(False)
try:
return bool(x)
except jax.errors.TracerBoolConversionError:
... | Return True if this function is being called inside ``jax.jit``. | _is_jax_jit_enabled | python | scikit-learn/scikit-learn | sklearn/externals/array_api_extra/_lib/_lazy.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/externals/array_api_extra/_lib/_lazy.py | BSD-3-Clause |
def _lazy_apply_wrapper( # type: ignore[explicit-any] # numpydoc ignore=PR01,RT01
func: Callable[..., Array | ArrayLike | Sequence[Array | ArrayLike]],
as_numpy: bool,
multi_output: bool,
xp: ModuleType,
) -> Callable[..., tuple[Array, ...]]:
"""
Helper of `lazy_apply`.
Given a function t... |
Helper of `lazy_apply`.
Given a function that accepts one or more arrays as positional arguments and returns
a single array-like or a sequence of array-likes, return a function that accepts the
same number of Array API arrays and always returns a tuple of Array API array.
Any keyword arguments ar... | _lazy_apply_wrapper | python | scikit-learn/scikit-learn | sklearn/externals/array_api_extra/_lib/_lazy.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/externals/array_api_extra/_lib/_lazy.py | BSD-3-Clause |
def _check_ns_shape_dtype(
actual: Array, desired: Array
) -> ModuleType: # numpydoc ignore=RT03
"""
Assert that namespace, shape and dtype of the two arrays match.
Parameters
----------
actual : Array
The array produced by the tested function.
desired : Array
The expected ... |
Assert that namespace, shape and dtype of the two arrays match.
Parameters
----------
actual : Array
The array produced by the tested function.
desired : Array
The expected array (typically hardcoded).
Returns
-------
Arrays namespace.
| _check_ns_shape_dtype | python | scikit-learn/scikit-learn | sklearn/externals/array_api_extra/_lib/_testing.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/externals/array_api_extra/_lib/_testing.py | BSD-3-Clause |
def xp_assert_equal(actual: Array, desired: Array, err_msg: str = "") -> None:
"""
Array-API compatible version of `np.testing.assert_array_equal`.
Parameters
----------
actual : Array
The array produced by the tested function.
desired : Array
The expected array (typically hardc... |
Array-API compatible version of `np.testing.assert_array_equal`.
Parameters
----------
actual : Array
The array produced by the tested function.
desired : Array
The expected array (typically hardcoded).
err_msg : str, optional
Error message to display on failure.
S... | xp_assert_equal | python | scikit-learn/scikit-learn | sklearn/externals/array_api_extra/_lib/_testing.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/externals/array_api_extra/_lib/_testing.py | BSD-3-Clause |
def xp_assert_close(
actual: Array,
desired: Array,
*,
rtol: float | None = None,
atol: float = 0,
err_msg: str = "",
) -> None:
"""
Array-API compatible version of `np.testing.assert_allclose`.
Parameters
----------
actual : Array
The array produced by the tested fu... |
Array-API compatible version of `np.testing.assert_allclose`.
Parameters
----------
actual : Array
The array produced by the tested function.
desired : Array
The expected array (typically hardcoded).
rtol : float, optional
Relative tolerance. Default: dtype-dependent.
... | xp_assert_close | python | scikit-learn/scikit-learn | sklearn/externals/array_api_extra/_lib/_testing.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/externals/array_api_extra/_lib/_testing.py | BSD-3-Clause |
def in1d(
x1: Array,
x2: Array,
/,
*,
assume_unique: bool = False,
invert: bool = False,
xp: ModuleType | None = None,
) -> Array: # numpydoc ignore=PR01,RT01
"""
Check whether each element of an array is also present in a second array.
Returns a boolean array the same length a... |
Check whether each element of an array is also present in a second array.
Returns a boolean array the same length as `x1` that is True
where an element of `x1` is in `x2` and False otherwise.
This function has been adapted using the original implementation
present in numpy:
https://github.com... | in1d | python | scikit-learn/scikit-learn | sklearn/externals/array_api_extra/_lib/_utils/_helpers.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/externals/array_api_extra/_lib/_utils/_helpers.py | BSD-3-Clause |
def mean(
x: Array,
/,
*,
axis: int | tuple[int, ...] | None = None,
keepdims: bool = False,
xp: ModuleType | None = None,
) -> Array: # numpydoc ignore=PR01,RT01
"""
Complex mean, https://github.com/data-apis/array-api/issues/846.
"""
if xp is None:
xp = array_namespace... |
Complex mean, https://github.com/data-apis/array-api/issues/846.
| mean | python | scikit-learn/scikit-learn | sklearn/externals/array_api_extra/_lib/_utils/_helpers.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/externals/array_api_extra/_lib/_utils/_helpers.py | BSD-3-Clause |
def is_python_scalar(x: object) -> TypeIs[complex]: # numpydoc ignore=PR01,RT01
"""Return True if `x` is a Python scalar, False otherwise."""
# isinstance(x, float) returns True for np.float64
# isinstance(x, complex) returns True for np.complex128
# bool is a subclass of int
return isinstance(x, i... | Return True if `x` is a Python scalar, False otherwise. | is_python_scalar | python | scikit-learn/scikit-learn | sklearn/externals/array_api_extra/_lib/_utils/_helpers.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/externals/array_api_extra/_lib/_utils/_helpers.py | BSD-3-Clause |
def asarrays(
a: Array | complex,
b: Array | complex,
xp: ModuleType,
) -> tuple[Array, Array]:
"""
Ensure both `a` and `b` are arrays.
If `b` is a python scalar, it is converted to the same dtype as `a`, and vice versa.
Behavior is not specified when mixing a Python ``float`` and an array... |
Ensure both `a` and `b` are arrays.
If `b` is a python scalar, it is converted to the same dtype as `a`, and vice versa.
Behavior is not specified when mixing a Python ``float`` and an array with an
integer data type; this may give ``float32``, ``float64``, or raise an exception.
Behavior is impl... | asarrays | python | scikit-learn/scikit-learn | sklearn/externals/array_api_extra/_lib/_utils/_helpers.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/externals/array_api_extra/_lib/_utils/_helpers.py | BSD-3-Clause |
def ndindex(*x: int) -> Generator[tuple[int, ...]]:
"""
Generate all N-dimensional indices for a given array shape.
Given the shape of an array, an ndindex instance iterates over the N-dimensional
index of the array. At each iteration a tuple of indices is returned, the last
dimension is iterated o... |
Generate all N-dimensional indices for a given array shape.
Given the shape of an array, an ndindex instance iterates over the N-dimensional
index of the array. At each iteration a tuple of indices is returned, the last
dimension is iterated over first.
This has an identical API to numpy.ndindex.... | ndindex | python | scikit-learn/scikit-learn | sklearn/externals/array_api_extra/_lib/_utils/_helpers.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/externals/array_api_extra/_lib/_utils/_helpers.py | BSD-3-Clause |
def eager_shape(x: Array, /) -> tuple[int, ...]:
"""
Return shape of an array. Raise if shape is not fully defined.
Parameters
----------
x : Array
Input array.
Returns
-------
tuple[int, ...]
Shape of the array.
"""
shape = x.shape
# Dask arrays uses non-st... |
Return shape of an array. Raise if shape is not fully defined.
Parameters
----------
x : Array
Input array.
Returns
-------
tuple[int, ...]
Shape of the array.
| eager_shape | python | scikit-learn/scikit-learn | sklearn/externals/array_api_extra/_lib/_utils/_helpers.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/externals/array_api_extra/_lib/_utils/_helpers.py | BSD-3-Clause |
def meta_namespace(
*arrays: Array | complex | None, xp: ModuleType | None = None
) -> ModuleType:
"""
Get the namespace of Dask chunks.
On all other backends, just return the namespace of the arrays.
Parameters
----------
*arrays : Array | int | float | complex | bool | None
Input... |
Get the namespace of Dask chunks.
On all other backends, just return the namespace of the arrays.
Parameters
----------
*arrays : Array | int | float | complex | bool | None
Input arrays.
xp : array_namespace, optional
The standard-compatible namespace for the input arrays. De... | meta_namespace | python | scikit-learn/scikit-learn | sklearn/externals/array_api_extra/_lib/_utils/_helpers.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/externals/array_api_extra/_lib/_utils/_helpers.py | BSD-3-Clause |
def parse(version: str) -> Union["LegacyVersion", "Version"]:
"""Parse the given version from a string to an appropriate class.
Parameters
----------
version : str
Version in a string format, eg. "0.9.1" or "1.2.dev0".
Returns
-------
version : :class:`Version` object or a :class:`... | Parse the given version from a string to an appropriate class.
Parameters
----------
version : str
Version in a string format, eg. "0.9.1" or "1.2.dev0".
Returns
-------
version : :class:`Version` object or a :class:`LegacyVersion` object
Returned class depends on the given ver... | parse | python | scikit-learn/scikit-learn | sklearn/externals/_packaging/version.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/externals/_packaging/version.py | BSD-3-Clause |
def _parse_local_version(local: str) -> Optional[LocalType]:
"""
Takes a string like abc.1.twelve and turns it into ("abc", 1, "twelve").
"""
if local is not None:
return tuple(
part.lower() if not part.isdigit() else int(part)
for part in _local_version_separators.split(... |
Takes a string like abc.1.twelve and turns it into ("abc", 1, "twelve").
| _parse_local_version | python | scikit-learn/scikit-learn | sklearn/externals/_packaging/version.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/externals/_packaging/version.py | BSD-3-Clause |
def _make_edges_3d(n_x, n_y, n_z=1):
"""Returns a list of edges for a 3D image.
Parameters
----------
n_x : int
The size of the grid in the x direction.
n_y : int
The size of the grid in the y direction.
n_z : integer, default=1
The size of the grid in the z direction, d... | Returns a list of edges for a 3D image.
Parameters
----------
n_x : int
The size of the grid in the x direction.
n_y : int
The size of the grid in the y direction.
n_z : integer, default=1
The size of the grid in the z direction, defaults to 1
| _make_edges_3d | python | scikit-learn/scikit-learn | sklearn/feature_extraction/image.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/feature_extraction/image.py | BSD-3-Clause |
def _mask_edges_weights(mask, edges, weights=None):
"""Apply a mask to edges (weighted or not)"""
inds = np.arange(mask.size)
inds = inds[mask.ravel()]
ind_mask = np.logical_and(np.isin(edges[0], inds), np.isin(edges[1], inds))
edges = edges[:, ind_mask]
if weights is not None:
weights =... | Apply a mask to edges (weighted or not) | _mask_edges_weights | python | scikit-learn/scikit-learn | sklearn/feature_extraction/image.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/feature_extraction/image.py | BSD-3-Clause |
def img_to_graph(img, *, mask=None, return_as=sparse.coo_matrix, dtype=None):
"""Graph of the pixel-to-pixel gradient connections.
Edges are weighted with the gradient values.
Read more in the :ref:`User Guide <image_feature_extraction>`.
Parameters
----------
img : array-like of shape (heigh... | Graph of the pixel-to-pixel gradient connections.
Edges are weighted with the gradient values.
Read more in the :ref:`User Guide <image_feature_extraction>`.
Parameters
----------
img : array-like of shape (height, width) or (height, width, channel)
2D or 3D image.
mask : ndarray of s... | img_to_graph | python | scikit-learn/scikit-learn | sklearn/feature_extraction/image.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/feature_extraction/image.py | BSD-3-Clause |
def grid_to_graph(
n_x, n_y, n_z=1, *, mask=None, return_as=sparse.coo_matrix, dtype=int
):
"""Graph of the pixel-to-pixel connections.
Edges exist if 2 voxels are connected.
Read more in the :ref:`User Guide <connectivity_graph_image>`.
Parameters
----------
n_x : int
Dimension i... | Graph of the pixel-to-pixel connections.
Edges exist if 2 voxels are connected.
Read more in the :ref:`User Guide <connectivity_graph_image>`.
Parameters
----------
n_x : int
Dimension in x axis.
n_y : int
Dimension in y axis.
n_z : int, default=1
Dimension in z ax... | grid_to_graph | python | scikit-learn/scikit-learn | sklearn/feature_extraction/image.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/feature_extraction/image.py | BSD-3-Clause |
def _compute_n_patches(i_h, i_w, p_h, p_w, max_patches=None):
"""Compute the number of patches that will be extracted in an image.
Read more in the :ref:`User Guide <image_feature_extraction>`.
Parameters
----------
i_h : int
The image height
i_w : int
The image with
p_h : ... | Compute the number of patches that will be extracted in an image.
Read more in the :ref:`User Guide <image_feature_extraction>`.
Parameters
----------
i_h : int
The image height
i_w : int
The image with
p_h : int
The height of a patch
p_w : int
The width of ... | _compute_n_patches | python | scikit-learn/scikit-learn | sklearn/feature_extraction/image.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/feature_extraction/image.py | BSD-3-Clause |
def _extract_patches(arr, patch_shape=8, extraction_step=1):
"""Extracts patches of any n-dimensional array in place using strides.
Given an n-dimensional array it will return a 2n-dimensional array with
the first n dimensions indexing patch position and the last n indexing
the patch content. This oper... | Extracts patches of any n-dimensional array in place using strides.
Given an n-dimensional array it will return a 2n-dimensional array with
the first n dimensions indexing patch position and the last n indexing
the patch content. This operation is immediate (O(1)). A reshape
performed on the first n di... | _extract_patches | python | scikit-learn/scikit-learn | sklearn/feature_extraction/image.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/feature_extraction/image.py | BSD-3-Clause |
def extract_patches_2d(image, patch_size, *, max_patches=None, random_state=None):
"""Reshape a 2D image into a collection of patches.
The resulting patches are allocated in a dedicated array.
Read more in the :ref:`User Guide <image_feature_extraction>`.
Parameters
----------
image : ndarray... | Reshape a 2D image into a collection of patches.
The resulting patches are allocated in a dedicated array.
Read more in the :ref:`User Guide <image_feature_extraction>`.
Parameters
----------
image : ndarray of shape (image_height, image_width) or (image_height, image_width, n_channels)
... | extract_patches_2d | python | scikit-learn/scikit-learn | sklearn/feature_extraction/image.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/feature_extraction/image.py | BSD-3-Clause |
def reconstruct_from_patches_2d(patches, image_size):
"""Reconstruct the image from all of its patches.
Patches are assumed to overlap and the image is constructed by filling in
the patches from left to right, top to bottom, averaging the overlapping
regions.
Read more in the :ref:`User Guide <ima... | Reconstruct the image from all of its patches.
Patches are assumed to overlap and the image is constructed by filling in
the patches from left to right, top to bottom, averaging the overlapping
regions.
Read more in the :ref:`User Guide <image_feature_extraction>`.
Parameters
----------
p... | reconstruct_from_patches_2d | python | scikit-learn/scikit-learn | sklearn/feature_extraction/image.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/feature_extraction/image.py | BSD-3-Clause |
def transform(self, X):
"""Transform the image samples in `X` into a matrix of patch data.
Parameters
----------
X : ndarray of shape (n_samples, image_height, image_width) or \
(n_samples, image_height, image_width, n_channels)
Array of images from which to ... | Transform the image samples in `X` into a matrix of patch data.
Parameters
----------
X : ndarray of shape (n_samples, image_height, image_width) or (n_samples, image_height, image_width, n_channels)
Array of images from which to extract patches. For color images,
... | transform | python | scikit-learn/scikit-learn | sklearn/feature_extraction/image.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/feature_extraction/image.py | BSD-3-Clause |
def _preprocess(doc, accent_function=None, lower=False):
"""Chain together an optional series of text preprocessing steps to
apply to a document.
Parameters
----------
doc: str
The string to preprocess
accent_function: callable, default=None
Function for handling accented charac... | Chain together an optional series of text preprocessing steps to
apply to a document.
Parameters
----------
doc: str
The string to preprocess
accent_function: callable, default=None
Function for handling accented characters. Common strategies include
normalizing and removing... | _preprocess | python | scikit-learn/scikit-learn | sklearn/feature_extraction/text.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/feature_extraction/text.py | BSD-3-Clause |
def _analyze(
doc,
analyzer=None,
tokenizer=None,
ngrams=None,
preprocessor=None,
decoder=None,
stop_words=None,
):
"""Chain together an optional series of text processing steps to go from
a single document to ngrams, with or without tokenizing or preprocessing.
If analyzer is u... | Chain together an optional series of text processing steps to go from
a single document to ngrams, with or without tokenizing or preprocessing.
If analyzer is used, only the decoder argument is used, as the analyzer is
intended to replace the preprocessor, tokenizer, and ngrams steps.
Parameters
-... | _analyze | python | scikit-learn/scikit-learn | sklearn/feature_extraction/text.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/feature_extraction/text.py | BSD-3-Clause |
def strip_accents_unicode(s):
"""Transform accentuated unicode symbols into their simple counterpart.
Warning: the python-level loop and join operations make this
implementation 20 times slower than the strip_accents_ascii basic
normalization.
Parameters
----------
s : str
The stri... | Transform accentuated unicode symbols into their simple counterpart.
Warning: the python-level loop and join operations make this
implementation 20 times slower than the strip_accents_ascii basic
normalization.
Parameters
----------
s : str
The string to strip.
Returns
-------... | strip_accents_unicode | python | scikit-learn/scikit-learn | sklearn/feature_extraction/text.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/feature_extraction/text.py | BSD-3-Clause |
def strip_accents_ascii(s):
"""Transform accentuated unicode symbols into ascii or nothing.
Warning: this solution is only suited for languages that have a direct
transliteration to ASCII symbols.
Parameters
----------
s : str
The string to strip.
Returns
-------
s : str
... | Transform accentuated unicode symbols into ascii or nothing.
Warning: this solution is only suited for languages that have a direct
transliteration to ASCII symbols.
Parameters
----------
s : str
The string to strip.
Returns
-------
s : str
The stripped string.
Se... | strip_accents_ascii | python | scikit-learn/scikit-learn | sklearn/feature_extraction/text.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/feature_extraction/text.py | BSD-3-Clause |
def decode(self, doc):
"""Decode the input into a string of unicode symbols.
The decoding strategy depends on the vectorizer parameters.
Parameters
----------
doc : bytes or str
The string to decode.
Returns
-------
doc: str
A st... | Decode the input into a string of unicode symbols.
The decoding strategy depends on the vectorizer parameters.
Parameters
----------
doc : bytes or str
The string to decode.
Returns
-------
doc: str
A string of unicode symbols.
| decode | python | scikit-learn/scikit-learn | sklearn/feature_extraction/text.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/feature_extraction/text.py | BSD-3-Clause |
def _word_ngrams(self, tokens, stop_words=None):
"""Turn tokens into a sequence of n-grams after stop words filtering"""
# handle stop words
if stop_words is not None:
tokens = [w for w in tokens if w not in stop_words]
# handle token n-grams
min_n, max_n = self.ngra... | Turn tokens into a sequence of n-grams after stop words filtering | _word_ngrams | python | scikit-learn/scikit-learn | sklearn/feature_extraction/text.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/feature_extraction/text.py | BSD-3-Clause |
def _char_ngrams(self, text_document):
"""Tokenize text_document into a sequence of character n-grams"""
# normalize white spaces
text_document = self._white_spaces.sub(" ", text_document)
text_len = len(text_document)
min_n, max_n = self.ngram_range
if min_n == 1:
... | Tokenize text_document into a sequence of character n-grams | _char_ngrams | python | scikit-learn/scikit-learn | sklearn/feature_extraction/text.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/feature_extraction/text.py | BSD-3-Clause |
def _char_wb_ngrams(self, text_document):
"""Whitespace sensitive char-n-gram tokenization.
Tokenize text_document into a sequence of character n-grams
operating only inside word boundaries. n-grams at the edges
of words are padded with space."""
# normalize white spaces
... | Whitespace sensitive char-n-gram tokenization.
Tokenize text_document into a sequence of character n-grams
operating only inside word boundaries. n-grams at the edges
of words are padded with space. | _char_wb_ngrams | python | scikit-learn/scikit-learn | sklearn/feature_extraction/text.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/feature_extraction/text.py | BSD-3-Clause |
def build_preprocessor(self):
"""Return a function to preprocess the text before tokenization.
Returns
-------
preprocessor: callable
A function to preprocess the text before tokenization.
"""
if self.preprocessor is not None:
return self.prepro... | Return a function to preprocess the text before tokenization.
Returns
-------
preprocessor: callable
A function to preprocess the text before tokenization.
| build_preprocessor | python | scikit-learn/scikit-learn | sklearn/feature_extraction/text.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/feature_extraction/text.py | BSD-3-Clause |
def build_tokenizer(self):
"""Return a function that splits a string into a sequence of tokens.
Returns
-------
tokenizer: callable
A function to split a string into a sequence of tokens.
"""
if self.tokenizer is not None:
return self.tokenizer
... | Return a function that splits a string into a sequence of tokens.
Returns
-------
tokenizer: callable
A function to split a string into a sequence of tokens.
| build_tokenizer | python | scikit-learn/scikit-learn | sklearn/feature_extraction/text.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/feature_extraction/text.py | BSD-3-Clause |
def _check_stop_words_consistency(self, stop_words, preprocess, tokenize):
"""Check if stop words are consistent
Returns
-------
is_consistent : True if stop words are consistent with the preprocessor
and tokenizer, False if they are not, None if the check
... | Check if stop words are consistent
Returns
-------
is_consistent : True if stop words are consistent with the preprocessor
and tokenizer, False if they are not, None if the check
was previously performed, "error" if it could not be
... | _check_stop_words_consistency | python | scikit-learn/scikit-learn | sklearn/feature_extraction/text.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/feature_extraction/text.py | BSD-3-Clause |
def build_analyzer(self):
"""Return a callable to process input data.
The callable handles preprocessing, tokenization, and n-grams generation.
Returns
-------
analyzer: callable
A function to handle preprocessing, tokenization
and n-grams generation.
... | Return a callable to process input data.
The callable handles preprocessing, tokenization, and n-grams generation.
Returns
-------
analyzer: callable
A function to handle preprocessing, tokenization
and n-grams generation.
| build_analyzer | python | scikit-learn/scikit-learn | sklearn/feature_extraction/text.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/feature_extraction/text.py | BSD-3-Clause |
def _check_vocabulary(self):
"""Check if vocabulary is empty or missing (not fitted)"""
if not hasattr(self, "vocabulary_"):
self._validate_vocabulary()
if not self.fixed_vocabulary_:
raise NotFittedError("Vocabulary not fitted or provided")
if len(self.v... | Check if vocabulary is empty or missing (not fitted) | _check_vocabulary | python | scikit-learn/scikit-learn | sklearn/feature_extraction/text.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/feature_extraction/text.py | BSD-3-Clause |
def fit(self, X, y=None):
"""Only validates estimator's parameters.
This method allows to: (i) validate the estimator's parameters and
(ii) be consistent with the scikit-learn transformer API.
Parameters
----------
X : ndarray of shape [n_samples, n_features]
... | Only validates estimator's parameters.
This method allows to: (i) validate the estimator's parameters and
(ii) be consistent with the scikit-learn transformer API.
Parameters
----------
X : ndarray of shape [n_samples, n_features]
Training data.
y : Ignored... | fit | python | scikit-learn/scikit-learn | sklearn/feature_extraction/text.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/feature_extraction/text.py | BSD-3-Clause |
def transform(self, X):
"""Transform a sequence of documents to a document-term matrix.
Parameters
----------
X : iterable over raw text documents, length = n_samples
Samples. Each sample must be a text document (either bytes or
unicode strings, file name or file... | Transform a sequence of documents to a document-term matrix.
Parameters
----------
X : iterable over raw text documents, length = n_samples
Samples. Each sample must be a text document (either bytes or
unicode strings, file name or file object depending on the
... | transform | python | scikit-learn/scikit-learn | sklearn/feature_extraction/text.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/feature_extraction/text.py | BSD-3-Clause |
def _document_frequency(X):
"""Count the number of non-zero values for each feature in sparse X."""
if sp.issparse(X) and X.format == "csr":
return np.bincount(X.indices, minlength=X.shape[1])
else:
return np.diff(X.indptr) | Count the number of non-zero values for each feature in sparse X. | _document_frequency | python | scikit-learn/scikit-learn | sklearn/feature_extraction/text.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/feature_extraction/text.py | BSD-3-Clause |
def _sort_features(self, X, vocabulary):
"""Sort features by name
Returns a reordered matrix and modifies the vocabulary in place
"""
sorted_features = sorted(vocabulary.items())
map_index = np.empty(len(sorted_features), dtype=X.indices.dtype)
for new_val, (term, old_va... | Sort features by name
Returns a reordered matrix and modifies the vocabulary in place
| _sort_features | python | scikit-learn/scikit-learn | sklearn/feature_extraction/text.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/feature_extraction/text.py | BSD-3-Clause |
def _count_vocab(self, raw_documents, fixed_vocab):
"""Create sparse feature matrix, and vocabulary where fixed_vocab=False"""
if fixed_vocab:
vocabulary = self.vocabulary_
else:
# Add a new value when a new vocabulary item is seen
vocabulary = defaultdict()
... | Create sparse feature matrix, and vocabulary where fixed_vocab=False | _count_vocab | python | scikit-learn/scikit-learn | sklearn/feature_extraction/text.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/feature_extraction/text.py | BSD-3-Clause |
def fit_transform(self, raw_documents, y=None):
"""Learn the vocabulary dictionary and return document-term matrix.
This is equivalent to fit followed by transform, but more efficiently
implemented.
Parameters
----------
raw_documents : iterable
An iterable ... | Learn the vocabulary dictionary and return document-term matrix.
This is equivalent to fit followed by transform, but more efficiently
implemented.
Parameters
----------
raw_documents : iterable
An iterable which generates either str, unicode or file objects.
... | fit_transform | python | scikit-learn/scikit-learn | sklearn/feature_extraction/text.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/feature_extraction/text.py | BSD-3-Clause |
def transform(self, raw_documents):
"""Transform documents to document-term matrix.
Extract token counts out of raw text documents using the vocabulary
fitted with fit or the one provided to the constructor.
Parameters
----------
raw_documents : iterable
An ... | Transform documents to document-term matrix.
Extract token counts out of raw text documents using the vocabulary
fitted with fit or the one provided to the constructor.
Parameters
----------
raw_documents : iterable
An iterable which generates either str, unicode or... | transform | python | scikit-learn/scikit-learn | sklearn/feature_extraction/text.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/feature_extraction/text.py | BSD-3-Clause |
def inverse_transform(self, X):
"""Return terms per document with nonzero entries in X.
Parameters
----------
X : {array-like, sparse matrix} of shape (n_samples, n_features)
Document-term matrix.
Returns
-------
X_original : list of arrays of shape ... | Return terms per document with nonzero entries in X.
Parameters
----------
X : {array-like, sparse matrix} of shape (n_samples, n_features)
Document-term matrix.
Returns
-------
X_original : list of arrays of shape (n_samples,)
List of arrays of ... | inverse_transform | python | scikit-learn/scikit-learn | sklearn/feature_extraction/text.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/feature_extraction/text.py | BSD-3-Clause |
def fit(self, X, y=None):
"""Learn the idf vector (global term weights).
Parameters
----------
X : sparse matrix of shape (n_samples, n_features)
A matrix of term/token counts.
y : None
This parameter is not needed to compute tf-idf.
Returns
... | Learn the idf vector (global term weights).
Parameters
----------
X : sparse matrix of shape (n_samples, n_features)
A matrix of term/token counts.
y : None
This parameter is not needed to compute tf-idf.
Returns
-------
self : object
... | fit | python | scikit-learn/scikit-learn | sklearn/feature_extraction/text.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/feature_extraction/text.py | BSD-3-Clause |
def transform(self, X, copy=True):
"""Transform a count matrix to a tf or tf-idf representation.
Parameters
----------
X : sparse matrix of (n_samples, n_features)
A matrix of term/token counts.
copy : bool, default=True
Whether to copy X and operate on ... | Transform a count matrix to a tf or tf-idf representation.
Parameters
----------
X : sparse matrix of (n_samples, n_features)
A matrix of term/token counts.
copy : bool, default=True
Whether to copy X and operate on the copy or perform in-place
opera... | transform | python | scikit-learn/scikit-learn | sklearn/feature_extraction/text.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/feature_extraction/text.py | BSD-3-Clause |
def idf_(self):
"""Inverse document frequency vector, only defined if `use_idf=True`.
Returns
-------
ndarray of shape (n_features,)
"""
if not hasattr(self, "_tfidf"):
raise NotFittedError(
f"{self.__class__.__name__} is not fitted yet. Call ... | Inverse document frequency vector, only defined if `use_idf=True`.
Returns
-------
ndarray of shape (n_features,)
| idf_ | python | scikit-learn/scikit-learn | sklearn/feature_extraction/text.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/feature_extraction/text.py | BSD-3-Clause |
def fit(self, raw_documents, y=None):
"""Learn vocabulary and idf from training set.
Parameters
----------
raw_documents : iterable
An iterable which generates either str, unicode or file objects.
y : None
This parameter is not needed to compute tfidf.
... | Learn vocabulary and idf from training set.
Parameters
----------
raw_documents : iterable
An iterable which generates either str, unicode or file objects.
y : None
This parameter is not needed to compute tfidf.
Returns
-------
self : ob... | fit | python | scikit-learn/scikit-learn | sklearn/feature_extraction/text.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/feature_extraction/text.py | BSD-3-Clause |
def fit_transform(self, raw_documents, y=None):
"""Learn vocabulary and idf, return document-term matrix.
This is equivalent to fit followed by transform, but more efficiently
implemented.
Parameters
----------
raw_documents : iterable
An iterable which gene... | Learn vocabulary and idf, return document-term matrix.
This is equivalent to fit followed by transform, but more efficiently
implemented.
Parameters
----------
raw_documents : iterable
An iterable which generates either str, unicode or file objects.
y : Non... | fit_transform | python | scikit-learn/scikit-learn | sklearn/feature_extraction/text.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/feature_extraction/text.py | BSD-3-Clause |
def transform(self, raw_documents):
"""Transform documents to document-term matrix.
Uses the vocabulary and document frequencies (df) learned by fit (or
fit_transform).
Parameters
----------
raw_documents : iterable
An iterable which generates either str, un... | Transform documents to document-term matrix.
Uses the vocabulary and document frequencies (df) learned by fit (or
fit_transform).
Parameters
----------
raw_documents : iterable
An iterable which generates either str, unicode or file objects.
Returns
... | transform | python | scikit-learn/scikit-learn | sklearn/feature_extraction/text.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/feature_extraction/text.py | BSD-3-Clause |
def _add_iterable_element(
self,
f,
v,
feature_names,
vocab,
*,
fitting=True,
transforming=False,
indices=None,
values=None,
):
"""Add feature names for iterable of strings"""
for vv in v:
if isinstance(vv, s... | Add feature names for iterable of strings | _add_iterable_element | python | scikit-learn/scikit-learn | sklearn/feature_extraction/_dict_vectorizer.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/feature_extraction/_dict_vectorizer.py | BSD-3-Clause |
def fit(self, X, y=None):
"""Learn a list of feature name -> indices mappings.
Parameters
----------
X : Mapping or iterable over Mappings
Dict(s) or Mapping(s) from feature names (arbitrary Python
objects) to feature values (strings or convertible to dtype).
... | Learn a list of feature name -> indices mappings.
Parameters
----------
X : Mapping or iterable over Mappings
Dict(s) or Mapping(s) from feature names (arbitrary Python
objects) to feature values (strings or convertible to dtype).
.. versionchanged:: 0.24
... | fit | python | scikit-learn/scikit-learn | sklearn/feature_extraction/_dict_vectorizer.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/feature_extraction/_dict_vectorizer.py | BSD-3-Clause |
def inverse_transform(self, X, dict_type=dict):
"""Transform array or sparse matrix X back to feature mappings.
X must have been produced by this DictVectorizer's transform or
fit_transform method; it may only have passed through transformers
that preserve the number of features and the... | Transform array or sparse matrix X back to feature mappings.
X must have been produced by this DictVectorizer's transform or
fit_transform method; it may only have passed through transformers
that preserve the number of features and their order.
In the case of one-hot/one-of-K coding, ... | inverse_transform | python | scikit-learn/scikit-learn | sklearn/feature_extraction/_dict_vectorizer.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/feature_extraction/_dict_vectorizer.py | BSD-3-Clause |
def transform(self, X):
"""Transform feature->value dicts to array or sparse matrix.
Named features not encountered during fit or fit_transform will be
silently ignored.
Parameters
----------
X : Mapping or iterable over Mappings of shape (n_samples,)
Dict(s... | Transform feature->value dicts to array or sparse matrix.
Named features not encountered during fit or fit_transform will be
silently ignored.
Parameters
----------
X : Mapping or iterable over Mappings of shape (n_samples,)
Dict(s) or Mapping(s) from feature names ... | transform | python | scikit-learn/scikit-learn | sklearn/feature_extraction/_dict_vectorizer.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/feature_extraction/_dict_vectorizer.py | BSD-3-Clause |
def restrict(self, support, indices=False):
"""Restrict the features to those in support using feature selection.
This function modifies the estimator in-place.
Parameters
----------
support : array-like
Boolean mask or list of indices (as returned by the get_suppor... | Restrict the features to those in support using feature selection.
This function modifies the estimator in-place.
Parameters
----------
support : array-like
Boolean mask or list of indices (as returned by the get_support
member of feature selectors).
ind... | restrict | python | scikit-learn/scikit-learn | sklearn/feature_extraction/_dict_vectorizer.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/feature_extraction/_dict_vectorizer.py | BSD-3-Clause |
def transform(self, raw_X):
"""Transform a sequence of instances to a scipy.sparse matrix.
Parameters
----------
raw_X : iterable over iterable over raw features, length = n_samples
Samples. Each sample must be iterable an (e.g., a list or tuple)
containing/gener... | Transform a sequence of instances to a scipy.sparse matrix.
Parameters
----------
raw_X : iterable over iterable over raw features, length = n_samples
Samples. Each sample must be iterable an (e.g., a list or tuple)
containing/generating feature names (and optionally val... | transform | python | scikit-learn/scikit-learn | sklearn/feature_extraction/_hash.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/feature_extraction/_hash.py | BSD-3-Clause |
def test_dictvectorizer_dense_sparse_equivalence():
"""Check the equivalence between between sparse and dense DictVectorizer.
Non-regression test for:
https://github.com/scikit-learn/scikit-learn/issues/19978
"""
movie_entry_fit = [
{"category": ["thriller", "drama"], "year": 2003},
... | Check the equivalence between between sparse and dense DictVectorizer.
Non-regression test for:
https://github.com/scikit-learn/scikit-learn/issues/19978
| test_dictvectorizer_dense_sparse_equivalence | python | scikit-learn/scikit-learn | sklearn/feature_extraction/tests/test_dict_vectorizer.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/feature_extraction/tests/test_dict_vectorizer.py | BSD-3-Clause |
def test_dict_vectorizer_unsupported_value_type():
"""Check that we raise an error when the value associated to a feature
is not supported.
Non-regression test for:
https://github.com/scikit-learn/scikit-learn/issues/19489
"""
class A:
pass
vectorizer = DictVectorizer(sparse=True)... | Check that we raise an error when the value associated to a feature
is not supported.
Non-regression test for:
https://github.com/scikit-learn/scikit-learn/issues/19489
| test_dict_vectorizer_unsupported_value_type | python | scikit-learn/scikit-learn | sklearn/feature_extraction/tests/test_dict_vectorizer.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/feature_extraction/tests/test_dict_vectorizer.py | BSD-3-Clause |
def test_dict_vectorizer_get_feature_names_out():
"""Check that integer feature names are converted to strings in
feature_names_out."""
X = [{1: 2, 3: 4}, {2: 4}]
dv = DictVectorizer(sparse=False).fit(X)
feature_names = dv.get_feature_names_out()
assert isinstance(feature_names, np.ndarray)
... | Check that integer feature names are converted to strings in
feature_names_out. | test_dict_vectorizer_get_feature_names_out | python | scikit-learn/scikit-learn | sklearn/feature_extraction/tests/test_dict_vectorizer.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/feature_extraction/tests/test_dict_vectorizer.py | BSD-3-Clause |
def test_dict_vectorizer_not_fitted_error(method, input):
"""Check that unfitted DictVectorizer instance raises NotFittedError.
This should be part of the common test but currently they test estimator accepting
text input.
"""
dv = DictVectorizer(sparse=False)
with pytest.raises(NotFittedError... | Check that unfitted DictVectorizer instance raises NotFittedError.
This should be part of the common test but currently they test estimator accepting
text input.
| test_dict_vectorizer_not_fitted_error | python | scikit-learn/scikit-learn | sklearn/feature_extraction/tests/test_dict_vectorizer.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/feature_extraction/tests/test_dict_vectorizer.py | BSD-3-Clause |
def test_feature_hasher_single_string(raw_X):
"""FeatureHasher raises error when a sample is a single string.
Non-regression test for gh-13199.
"""
msg = "Samples can not be a single string"
feature_hasher = FeatureHasher(n_features=10, input_type="string")
with pytest.raises(ValueError, match... | FeatureHasher raises error when a sample is a single string.
Non-regression test for gh-13199.
| test_feature_hasher_single_string | python | scikit-learn/scikit-learn | sklearn/feature_extraction/tests/test_feature_hasher.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/feature_extraction/tests/test_feature_hasher.py | BSD-3-Clause |
def test_patch_extractor_wrong_input(orange_face):
"""Check that an informative error is raised if the patch_size is not valid."""
faces = _make_images(orange_face)
err_msg = "patch_size must be a tuple of two integers"
extractor = PatchExtractor(patch_size=(8, 8, 8))
with pytest.raises(ValueError, ... | Check that an informative error is raised if the patch_size is not valid. | test_patch_extractor_wrong_input | python | scikit-learn/scikit-learn | sklearn/feature_extraction/tests/test_image.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/feature_extraction/tests/test_image.py | BSD-3-Clause |
def test_countvectorizer_custom_token_pattern():
"""Check `get_feature_names_out()` when a custom token pattern is passed.
Non-regression test for:
https://github.com/scikit-learn/scikit-learn/issues/12971
"""
corpus = [
"This is the 1st document in my corpus.",
"This document is the... | Check `get_feature_names_out()` when a custom token pattern is passed.
Non-regression test for:
https://github.com/scikit-learn/scikit-learn/issues/12971
| test_countvectorizer_custom_token_pattern | python | scikit-learn/scikit-learn | sklearn/feature_extraction/tests/test_text.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/feature_extraction/tests/test_text.py | BSD-3-Clause |
def test_countvectorizer_custom_token_pattern_with_several_group():
"""Check that we raise an error if token pattern capture several groups.
Non-regression test for:
https://github.com/scikit-learn/scikit-learn/issues/12971
"""
corpus = [
"This is the 1st document in my corpus.",
"Th... | Check that we raise an error if token pattern capture several groups.
Non-regression test for:
https://github.com/scikit-learn/scikit-learn/issues/12971
| test_countvectorizer_custom_token_pattern_with_several_group | python | scikit-learn/scikit-learn | sklearn/feature_extraction/tests/test_text.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/feature_extraction/tests/test_text.py | BSD-3-Clause |
def test_countvectorizer_sort_features_64bit_sparse_indices(csr_container):
"""
Check that CountVectorizer._sort_features preserves the dtype of its sparse
feature matrix.
This test is skipped on 32bit platforms, see:
https://github.com/scikit-learn/scikit-learn/pull/11295
for more details.... |
Check that CountVectorizer._sort_features preserves the dtype of its sparse
feature matrix.
This test is skipped on 32bit platforms, see:
https://github.com/scikit-learn/scikit-learn/pull/11295
for more details.
| test_countvectorizer_sort_features_64bit_sparse_indices | python | scikit-learn/scikit-learn | sklearn/feature_extraction/tests/test_text.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/feature_extraction/tests/test_text.py | BSD-3-Clause |
def test_vectorizers_do_not_have_set_output(Estimator):
"""Check that vectorizers do not define set_output."""
est = Estimator()
assert not hasattr(est, "set_output") | Check that vectorizers do not define set_output. | test_vectorizers_do_not_have_set_output | python | scikit-learn/scikit-learn | sklearn/feature_extraction/tests/test_text.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/feature_extraction/tests/test_text.py | BSD-3-Clause |
def test_tfidf_transformer_copy(csr_container):
"""Check the behaviour of TfidfTransformer.transform with the copy parameter."""
X = sparse.rand(10, 20000, dtype=np.float64, random_state=42)
X_csr = csr_container(X)
# keep a copy of the original matrix for later comparison
X_csr_original = X_csr.co... | Check the behaviour of TfidfTransformer.transform with the copy parameter. | test_tfidf_transformer_copy | python | scikit-learn/scikit-learn | sklearn/feature_extraction/tests/test_text.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/feature_extraction/tests/test_text.py | BSD-3-Clause |
def test_tfidf_vectorizer_perserve_dtype_idf(dtype):
"""Check that `idf_` has the same dtype as the input data.
Non-regression test for:
https://github.com/scikit-learn/scikit-learn/issues/30016
"""
X = [str(uuid.uuid4()) for i in range(100_000)]
vectorizer = TfidfVectorizer(dtype=dtype).fit(X)... | Check that `idf_` has the same dtype as the input data.
Non-regression test for:
https://github.com/scikit-learn/scikit-learn/issues/30016
| test_tfidf_vectorizer_perserve_dtype_idf | python | scikit-learn/scikit-learn | sklearn/feature_extraction/tests/test_text.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/feature_extraction/tests/test_text.py | BSD-3-Clause |
def get_support(self, indices=False):
"""
Get a mask, or integer index, of the features selected.
Parameters
----------
indices : bool, default=False
If True, the return value will be an array of integers, rather
than a boolean mask.
Returns
... |
Get a mask, or integer index, of the features selected.
Parameters
----------
indices : bool, default=False
If True, the return value will be an array of integers, rather
than a boolean mask.
Returns
-------
support : array
A... | get_support | python | scikit-learn/scikit-learn | sklearn/feature_selection/_base.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/feature_selection/_base.py | BSD-3-Clause |
def _get_support_mask(self):
"""
Get the boolean mask indicating which features are selected
Returns
-------
support : boolean array of shape [# input features]
An element is True iff its corresponding feature is selected for
retention.
""" |
Get the boolean mask indicating which features are selected
Returns
-------
support : boolean array of shape [# input features]
An element is True iff its corresponding feature is selected for
retention.
| _get_support_mask | python | scikit-learn/scikit-learn | sklearn/feature_selection/_base.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/feature_selection/_base.py | BSD-3-Clause |
def transform(self, X):
"""Reduce X to the selected features.
Parameters
----------
X : array of shape [n_samples, n_features]
The input samples.
Returns
-------
X_r : array of shape [n_samples, n_selected_features]
The input samples with... | Reduce X to the selected features.
Parameters
----------
X : array of shape [n_samples, n_features]
The input samples.
Returns
-------
X_r : array of shape [n_samples, n_selected_features]
The input samples with only the selected features.
... | transform | python | scikit-learn/scikit-learn | sklearn/feature_selection/_base.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/feature_selection/_base.py | BSD-3-Clause |
def inverse_transform(self, X):
"""Reverse the transformation operation.
Parameters
----------
X : array of shape [n_samples, n_selected_features]
The input samples.
Returns
-------
X_original : array of shape [n_samples, n_original_features]
... | Reverse the transformation operation.
Parameters
----------
X : array of shape [n_samples, n_selected_features]
The input samples.
Returns
-------
X_original : array of shape [n_samples, n_original_features]
`X` with columns of zeros inserted whe... | inverse_transform | python | scikit-learn/scikit-learn | sklearn/feature_selection/_base.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/feature_selection/_base.py | BSD-3-Clause |
def get_feature_names_out(self, input_features=None):
"""Mask feature names according to selected features.
Parameters
----------
input_features : array-like of str or None, default=None
Input features.
- If `input_features` is `None`, then `feature_names_in_` i... | Mask feature names according to selected features.
Parameters
----------
input_features : array-like of str or None, default=None
Input features.
- If `input_features` is `None`, then `feature_names_in_` is
used as feature names in. If `feature_names_in_` ... | get_feature_names_out | python | scikit-learn/scikit-learn | sklearn/feature_selection/_base.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/feature_selection/_base.py | BSD-3-Clause |
def _get_feature_importances(estimator, getter, transform_func=None, norm_order=1):
"""
Retrieve and aggregate (ndim > 1) the feature importances
from an estimator. Also optionally applies transformation.
Parameters
----------
estimator : estimator
A scikit-learn estimator from which w... |
Retrieve and aggregate (ndim > 1) the feature importances
from an estimator. Also optionally applies transformation.
Parameters
----------
estimator : estimator
A scikit-learn estimator from which we want to get the feature
importances.
getter : "auto", str or callable
... | _get_feature_importances | python | scikit-learn/scikit-learn | sklearn/feature_selection/_base.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/feature_selection/_base.py | BSD-3-Clause |
def fit(self, X, y=None, **fit_params):
"""Fit the SelectFromModel meta-transformer.
Parameters
----------
X : array-like of shape (n_samples, n_features)
The training input samples.
y : array-like of shape (n_samples,), default=None
The target values (i... | Fit the SelectFromModel meta-transformer.
Parameters
----------
X : array-like of shape (n_samples, n_features)
The training input samples.
y : array-like of shape (n_samples,), default=None
The target values (integers that correspond to classes in
c... | fit | python | scikit-learn/scikit-learn | sklearn/feature_selection/_from_model.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/feature_selection/_from_model.py | BSD-3-Clause |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.