
    -i                         S SK Jr  S SKJr  S SKrS SKJr  S SK	J
r
  SSKJrJrJr  SSKJrJr  SS	KJr  S
 r " S S\\5      rg)    )chain)IntegralN)metadata_routing   )BaseEstimatorTransformerMixin_fit_context)Interval
StrOptions   )	transformc                 d    [        U S5      (       a  U R                  5       $ U R                  5       $ )z6Like d.iteritems, but accepts any collections.Mapping.	iteritems)hasattrr   items)ds    S/var/www/html/venv/lib/python3.13/site-packages/sklearn/feature_extraction/_hash.py
_iteritemsr      s%    #A{331;;=BB    c                     ^  \ rS rSr% SrS\R                  0r\" \	S\
R                  " \
R                  5      R                  SS9/\" 1 Sk5      /SS	/S
.r\\S'    SS\
R$                  SS.S jjr\" SS9SS j5       rS rU 4S jrSrU =r$ )FeatureHasher   an  Implements feature hashing, aka the hashing trick.

This class turns sequences of symbolic feature names (strings) into
scipy.sparse matrices, using a hash function to compute the matrix column
corresponding to a name. The hash function employed is the signed 32-bit
version of Murmurhash3.

Feature names of type byte string are used as-is. Unicode strings are
converted to UTF-8 first, but no Unicode normalization is done.
Feature values must be (finite) numbers.

This class is a low-memory alternative to DictVectorizer and
CountVectorizer, intended for large-scale (online) learning and situations
where memory is tight, e.g. when running prediction code on embedded
devices.

For an efficiency comparison of the different feature extractors, see
:ref:`sphx_glr_auto_examples_text_plot_hashing_vs_dict_vectorizer.py`.

Read more in the :ref:`User Guide <feature_hashing>`.

.. versionadded:: 0.13

Parameters
----------
n_features : int, default=2**20
    The number of features (columns) in the output matrices. Small numbers
    of features are likely to cause hash collisions, but large numbers
    will cause larger coefficient dimensions in linear learners.
input_type : str, default='dict'
    Choose a string from {'dict', 'pair', 'string'}.
    Either "dict" (the default) to accept dictionaries over
    (feature_name, value); "pair" to accept pairs of (feature_name, value);
    or "string" to accept single strings.
    feature_name should be a string, while value should be a number.
    In the case of "string", a value of 1 is implied.
    The feature_name is hashed to find the appropriate column for the
    feature. The value's sign might be flipped in the output (but see
    non_negative, below).
dtype : numpy dtype, default=np.float64
    The type of feature values. Passed to scipy.sparse matrix constructors
    as the dtype argument. Do not set this to bool, np.boolean or any
    unsigned integer type.
alternate_sign : bool, default=True
    When True, an alternating sign is added to the features as to
    approximately conserve the inner product in the hashed space even for
    small n_features. This approach is similar to sparse random projection.

    .. versionchanged:: 0.19
        ``alternate_sign`` replaces the now deprecated ``non_negative``
        parameter.

See Also
--------
DictVectorizer : Vectorizes string-valued features using a hash table.
sklearn.preprocessing.OneHotEncoder : Handles nominal/categorical features.

Notes
-----
This estimator is :term:`stateless` and does not need to be fitted.
However, we recommend to call :meth:`fit_transform` instead of
:meth:`transform`, as parameter validation is only performed in
:meth:`fit`.

Examples
--------
>>> from sklearn.feature_extraction import FeatureHasher
>>> h = FeatureHasher(n_features=10)
>>> D = [{'dog': 1, 'cat':2, 'elephant':4},{'dog': 2, 'run': 5}]
>>> f = h.transform(D)
>>> f.toarray()
array([[ 0.,  0., -4., -1.,  0.,  0.,  0.,  0.,  0.,  2.],
       [ 0.,  0.,  0., -2., -5.,  0.,  0.,  0.,  0.,  0.]])

With `input_type="string"`, the input must be an iterable over iterables of
strings:

>>> h = FeatureHasher(n_features=8, input_type="string")
>>> raw_X = [["dog", "cat", "snake"], ["snake", "dog"], ["cat", "bird"]]
>>> f = h.transform(raw_X)
>>> f.toarray()
array([[ 0.,  0.,  0., -1.,  0., -1.,  0.,  1.],
       [ 0.,  0.,  0., -1.,  0., -1.,  0.,  0.],
       [ 0., -1.,  0.,  0.,  0.,  0.,  0.,  1.]])
raw_Xr   both)closed>   dictpairstringno_validationboolean)
n_features
input_typedtypealternate_sign_parameter_constraintsr   T)r"   r#   r$   c                4    X0l         X l        Xl        X@l        g N)r#   r"   r!   r$   )selfr!   r"   r#   r$   s        r   __init__FeatureHasher.__init__w   s     
$$,r   )prefer_skip_nested_validationc                     U $ )a  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 : Ignored
    Not used, present here for API consistency by convention.

y : Ignored
    Not used, present here for API consistency by convention.

Returns
-------
self : object
    FeatureHasher class instance.
 )r(   Xys      r   fitFeatureHasher.fit   s	    ( r   c                    [        U5      nU R                  S:X  a
  S U 5       nOQU R                  S:X  aA  [        U5      n[        U[        5      (       a  [        S5      e[        U/U5      nS U 5       n[        XR                  U R                  U R                  SS9u  pEnUR                  S   S-
  nUS:X  a  [        S	5      e[        R                  " XdU4U R                  XpR                  4S
9nUR                  5         U$ )af  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 values, see
    the input_type constructor argument) which will be hashed.
    raw_X need not support the len function, so it can be the result
    of a generator; n_samples is determined on the fly.

Returns
-------
X : sparse matrix of shape (n_samples, n_features)
    Feature matrix, for use with estimators or further transformers.
r   c              3   8   #    U  H  n[        U5      v   M     g 7fr'   )r   ).0r   s     r   	<genexpr>*FeatureHasher.transform.<locals>.<genexpr>   s     2EqZ]]Es   r   z\Samples can not be a single string. The input must be an iterable over iterables of strings.c              3   4   #    U  H  nS  U 5       v   M     g7f)c              3   (   #    U  H  oS 4v   M
     g7f)r   Nr-   )r4   fs     r   r5   4FeatureHasher.transform.<locals>.<genexpr>.<genexpr>   s     (a!fas   Nr-   )r4   xs     r   r5   r6      s     9&Q(a((&s   r   )seedr   z Cannot vectorize empty sequence.)r#   shape)iterr"   next
isinstancestr
ValueErrorr   _hashing_transformr!   r#   r$   r=   sp
csr_matrixsum_duplicates)	r(   r   first_raw_Xraw_X_indicesindptrvalues	n_samplesr.   s	            r   r   FeatureHasher.transform   s    " U??f$2E2E__(u+K+s++ 2  K=%0F9&9E"4??DJJ0C0C!#
 LLOa'	>?@@MMf%**oo.

 	
r   c                    > [         TU ]  5       nSUR                  l        U R                  S:X  a  SUR                  l        O!U R                  S:X  a  SUR                  l        SUl        U$ )NFr   Tr   )super__sklearn_tags__
input_tagstwo_d_arrayr"   r   r   requires_fit)r(   tags	__class__s     r   rP   FeatureHasher.__sklearn_tags__   sY    w')&+#??h&%)DOO"__&#'DOO !r   )r$   r#   r"   r!   )i   )NN)__name__
__module____qualname____firstlineno____doc__r   UNUSED+_FeatureHasher__metadata_request__transformr
   r   npiinfoint32maxr   r%   r   __annotations__float64r)   r	   r0   r   rP   __static_attributes____classcell__)rU   s   @r   r   r      s    Tn &-.>.E.E$F!  !RXXbhh-?-C-CFST!"<=> $+	$D  - jj- 5 6*-^ r   r   )	itertoolsr   numbersr   numpyr^   scipy.sparsesparserD   sklearn.utilsr   baser   r   r	   utils._param_validationr
   r   _hashing_fastr   rC   r   r   r-   r   r   <module>ro      s9        * @ @ : :C
{$m {r   