
    0PhA.                       d Z ddlZddlZddlZddlZddlmZ ddlmZ ddl	m
Z
 ddlmZ ddlmZ ddlZddlmZ ddlmZ d	d
lmZmZmZmZ d	dlmZ d	dlmZ d	dlm Z m!Z!m"Z"m#Z# d	dl$m%Z% d	dl&m'Z'm(Z(m)Z)m*Z* ddl+m,Z, ddl-m.Z. g dZ/d(dZ0	 	 	 	 	 	 d)dZ1d Z2d Z3d Z4d Z5 G d d          Z6 G d dee6ed          Z7d  Z8 G d! d"e6e          Z9d# Z: G d$ d%eeed          Z; G d& d'e9          Z<dS )*z7Utilities to build feature vectors from text documents.    N)defaultdict)Mapping)partial)Integral)
itemgetter)metadata_routing   )BaseEstimatorOneToOneFeatureMixinTransformerMixin_fit_context)NotFittedError)	normalize)
HasMethodsInterval
RealNotInt
StrOptions)	_IS_32BIT)FLOAT_DTYPEScheck_arraycheck_is_fittedvalidate_data   )FeatureHasher)ENGLISH_STOP_WORDS)HashingVectorizerCountVectorizerr   TfidfTransformerTfidfVectorizerstrip_accents_asciistrip_accents_unicode
strip_tagsFc                 L    |r|                                  } | ||           } | S )a  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.
    lower: bool, default=False
        Whether to use str.lower to lowercase all of the text

    Returns
    -------
    doc: str
        preprocessed string
    )lower)docaccent_functionr$   s      _/var/www/html/test/jupyter/venv/lib/python3.11/site-packages/sklearn/feature_extraction/text.py_preprocessr(   *   s3    &  iikk"oc""J    c                     | ||           } | ||           } n6| ||           } | ||           } || || |          } n ||           } | S )a  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
    ----------
    analyzer: callable, default=None
    tokenizer: callable, default=None
    ngrams: callable, default=None
    preprocessor: callable, default=None
    decoder: callable, default=None
    stop_words: list, default=None

    Returns
    -------
    ngrams: list
        A sequence of tokens, possibly with pairs, triples, etc.
     )r%   analyzer	tokenizerngramspreprocessordecoder
stop_wordss          r'   _analyzer2   D   s    < gcllhsmm#,s##C )C..C%fS*--fSkkJr)   c                     	 |                      dd           | S # t          $ r7 t          j        d|           }d                    d |D                       cY S w xY w)a  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
    -------
    s : str
        The stripped string.

    See Also
    --------
    strip_accents_ascii : Remove accentuated char for any unicode symbol that
        has a direct ASCII equivalent.
    ASCIIstrict)errorsNFKD c                 :    g | ]}t          j        |          |S r+   )unicodedata	combining).0cs     r'   
<listcomp>z)strip_accents_unicode.<locals>.<listcomp>   s(    NNNa[5J15M5MNNNNr)   )encodeUnicodeEncodeErrorr:   r   join)s
normalizeds     r'   r!   r!   s   s}    ,P 	
*** P P P *6155
wwNN:NNNOOOOOPs    >AAc                 ~    t          j        d|           }|                    dd                              d          S )a  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.

    See Also
    --------
    strip_accents_unicode : Remove accentuated char for any unicode symbol.
    r7   r4   ignore)r:   r   r?   decode)rB   	nkfd_forms     r'   r    r       s:    ( %fa00IGX..55g>>>r)   c                 j    t          j        dt           j                                      d|           S )a8  Basic regexp based HTML / XML tag stripper function.

    For serious HTML/XML preprocessing you should rather use an external
    library such as lxml or BeautifulSoup.

    Parameters
    ----------
    s : str
        The string to strip.

    Returns
    -------
    s : str
        The stripped string.
    z	<([^>]+)>)flags )recompileUNICODEsub)rB   s    r'   r"   r"      s+      :l"*55599#qAAAr)   c                     | dk    rt           S t          | t                    rt          d| z            | d S t	          |           S )Nenglishznot a built-in stop list: %s)r   
isinstancestr
ValueError	frozenset)stops    r'   _check_stop_listrV      sO    y!!	D#		 7$>???	tr)   c                       e Zd ZdZ ej        d          Zd ZddZd Z	d Z
d Zd	 Zd
 Zd Zd Zd Zd Zd Zd ZdS )_VectorizerMixinz?Provides common code for text vectorizers (tokenization logic).z\s\s+c                 x   | j         dk    r=t          |d          5 }|                                }ddd           n# 1 swxY w Y   n| j         dk    r|                                }t          |t                    r |                    | j        | j                  }|t          j	        u rt          d          |S )a?  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.
        filenamerbNfilez?np.nan is an invalid document, expected byte or unicode string.)inputopenreadrQ   bytesrF   encodingdecode_errornpnanrS   )selfr%   fhs      r'   rF   z_VectorizerMixin.decode   s     :##c4  Bggii                              Z6!!((**Cc5!! 	?**T]D,=>>C"&==Q   
s   =AANc           
      |   fd|D             }| j         \  }}|dk    r|}|dk    rt          |          }|dz  }ng }t          |          }|j        }dj        }t          |t          |dz   |dz                       D ]9}	t          ||	z
  dz             D ]!}
 | |||
|
|	z                                 ":|S )zATurn tokens into a sequence of n-grams after stop words filteringNc                     g | ]}|v|	S r+   r+   )r<   wr1   s     r'   r>   z1_VectorizerMixin._word_ngrams.<locals>.<listcomp>   s#    ???A1J+>+>a+>+>+>r)   r   rJ   )ngram_rangelistlenappendrA   rangemin)re   tokensr1   min_nmax_noriginal_tokensn_original_tokenstokens_append
space_joinnis     `        r'   _word_ngramsz_VectorizerMixin._word_ngrams   s    !???????F 'uA::$Ozz o..
 #O 4 4 #MMJ5#eai1BQ1F"G"GHH J J014q899 J JA!M**_QQY-G"H"HIIIIJ r)   c                 `   | j                             d|          }t          |          }| j        \  }}|dk    rt	          |          }|dz  }ng }|j        }t          |t          |dz   |dz                       D ]0}t          ||z
  dz             D ]} |||||z                       1|S )z;Tokenize text_document into a sequence of character n-gramsrJ   r   )_white_spacesrN   rl   rj   rk   rm   rn   ro   )	re   text_documenttext_lenrq   rr   r.   ngrams_appendrw   rx   s	            r'   _char_ngramsz_VectorizerMixin._char_ngrams  s     *..sMBB}%%'uA:: -((FQJEEF uc%!)X\::;; 	8 	8A8a<!+,, 8 8mAAI677778r)   c                    | j                             d|          }| j        \  }}g }|j        }|                                D ]|}d|z   dz   }t          |          }t          ||dz             D ]O}d}	 |||	|	|z                       |	|z   |k     r$|	dz  }	 |||	|	|z                       |	|z   |k     $|	dk    r nP}|S )zWhitespace 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.rJ   r   r   )r{   rN   rj   rm   splitrl   rn   )
re   r|   rq   rr   r.   r~   ri   w_lenrw   offsets
             r'   _char_wb_ngramsz _VectorizerMixin._char_wb_ngrams#  s    *..sMBB'u $$&& 
	 
	Aa#AFFE5%!),,  a! 34555qj5((aKF!M!FVaZ$7"8999 qj5(( Q;;E r)   c                    | j         | j         S | j        sd}nYt          | j                  r| j        }n=| j        dk    rt          }n*| j        dk    rt          }nt          d| j        z            t          t          || j                  S )zReturn a function to preprocess the text before tokenization.

        Returns
        -------
        preprocessor: callable
              A function to preprocess the text before tokenization.
        Nasciiunicodez%Invalid value for "strip_accents": %s)r&   r$   )	r/   strip_accentscallabler    r!   rS   r   r(   	lowercase)re   r   s     r'   build_preprocessorz#_VectorizerMixin.build_preprocessor?  s     ($$ ! 	 MMd()) 		 .MM7**/MM9,,1MM7$:LL   {MXXXXr)   c                     | j         | j         S t          j        | j                  }|j        dk    rt          d          |j        S )zReturn 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.
        Nr   zUMore than 1 capturing group in token pattern. Only a single group should be captured.)r-   rK   rL   token_patterngroupsrS   findall)re   r   s     r'   build_tokenizerz _VectorizerMixin.build_tokenizerZ  sV     >%>!
4#566!##,  
 $$r)   c                 *    t          | j                  S )zBuild or fetch the effective stop words list.

        Returns
        -------
        stop_words: list or None
                A list of stop words.
        )rV   r1   re   s    r'   get_stop_wordsz_VectorizerMixin.get_stop_wordsn  s      000r)   c                    t          | j                  t          | dd          k    rdS 	 t                      }|pdD ]A}t	           | ||                              }|D ]}||vr|                    |           Bt          | j                  | _        |r$t          j        dt          |          z             | S # t          $ r t          | j                  | _        Y dS w xY w)a  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
                        performed (e.g. because of the use of a custom
                        preprocessor / tokenizer)
        _stop_words_idNr+   z}Your stop_words may be inconsistent with your preprocessing. Tokenizing the stop words generated tokens %r not in stop_words.error)idr1   getattrsetrk   addr   warningswarnsorted	Exception)re   r1   
preprocesstokenizeinconsistentri   rp   tokens           r'   _check_stop_words_consistencyz._VectorizerMixin._check_stop_words_consistencyx  s(    do'$0@$"G"GGG4	55L%2 0 0hhzz!}}5566# 0 0EJ..$((///0 #%T_"5"5D " %+<$8$89   $## 	 	 	 #%T_"5"5D77		s   BC #C('C(c                 R   t          | j                  r!t          t          | j        | j                  S |                                 }| j        dk    r"t          t          | j        || j                  S | j        dk    r"t          t          | j        || j                  S | j        dk    rc|                                 }| 	                                }| 
                    |||           t          t          | j        ||| j        |          S t          d| j        z            )a!  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.
        )r,   r0   char)r.   r/   r0   char_wbword)r.   r-   r/   r0   r1   z.%s is not a valid tokenization scheme/analyzer)r   r,   r   r2   rF   r   r   r   r   r   r   ry   rS   )re   r   r1   r   s       r'   build_analyzerz_VectorizerMixin.build_analyzer  sB    DM"" 	R8dmT[QQQQ,,..
=F""('	    ]i''+'	    ]f$$,,..J++--H..z:xPPP("'%    @4=P  r)   c                    | j         }|Et          |t                    rt          |          }t          |t                    sHi }t          |          D ]3\  }}|                    ||          |k    rd|z  }t          |          4|}nt          |                                          }t          |          t          |          k    rt          d          t          t          |                    D ])}||vr#dt          |          |fz  }t          |          *|st          d          d| _        t          |          | _        d S d| _        d S )Nz Duplicate term in vocabulary: %rz%Vocabulary contains repeated indices.z/Vocabulary of size %d doesn't contain index %d.zempty vocabulary passed to fitTF)
vocabularyrQ   r   r   r   	enumerate
setdefaultrS   valuesrl   rn   fixed_vocabulary_dictvocabulary_)re   r   vocabrx   tmsgindicess          r'   _validate_vocabularyz%_VectorizerMixin._validate_vocabulary  s{   _
!*c** 0#J//
j'22 .%j11 . .DAq''1--22@1D(oo- 3 #

j//1122w<<3z??22$%LMMMs:// . .A''O
OOS  )oo- (  C !ABBB%)D"#J//D%*D"""r)   c                     t          | d          s*|                                  | j        st          d          t	          | j                  dk    rt          d          dS )z4Check if vocabulary is empty or missing (not fitted)r   z!Vocabulary not fitted or providedr   zVocabulary is emptyN)hasattrr   r   r   rl   r   rS   r   s    r'   _check_vocabularyz"_VectorizerMixin._check_vocabulary  so    t]++ 	J%%''') J$%HIIIt  A%%2333 &%r)   c                 n    | j         \  }}||k    r$t          dt          | j                   z            dS )z'Check validity of ngram_range parameterzOInvalid value for ngram_range=%s lower boundary larger than the upper boundary.N)rj   rS   rR   )re   rq   max_ms      r'   _validate_ngram_rangez&_VectorizerMixin._validate_ngram_range  sJ    'u5==ACFtGWCXCXY   =r)   c                    | j         | j        t          j        d           | j        (t          | j                  rt          j        d           | j        dk    r/| j        (t          | j                  rt          j        d           | j        dk    st          | j                  r^| j        t          j        d           | j        | j        dk    rt          j        d           | j         t          j        d	           d S d S d S )
NzMThe parameter 'token_pattern' will not be used since 'tokenizer' is not None'zKThe parameter 'preprocessor' will not be used since 'analyzer' is callable'r   r   zJThe parameter 'ngram_range' will not be used since 'analyzer' is callable'r   zFThe parameter 'stop_words' will not be used since 'analyzer' != 'word'(?u)\b\w\w+\bzIThe parameter 'token_pattern' will not be used since 'analyzer' != 'word'zEThe parameter 'tokenizer' will not be used since 'analyzer' != 'word')	r-   r   r   r   r/   r   r,   rj   r1   r   s    r'   _warn_for_unused_paramsz(_VectorizerMixin._warn_for_unused_params  sS   >%$*<*HM2  
 (Xdm-D-D(M1   && ,'' - M1   =F""ht}&=&="*2  
 ".&*:::2   ~)2     #" *)r)   N)__name__
__module____qualname____doc__rK   rL   r{   rF   ry   r   r   r   r   r   r   r   r   r   r   r   r+   r)   r'   rX   rX      s        IIBJx((M  @   <  .  8Y Y Y6% % %(1 1 1% % %N1 1 1f+ + +<4 4 4  ( ( ( ( (r)   rX   c                   .    e Zd ZU dZi d eh d          gdegd eh d          gd edd	h          d
egddgded
gded
gd edh          ed
gded
gdegd eh d          egd e	e
d ej        ej                  j        d          gddgd eddh          d
gddgddZeed <   d!d"d#d
d$d
d
d
d%d&d'd(d)dd$ej        d*d+Z ed$,          d3d-            Z ed$,          d3d.            Zd/ Zd3d0Zd1 Z fd2Z xZS )4r   a  Convert a collection of text documents to a matrix of token occurrences.

    It turns a collection of text documents into a scipy.sparse matrix holding
    token occurrence counts (or binary occurrence information), possibly
    normalized as token frequencies if norm='l1' or projected on the euclidean
    unit sphere if norm='l2'.

    This text vectorizer implementation uses the hashing trick to find the
    token string name to feature integer index mapping.

    This strategy has several advantages:

    - it is very low memory scalable to large datasets as there is no need to
      store a vocabulary dictionary in memory.

    - it is fast to pickle and un-pickle as it holds no state besides the
      constructor parameters.

    - it can be used in a streaming (partial fit) or parallel pipeline as there
      is no state computed during fit.

    There are also a couple of cons (vs using a CountVectorizer with an
    in-memory vocabulary):

    - there is no way to compute the inverse transform (from feature indices to
      string feature names) which can be a problem when trying to introspect
      which features are most important to a model.

    - there can be collisions: distinct tokens can be mapped to the same
      feature index. However in practice this is rarely an issue if n_features
      is large enough (e.g. 2 ** 18 for text classification problems).

    - no IDF weighting as this would render the transformer stateful.

    The hash function employed is the signed 32-bit version of Murmurhash3.

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

    For an example of document clustering and comparison with
    :class:`~sklearn.feature_extraction.text.TfidfVectorizer`, see
    :ref:`sphx_glr_auto_examples_text_plot_document_clustering.py`.

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

    Parameters
    ----------
    input : {'filename', 'file', 'content'}, default='content'
        - If `'filename'`, the sequence passed as an argument to fit is
          expected to be a list of filenames that need reading to fetch
          the raw content to analyze.

        - If `'file'`, the sequence items must have a 'read' method (file-like
          object) that is called to fetch the bytes in memory.

        - If `'content'`, the input is expected to be a sequence of items that
          can be of type string or byte.

    encoding : str, default='utf-8'
        If bytes or files are given to analyze, this encoding is used to
        decode.

    decode_error : {'strict', 'ignore', 'replace'}, default='strict'
        Instruction on what to do if a byte sequence is given to analyze that
        contains characters not of the given `encoding`. By default, it is
        'strict', meaning that a UnicodeDecodeError will be raised. Other
        values are 'ignore' and 'replace'.

    strip_accents : {'ascii', 'unicode'} or callable, default=None
        Remove accents and perform other character normalization
        during the preprocessing step.
        'ascii' is a fast method that only works on characters that have
        a direct ASCII mapping.
        'unicode' is a slightly slower method that works on any character.
        None (default) means no character normalization is performed.

        Both 'ascii' and 'unicode' use NFKD normalization from
        :func:`unicodedata.normalize`.

    lowercase : bool, default=True
        Convert all characters to lowercase before tokenizing.

    preprocessor : callable, default=None
        Override the preprocessing (string transformation) stage while
        preserving the tokenizing and n-grams generation steps.
        Only applies if ``analyzer`` is not callable.

    tokenizer : callable, default=None
        Override the string tokenization step while preserving the
        preprocessing and n-grams generation steps.
        Only applies if ``analyzer == 'word'``.

    stop_words : {'english'}, list, default=None
        If 'english', a built-in stop word list for English is used.
        There are several known issues with 'english' and you should
        consider an alternative (see :ref:`stop_words`).

        If a list, that list is assumed to contain stop words, all of which
        will be removed from the resulting tokens.
        Only applies if ``analyzer == 'word'``.

    token_pattern : str or None, default=r"(?u)\\b\\w\\w+\\b"
        Regular expression denoting what constitutes a "token", only used
        if ``analyzer == 'word'``. The default regexp selects tokens of 2
        or more alphanumeric characters (punctuation is completely ignored
        and always treated as a token separator).

        If there is a capturing group in token_pattern then the
        captured group content, not the entire match, becomes the token.
        At most one capturing group is permitted.

    ngram_range : tuple (min_n, max_n), default=(1, 1)
        The lower and upper boundary of the range of n-values for different
        n-grams to be extracted. All values of n such that min_n <= n <= max_n
        will be used. For example an ``ngram_range`` of ``(1, 1)`` means only
        unigrams, ``(1, 2)`` means unigrams and bigrams, and ``(2, 2)`` means
        only bigrams.
        Only applies if ``analyzer`` is not callable.

    analyzer : {'word', 'char', 'char_wb'} or callable, default='word'
        Whether the feature should be made of word or character n-grams.
        Option 'char_wb' creates character n-grams only from text inside
        word boundaries; n-grams at the edges of words are padded with space.

        If a callable is passed it is used to extract the sequence of features
        out of the raw, unprocessed input.

        .. versionchanged:: 0.21
            Since v0.21, if ``input`` is ``'filename'`` or ``'file'``, the data
            is first read from the file and then passed to the given callable
            analyzer.

    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.

    binary : bool, default=False
        If True, all non zero counts are set to 1. This is useful for discrete
        probabilistic models that model binary events rather than integer
        counts.

    norm : {'l1', 'l2'}, default='l2'
        Norm used to normalize term vectors. None for no normalization.

    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.

        .. versionadded:: 0.19

    dtype : type, default=np.float64
        Type of the matrix returned by fit_transform() or transform().

    See Also
    --------
    CountVectorizer : Convert a collection of text documents to a matrix of
        token counts.
    TfidfVectorizer : Convert a collection of raw documents to a matrix of
        TF-IDF 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.text import HashingVectorizer
    >>> corpus = [
    ...     'This is the first document.',
    ...     'This document is the second document.',
    ...     'And this is the third one.',
    ...     'Is this the first document?',
    ... ]
    >>> vectorizer = HashingVectorizer(n_features=2**4)
    >>> X = vectorizer.fit_transform(corpus)
    >>> print(X.shape)
    (4, 16)
    r]   >   r\   contentrZ   ra   rb   >   rE   r5   replacer   r   r   Nr   booleanr/   r-   r1   rP   r   rj   r,   >   r   r   r   
n_featuresr   leftclosedbinarynorml1l2alternate_signdtypeno_validation_parameter_constraintsr   utf-8r5   Tr   r   r   i   F)r]   ra   rb   r   r   r/   r-   r1   r   rj   r,   r   r   r   r   r   c                    || _         || _        || _        || _        || _        || _        || _        || _        |	| _        || _	        || _
        |
| _        || _        || _        || _        || _        d S r   )r]   ra   rb   r   r/   r-   r,   r   r   r1   r   rj   r   r   r   r   )re   r]   ra   rb   r   r   r/   r-   r1   r   rj   r,   r   r   r   r   r   s                    r'   __init__zHashingVectorizer.__init__  s~    ( 
 (*(" "*$$&	,


r)   prefer_skip_nested_validationc                     | S )  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
            Not used, present for API consistency by convention.

        Returns
        -------
        self : object
            HashingVectorizer instance.
        r+   re   Xys      r'   partial_fitzHashingVectorizer.partial_fit!  s	    ( r)   c                     t          |t                    rt          d          |                                  |                                  |                                                     ||           | S )r   BIterable over raw text documents expected, string object received.)r   )rQ   rR   rS   r   r   _get_hasherfitr   s      r'   r   zHashingVectorizer.fit7  s{    * a 	T   	$$&&&""$$$qA&&&r)   c                    t          |t                    rt          d          |                                  |                                 |                                                     fd|D                       }| j        r|j        	                    d           | j
        t          || j
        d          }|S )a  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
            constructor argument) which will be tokenized and hashed.

        Returns
        -------
        X : sparse matrix of shape (n_samples, n_features)
            Document-term matrix.
        r   c              3   .   K   | ]} |          V  d S r   r+   )r<   r%   r,   s     r'   	<genexpr>z.HashingVectorizer.transform.<locals>.<genexpr>n  s+      (D(D3#(D(D(D(D(D(Dr)   r   NFr   copy)rQ   rR   rS   r   r   r   	transformr   datafillr   r   )re   r   r,   s     @r'   r   zHashingVectorizer.transformW  s     a 	T   	""$$$&&(((((D(D(D(D!(D(D(DDD; 	FKKNNN9 !$)%888Ar)   c                 T    |                      ||                              |          S )a  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
            constructor argument) which will be tokenized and hashed.
        y : any
            Ignored. This parameter exists only for compatibility with
            sklearn.pipeline.Pipeline.

        Returns
        -------
        X : sparse matrix of shape (n_samples, n_features)
            Document-term matrix.
        )r   r   r   s      r'   fit_transformzHashingVectorizer.fit_transformu  s$    $ xx1~~''***r)   c                 F    t          | j        d| j        | j                  S )Nstring)r   
input_typer   r   )r   r   r   r   r   s    r'   r   zHashingVectorizer._get_hasher  s,    *.	
 
 
 	
r)   c                 x    t                                                      }d|j        _        d|j        _        |S NTFsuper__sklearn_tags__
input_tagsr   two_d_arrayre   tags	__class__s     r'   r   z"HashingVectorizer.__sklearn_tags__  1    ww''))!%&+#r)   r   )r   r   r   r   r   rR   r   rk   tupler   r   rc   iinfoint32maxr   r   __annotations__float64r   r   r   r   r   r   r   r   __classcell__r   s   @r'   r   r   .  s        v vp$**<<<==>$SE$ 	$C$C$CDDE$ 	**gy%9::D(K	$
 	i[$ 	4($ 	h%$ 	zz9+..d;$ 	#t$ 	w$ 	ZZ ; ; ;<<hG$ 	xx!XRXbh-?-?-CFSSST$ 	9+$ 	T4L))40$ 	9+$  	!$D   , &j%# # # # #J \555   65* \555   65>  <+ + + +(
 
 
        r)   r   )auto_wrap_output_keysc                     t          j        |           r1| j        dk    r&t          j        | j        | j        d                   S t          j        | j                  S )zACount the number of non-zero values for each feature in sparse X.csrr   )	minlength)	spissparseformatrc   bincountr   shapediffindptr)r   s    r'   _document_frequencyr    sM    	{1~~ !!(e++{19
;;;;wqx   r)   c                       e Zd ZU dZdej        iZdej        iZi d eh d          gde	gd eh d          gd ed	d
h          de
gddgde
dgde
dgd edh          edgde	dgdegd eh d          e
gd eeddd           eeddd          gd eeddd           eeddd          gd eeddd          dgde ed          dgd dgd!d"Zeed#<   d$d%d&dd'dddd(d)d*d+dddd,ej        d-d.Zd/ Zd9d0Zd1 Zd:d2Z ed'3          d:d4            Zd5 Zd6 Zd:d7Z  fd8Z! xZ"S );r   a   Convert a collection of text documents to a matrix of token counts.

    This implementation produces a sparse representation of the counts using
    scipy.sparse.csr_matrix.

    If you do not provide an a-priori dictionary and you do not use an analyzer
    that does some kind of feature selection then the number of features will
    be equal to the vocabulary size found by analyzing the data.

    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 <text_feature_extraction>`.

    Parameters
    ----------
    input : {'filename', 'file', 'content'}, default='content'
        - If `'filename'`, the sequence passed as an argument to fit is
          expected to be a list of filenames that need reading to fetch
          the raw content to analyze.

        - If `'file'`, the sequence items must have a 'read' method (file-like
          object) that is called to fetch the bytes in memory.

        - If `'content'`, the input is expected to be a sequence of items that
          can be of type string or byte.

    encoding : str, default='utf-8'
        If bytes or files are given to analyze, this encoding is used to
        decode.

    decode_error : {'strict', 'ignore', 'replace'}, default='strict'
        Instruction on what to do if a byte sequence is given to analyze that
        contains characters not of the given `encoding`. By default, it is
        'strict', meaning that a UnicodeDecodeError will be raised. Other
        values are 'ignore' and 'replace'.

    strip_accents : {'ascii', 'unicode'} or callable, default=None
        Remove accents and perform other character normalization
        during the preprocessing step.
        'ascii' is a fast method that only works on characters that have
        a direct ASCII mapping.
        'unicode' is a slightly slower method that works on any characters.
        None (default) means no character normalization is performed.

        Both 'ascii' and 'unicode' use NFKD normalization from
        :func:`unicodedata.normalize`.

    lowercase : bool, default=True
        Convert all characters to lowercase before tokenizing.

    preprocessor : callable, default=None
        Override the preprocessing (strip_accents and lowercase) stage while
        preserving the tokenizing and n-grams generation steps.
        Only applies if ``analyzer`` is not callable.

    tokenizer : callable, default=None
        Override the string tokenization step while preserving the
        preprocessing and n-grams generation steps.
        Only applies if ``analyzer == 'word'``.

    stop_words : {'english'}, list, default=None
        If 'english', a built-in stop word list for English is used.
        There are several known issues with 'english' and you should
        consider an alternative (see :ref:`stop_words`).

        If a list, that list is assumed to contain stop words, all of which
        will be removed from the resulting tokens.
        Only applies if ``analyzer == 'word'``.

        If None, no stop words will be used. In this case, setting `max_df`
        to a higher value, such as in the range (0.7, 1.0), can automatically detect
        and filter stop words based on intra corpus document frequency of terms.

    token_pattern : str or None, default=r"(?u)\\b\\w\\w+\\b"
        Regular expression denoting what constitutes a "token", only used
        if ``analyzer == 'word'``. The default regexp select tokens of 2
        or more alphanumeric characters (punctuation is completely ignored
        and always treated as a token separator).

        If there is a capturing group in token_pattern then the
        captured group content, not the entire match, becomes the token.
        At most one capturing group is permitted.

    ngram_range : tuple (min_n, max_n), default=(1, 1)
        The lower and upper boundary of the range of n-values for different
        word n-grams or char n-grams to be extracted. All values of n such
        such that min_n <= n <= max_n will be used. For example an
        ``ngram_range`` of ``(1, 1)`` means only unigrams, ``(1, 2)`` means
        unigrams and bigrams, and ``(2, 2)`` means only bigrams.
        Only applies if ``analyzer`` is not callable.

    analyzer : {'word', 'char', 'char_wb'} or callable, default='word'
        Whether the feature should be made of word n-gram or character
        n-grams.
        Option 'char_wb' creates character n-grams only from text inside
        word boundaries; n-grams at the edges of words are padded with space.

        If a callable is passed it is used to extract the sequence of features
        out of the raw, unprocessed input.

        .. versionchanged:: 0.21

        Since v0.21, if ``input`` is ``filename`` or ``file``, the data is
        first read from the file and then passed to the given callable
        analyzer.

    max_df : float in range [0.0, 1.0] or int, default=1.0
        When building the vocabulary ignore terms that have a document
        frequency strictly higher than the given threshold (corpus-specific
        stop words).
        If float, the parameter represents a proportion of documents, integer
        absolute counts.
        This parameter is ignored if vocabulary is not None.

    min_df : float in range [0.0, 1.0] or int, default=1
        When building the vocabulary ignore terms that have a document
        frequency strictly lower than the given threshold. This value is also
        called cut-off in the literature.
        If float, the parameter represents a proportion of documents, integer
        absolute counts.
        This parameter is ignored if vocabulary is not None.

    max_features : int, default=None
        If not None, build a vocabulary that only consider the top
        `max_features` ordered by term frequency across the corpus.
        Otherwise, all features are used.

        This parameter is ignored if vocabulary is not None.

    vocabulary : Mapping or iterable, default=None
        Either a Mapping (e.g., a dict) where keys are terms and values are
        indices in the feature matrix, or an iterable over terms. If not
        given, a vocabulary is determined from the input documents. Indices
        in the mapping should not be repeated and should not have any gap
        between 0 and the largest index.

    binary : bool, default=False
        If True, all non zero counts are set to 1. This is useful for discrete
        probabilistic models that model binary events rather than integer
        counts.

    dtype : dtype, default=np.int64
        Type of the matrix returned by fit_transform() or transform().

    Attributes
    ----------
    vocabulary_ : dict
        A mapping of terms to feature indices.

    fixed_vocabulary_ : bool
        True if a fixed vocabulary of term to indices mapping
        is provided by the user.

    See Also
    --------
    HashingVectorizer : Convert a collection of text documents to a
        matrix of token counts.

    TfidfVectorizer : Convert a collection of raw documents to a matrix
        of TF-IDF features.

    Examples
    --------
    >>> from sklearn.feature_extraction.text import CountVectorizer
    >>> corpus = [
    ...     'This is the first document.',
    ...     'This document is the second document.',
    ...     'And this is the third one.',
    ...     'Is this the first document?',
    ... ]
    >>> vectorizer = CountVectorizer()
    >>> X = vectorizer.fit_transform(corpus)
    >>> vectorizer.get_feature_names_out()
    array(['and', 'document', 'first', 'is', 'one', 'second', 'the', 'third',
           'this'], ...)
    >>> print(X.toarray())
    [[0 1 1 1 0 0 1 0 1]
     [0 2 0 1 0 1 1 0 1]
     [1 0 0 1 1 0 1 1 1]
     [0 1 1 1 0 0 1 0 1]]
    >>> vectorizer2 = CountVectorizer(analyzer='word', ngram_range=(2, 2))
    >>> X2 = vectorizer2.fit_transform(corpus)
    >>> vectorizer2.get_feature_names_out()
    array(['and this', 'document is', 'first document', 'is the', 'is this',
           'second document', 'the first', 'the second', 'the third', 'third one',
           'this document', 'this is', 'this the'], ...)
     >>> print(X2.toarray())
     [[0 0 1 1 0 0 1 0 0 0 0 1 0]
     [0 1 0 1 0 1 0 1 0 0 1 0 0]
     [1 0 0 1 0 0 0 0 1 1 0 1 0]
     [0 0 1 0 1 0 1 0 0 0 0 0 1]]
    raw_documentsr]   >   r\   r   rZ   ra   rb   >   rE   r5   r   r   r   r   Nr   r   r/   r-   r1   rP   r   rj   r,   >   r   r   r   max_dfr   r   bothr   r   min_dfmax_featuresr   __iter__r   r   r   r   r   r   r5   Tr   r   r         ?F)r]   ra   rb   r   r   r/   r-   r1   r   rj   r,   r  r  r  r   r   r   c                    || _         || _        || _        || _        || _        || _        || _        || _        |	| _        || _	        || _
        || _        || _        |
| _        || _        || _        || _        d S r   )r]   ra   rb   r   r/   r-   r,   r   r   r1   r  r  r  rj   r   r   r   )re   r]   ra   rb   r   r   r/   r-   r1   r   rj   r,   r  r  r  r   r   r   s                     r'   r   zCountVectorizer.__init__  s    * 
 (*(" "*$(&$


r)   c                 (   t          |                                          }t          j        t	          |          |j        j                  }t          |          D ]\  }\  }}|||<   |||<   |                    |j        d          |_        |S )zgSort features by name

        Returns a reordered matrix and modifies the vocabulary in place
        r   clip)mode)	r   itemsrc   emptyrl   r   r   r   take)re   r   r   sorted_features	map_indexnew_valtermold_vals           r'   _sort_featureszCountVectorizer._sort_features  s    
 !!1!1!3!344HS11III	(1/(B(B 	) 	)$G_dG&Jt!(IgNN196N::	r)   c                    ||||t                      fS t          |          }t          j        t	          |          t
                    }|	|||k    z  }|	|||k    z  }||                                |k    rt          j        |                    d                                                    }||          	                                d|         }	t          j
        t	          |          t
                    }
d|
t          j        |          d         |	         <   |
}t          j        |          dz
  }t          |                                          D ]\  }}||         r||         ||<   ||= t          j        |          d         }t	          |          dk    rt          d          |dd|f         S )a*  Remove too rare or too common features.

        Prune features that are non zero in more samples than high or less
        documents than low, modifying the vocabulary, and restricting it to
        at most the limit most frequent.

        This does not prune samples with zero features.
        Nr  r   )axisTr   zFAfter pruning, no terms remain. Try a lower min_df or a higher max_df.)r   r  rc   onesrl   boolsumasarrayravelargsortzeroswherecumsumrk   r  rS   )re   r   r   highlowlimitdfsmasktfs	mask_indsnew_masknew_indicesr#  	old_indexkept_indicess                  r'   _limit_featureszCountVectorizer._limit_features  s    <CKEMcee8O "!$$ws3xxt,,,C4KD?C3JDe!3!3*QUUU]]++1133Cd),,..vv6IxC555H59HRXd^^A&y12Dioo)#J$4$4$6$677 	% 	%OD)I %#.y#9
4  t$$x~~a(|!!X   L!!r)   c                    |r| j         }nt                      }|j        |_        |                                 }g }g }t                      }|                    d           |D ]}i }	 ||          D ]5}
	 ||
         }||	vrd|	|<   n|	|xx         dz  cc<   &# t          $ r Y 2w xY w|                    |		                                           |                    |	
                                           |                    t          |                     |s t          |          }|st          d          |d         t          j        t          j                  j        k    r<t$          r(t          d                    |d                             t          j        }nt          j        }t          j        ||          }t          j        ||          }t          j        |t          j                  }t1          j        |||ft          |          dz
  t          |          f| j                  }|                                 ||fS )zDCreate sparse feature matrix, and vocabulary where fixed_vocab=Falser   r   z?empty vocabulary; perhaps the documents only contain stop wordszpsparse CSR array has {} non-zero elements and requires 64 bit indexing, which is unsupported with 32 bit Python.r  )r  r   )r   r   __len__default_factoryr   _make_int_arrayrm   KeyErrorextendkeysr   rl   r   rS   rc   r   r   r   r   r
  int64r+  
frombufferintcr  
csr_matrixr   sort_indices)re   r  fixed_vocabr   analyze	j_indicesr  r   r%   feature_counterfeaturefeature_idxindices_dtyper   s                 r'   _count_vocabzCountVectorizer._count_vocab  s|    	<)JJ %J)3);J&%%''	 ""a  	* 	*C O"73<< 	 	",W"5K"/997844'4449444   H _1133444MM/0022333MM#i..)))) 	j))J  U   ":**...  C fVBZ((   HMM HMJy>>>	F-888vRW555MY'v;;?C
OO4*
 
 

 	
1}s   4"B
B$#B$c                 0    |                      |           | S )an  Learn a vocabulary dictionary of all tokens in the raw documents.

        Parameters
        ----------
        raw_documents : iterable
            An iterable which generates either str, unicode or file objects.

        y : None
            This parameter is ignored.

        Returns
        -------
        self : object
            Fitted vectorizer.
        )r   )re   r  r   s      r'   r   zCountVectorizer.fit  s      	=)))r)   r   c                 z   t          |t                    rt          d          |                                  |                                  |                                  | j        }| j        }| j        }| j	        rN| j
        rG| j        D ]?}t          t          t          j        |                    rt          j        d            n@|                     || j	                  \  }}| j        r|j                            d           | j	        s|j        d         }	t          |t,                    r|n||	z  }
t          |t,                    r|n||	z  }|
|k     rt          d          ||                     ||          }|                     |||
||          }||                     ||          }|| _        |S )a  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.

        y : None
            This parameter is ignored.

        Returns
        -------
        X : array of shape (n_samples, n_features)
            Document-term matrix.
        r   zyUpper case characters found in vocabulary while 'lowercase' is True. These entries will not be matched with any documentsr   r   z-max_df corresponds to < documents than min_df)rQ   rR   rS   r   r   r   r  r  r  r   r   r   anymapisupperr   r   rQ  r   r   r   r  r   r%  r<  r   )re   r  r   r  r  r  r#  r   r   n_docmax_doc_countmin_doc_counts               r'   r   zCountVectorizer.fit_transform2  s   . mS)) 	T   	""$$$$$&&&!!###(! 		dn 		  s3;--.. M9   E ))-9OPP
A; 	FKKNNN% 	*GAJE&0&B&BVFFQVM&0&B&BVFFQVM},, !PQQQ''':66$$:}m\ A #'':66)Dr)   c                     t          |t                    rt          d          |                                  |                     |d          \  }}| j        r|j                            d           |S )a  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 file objects.

        Returns
        -------
        X : sparse matrix of shape (n_samples, n_features)
            Document-term matrix.
        r   T)rJ  r   )rQ   rR   rS   r   rQ  r   r   r   )re   r  _r   s       r'   r   zCountVectorizer.transformv  s}      mS)) 	T   	      D AA1; 	FKKNNNr)   c                    |                                   t          d          j        d         }t          j        t          | j                                                            }t          j        t          | j                                                            }|t          j	        |                   t          j                  rfdt          |          D             S fdt          |          D             S )aJ  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_inv : list of arrays of shape (n_samples,)
            List of arrays of terms.
        r  )accept_sparser   c                     g | ]>}|d d f                                          d                                                  ?S )Nr   )nonzeror,  r<   rx   r   inverse_vocabularys     r'   r>   z5CountVectorizer.inverse_transform.<locals>.<listcomp>  sU        #1QT7??#4#4Q#78>>@@  r)   c           	      |    g | ]8}t          j        |d d f                                                            9S r   )rc   flatnonzeror,  r`  s     r'   r>   z5CountVectorizer.inverse_transform.<locals>.<listcomp>  sP        #2>!AqqqD'#:#:;AACC  r)   )r   r   r  rc   arrayrk   r   rD  r   r-  r  r	  rn   )re   r   	n_samplestermsr   ra  s    `   @r'   inverse_transformz!CountVectorizer.inverse_transform  s    	   ///GAJ	d.33556677(4 0 7 7 9 9::;;"2:g#6#67;q>> 		    y))   
    y))   r)   c           	          |                                   t          j        d t          | j                                        t          d                    D             t                    S )a^  Get output feature names for transformation.

        Parameters
        ----------
        input_features : array-like of str or None, default=None
            Not used, present here for API consistency by convention.

        Returns
        -------
        feature_names_out : ndarray of str objects
            Transformed feature names.
        c                     g | ]\  }}|S r+   r+   )r<   r   rx   s      r'   r>   z9CountVectorizer.get_feature_names_out.<locals>.<listcomp>  s    OOO41aQOOOr)   r   )keyr  )r   rc   r+  r   r   r  r   object)re   input_featuress     r'   get_feature_names_outz%CountVectorizer.get_feature_names_out  se     	   zOO6$"2"8"8":":
1NNNOOO
 
 
 	
r)   c                 x    t                                                      }d|j        _        d|j        _        |S r   r   r   s     r'   r   z CountVectorizer.__sklearn_tags__  r   r)   )NNNr   )#r   r   r   r   r   UNUSED'_CountVectorizer__metadata_request__fit-_CountVectorizer__metadata_request__transformr   rR   r   rk   r   r   r   r   r   r   r   r   r   rc   rE  r   r%  r<  rQ  r   r   r   r   rg  rm  r   r  r  s   @r'   r   r     sK        @ @H  /0@0GH%46F6M$N!$**<<<==>$SE$ 	$C$C$CDDE$ 	**gy%9::D(K	$
 	i[$ 	4($ 	h%$ 	zz9+..d;$ 	#t$ 	w$ 	ZZ ; ; ;<<hG$ 	HZAf555HXq$v666
$  	HZAf555HXq$v666
!$( 	(AtFCCCTJ)$* 	w

: 6 6=+$, 	9+-$. 	/$D   : &h'% % % % %N  %" %" %" %"N? ? ?B   & \555A A A 65AF  8  B
 
 
 
&        r)   r   c                  D    t          j         t          d                    S )zEConstruct an array.array of a type suitable for scipy.sparse indices.rx   )rd  rR   r+   r)   r'   rA  rA    s    ;s3xx   r)   c                        e Zd ZU dZ eddh          dgdgdgdgdZeed<   dddd	dd
Z e	d          dd            Z
ddZ fdZ xZS )r   u  Transform a count matrix to a normalized tf or tf-idf representation.

    Tf means term-frequency while tf-idf means term-frequency times inverse
    document-frequency. This is a common term weighting scheme in information
    retrieval, that has also found good use in document classification.

    The goal of using tf-idf instead of the raw frequencies of occurrence of a
    token in a given document is to scale down the impact of tokens that occur
    very frequently in a given corpus and that are hence empirically less
    informative than features that occur in a small fraction of the training
    corpus.

    The formula that is used to compute the tf-idf for a term t of a document d
    in a document set is tf-idf(t, d) = tf(t, d) * idf(t), and the idf is
    computed as idf(t) = log [ n / df(t) ] + 1 (if ``smooth_idf=False``), where
    n is the total number of documents in the document set and df(t) is the
    document frequency of t; the document frequency is the number of documents
    in the document set that contain the term t. The effect of adding "1" to
    the idf in the equation above is that terms with zero idf, i.e., terms
    that occur in all documents in a training set, will not be entirely
    ignored.
    (Note that the idf formula above differs from the standard textbook
    notation that defines the idf as
    idf(t) = log [ n / (df(t) + 1) ]).

    If ``smooth_idf=True`` (the default), the constant "1" is added to the
    numerator and denominator of the idf as if an extra document was seen
    containing every term in the collection exactly once, which prevents
    zero divisions: idf(t) = log [ (1 + n) / (1 + df(t)) ] + 1.

    Furthermore, the formulas used to compute tf and idf depend
    on parameter settings that correspond to the SMART notation used in IR
    as follows:

    Tf is "n" (natural) by default, "l" (logarithmic) when
    ``sublinear_tf=True``.
    Idf is "t" when use_idf is given, "n" (none) otherwise.
    Normalization is "c" (cosine) when ``norm='l2'``, "n" (none)
    when ``norm=None``.

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

    Parameters
    ----------
    norm : {'l1', 'l2'} or None, default='l2'
        Each output row will have unit norm, either:

        - 'l2': Sum of squares of vector elements is 1. The cosine
          similarity between two vectors is their dot product when l2 norm has
          been applied.
        - 'l1': Sum of absolute values of vector elements is 1.
          See :func:`~sklearn.preprocessing.normalize`.
        - None: No normalization.

    use_idf : bool, default=True
        Enable inverse-document-frequency reweighting. If False, idf(t) = 1.

    smooth_idf : bool, default=True
        Smooth idf weights by adding one to document frequencies, as if an
        extra document was seen containing every term in the collection
        exactly once. Prevents zero divisions.

    sublinear_tf : bool, default=False
        Apply sublinear tf scaling, i.e. replace tf with 1 + log(tf).

    Attributes
    ----------
    idf_ : array of shape (n_features)
        The inverse document frequency (IDF) vector; only defined
        if  ``use_idf`` is True.

        .. versionadded:: 0.20

    n_features_in_ : int
        Number of features seen during :term:`fit`.

        .. versionadded:: 1.0

    feature_names_in_ : ndarray of shape (`n_features_in_`,)
        Names of features seen during :term:`fit`. Defined only when `X`
        has feature names that are all strings.

        .. versionadded:: 1.0

    See Also
    --------
    CountVectorizer : Transforms text into a sparse matrix of n-gram counts.

    TfidfVectorizer : Convert a collection of raw documents to a matrix of
        TF-IDF features.

    HashingVectorizer : Convert a collection of text documents to a matrix
        of token occurrences.

    References
    ----------
    .. [Yates2011] R. Baeza-Yates and B. Ribeiro-Neto (2011). Modern
                   Information Retrieval. Addison Wesley, pp. 68-74.

    .. [MRS2008] C.D. Manning, P. Raghavan and H. Schütze  (2008).
                   Introduction to Information Retrieval. Cambridge University
                   Press, pp. 118-120.

    Examples
    --------
    >>> from sklearn.feature_extraction.text import TfidfTransformer
    >>> from sklearn.feature_extraction.text import CountVectorizer
    >>> from sklearn.pipeline import Pipeline
    >>> corpus = ['this is the first document',
    ...           'this document is the second document',
    ...           'and this is the third one',
    ...           'is this the first document']
    >>> vocabulary = ['this', 'document', 'first', 'is', 'second', 'the',
    ...               'and', 'one']
    >>> pipe = Pipeline([('count', CountVectorizer(vocabulary=vocabulary)),
    ...                  ('tfid', TfidfTransformer())]).fit(corpus)
    >>> pipe['count'].transform(corpus).toarray()
    array([[1, 1, 1, 1, 0, 1, 0, 0],
           [1, 2, 0, 1, 1, 1, 0, 0],
           [1, 0, 0, 1, 0, 1, 1, 1],
           [1, 1, 1, 1, 0, 1, 0, 0]])
    >>> pipe['tfid'].idf_
    array([1.        , 1.22314355, 1.51082562, 1.        , 1.91629073,
           1.        , 1.91629073, 1.91629073])
    >>> pipe.transform(corpus).shape
    (4, 8)
    r   r   Nr   r   use_idf
smooth_idfsublinear_tfr   TFc                >    || _         || _        || _        || _        d S r   rt  )re   r   ru  rv  rw  s        r'   r   zTfidfTransformer.__init__\  s%    	$(r)   r   c                 n   t          | |dt                     }t          j        |          st          j        |          }|j        t          j        t          j        fv r|j        nt          j        }| j	        r|j
        \  }}t          |          }|                    |d          }|t          | j                  z  }|t          | j                  z  }t          j        |||          | _        | xj        |z  c_        t          j        | j        | j                   | xj        dz  c_        | S )af  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
            Fitted transformer.
        )r  csc)r]  accept_large_sparseFr   )
fill_valuer   )outr  )r   r   r  r	  rH  r   rc   r  float32ru  r  r  astypefloatrv  int	full_likeidf_log)re   r   r   r   re  r[  dfs          r'   r   zTfidfTransformer.fitb  s   ( !>9}
 
 
 {1~~ 	!a  A7rz2:&>>>BJ< 	7LIq$Q''B5u--B %(((BT_---I RIUKKKDIIIOIIF49$),,,,IIIIr)   c                    t          |            t          | |dt          j        t          j        g|d          }t          j        |          st          j        ||j                  }| j	        r/t          j
        |j        |j                   |xj        dz  c_        t          | d          r |xj        | j        |j                 z  c_        | j        t!          || j        d          }|S )	a  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
            operations. `copy=False` will only be effective with CSR sparse matrix.

        Returns
        -------
        vectors : sparse matrix of shape (n_samples, n_features)
            Tf-idf-weighted document-term matrix.
        r  F)r]  r   r   resetr  r  r  Nr   )r   r   rc   r  r  r  r	  rH  r   rw  r  r   r   r  r   r   r   )re   r   r   s      r'   r   zTfidfTransformer.transform  s    " 	:rz*
 
 
 {1~~ 	0aqw///A 	F1616"""FFcMFF4   	+ FFdi	**FF9 !$)%888Ar)   c                 |    t                                                      }d|j        _        ddg|j        _        |S )NTr  r  )r   r   r   sparsetransformer_tagspreserves_dtyper   s     r'   r   z!TfidfTransformer.__sklearn_tags__  s9    ww''))!% 2;I0F-r)   r   )T)r   r   r   r   r   r   r   r   r   r   r   r   r   r  r  s   @r'   r   r     s         ~ ~B T4L))40; k"	$ $D     $TdQV ) ) ) ) ) \555- - - 65-^) ) ) )V        r)   r   c                   X    e Zd ZU dZi ej        Zeed<   e                     e	ddh          dgdgdgdgd           dd	d
ddddddddddddde
j        ddddd fd
Zed             Zej        d             Zd Z ed          d fd	            Zd fd	Z fdZ fdZ xZS )r   a"  Convert a collection of raw documents to a matrix of TF-IDF features.

    Equivalent to :class:`CountVectorizer` followed by
    :class:`TfidfTransformer`.

    For an example of usage, see
    :ref:`sphx_glr_auto_examples_text_plot_document_classification_20newsgroups.py`.

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

    For an example of document clustering and comparison with
    :class:`~sklearn.feature_extraction.text.HashingVectorizer`, see
    :ref:`sphx_glr_auto_examples_text_plot_document_clustering.py`.

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

    Parameters
    ----------
    input : {'filename', 'file', 'content'}, default='content'
        - If `'filename'`, the sequence passed as an argument to fit is
          expected to be a list of filenames that need reading to fetch
          the raw content to analyze.

        - If `'file'`, the sequence items must have a 'read' method (file-like
          object) that is called to fetch the bytes in memory.

        - If `'content'`, the input is expected to be a sequence of items that
          can be of type string or byte.

    encoding : str, default='utf-8'
        If bytes or files are given to analyze, this encoding is used to
        decode.

    decode_error : {'strict', 'ignore', 'replace'}, default='strict'
        Instruction on what to do if a byte sequence is given to analyze that
        contains characters not of the given `encoding`. By default, it is
        'strict', meaning that a UnicodeDecodeError will be raised. Other
        values are 'ignore' and 'replace'.

    strip_accents : {'ascii', 'unicode'} or callable, default=None
        Remove accents and perform other character normalization
        during the preprocessing step.
        'ascii' is a fast method that only works on characters that have
        a direct ASCII mapping.
        'unicode' is a slightly slower method that works on any characters.
        None (default) means no character normalization is performed.

        Both 'ascii' and 'unicode' use NFKD normalization from
        :func:`unicodedata.normalize`.

    lowercase : bool, default=True
        Convert all characters to lowercase before tokenizing.

    preprocessor : callable, default=None
        Override the preprocessing (string transformation) stage while
        preserving the tokenizing and n-grams generation steps.
        Only applies if ``analyzer`` is not callable.

    tokenizer : callable, default=None
        Override the string tokenization step while preserving the
        preprocessing and n-grams generation steps.
        Only applies if ``analyzer == 'word'``.

    analyzer : {'word', 'char', 'char_wb'} or callable, default='word'
        Whether the feature should be made of word or character n-grams.
        Option 'char_wb' creates character n-grams only from text inside
        word boundaries; n-grams at the edges of words are padded with space.

        If a callable is passed it is used to extract the sequence of features
        out of the raw, unprocessed input.

        .. versionchanged:: 0.21
            Since v0.21, if ``input`` is ``'filename'`` or ``'file'``, the data
            is first read from the file and then passed to the given callable
            analyzer.

    stop_words : {'english'}, list, default=None
        If a string, it is passed to _check_stop_list and the appropriate stop
        list is returned. 'english' is currently the only supported string
        value.
        There are several known issues with 'english' and you should
        consider an alternative (see :ref:`stop_words`).

        If a list, that list is assumed to contain stop words, all of which
        will be removed from the resulting tokens.
        Only applies if ``analyzer == 'word'``.

        If None, no stop words will be used. In this case, setting `max_df`
        to a higher value, such as in the range (0.7, 1.0), can automatically detect
        and filter stop words based on intra corpus document frequency of terms.

    token_pattern : str, default=r"(?u)\\b\\w\\w+\\b"
        Regular expression denoting what constitutes a "token", only used
        if ``analyzer == 'word'``. The default regexp selects tokens of 2
        or more alphanumeric characters (punctuation is completely ignored
        and always treated as a token separator).

        If there is a capturing group in token_pattern then the
        captured group content, not the entire match, becomes the token.
        At most one capturing group is permitted.

    ngram_range : tuple (min_n, max_n), default=(1, 1)
        The lower and upper boundary of the range of n-values for different
        n-grams to be extracted. All values of n such that min_n <= n <= max_n
        will be used. For example an ``ngram_range`` of ``(1, 1)`` means only
        unigrams, ``(1, 2)`` means unigrams and bigrams, and ``(2, 2)`` means
        only bigrams.
        Only applies if ``analyzer`` is not callable.

    max_df : float or int, default=1.0
        When building the vocabulary ignore terms that have a document
        frequency strictly higher than the given threshold (corpus-specific
        stop words).
        If float in range [0.0, 1.0], the parameter represents a proportion of
        documents, integer absolute counts.
        This parameter is ignored if vocabulary is not None.

    min_df : float or int, default=1
        When building the vocabulary ignore terms that have a document
        frequency strictly lower than the given threshold. This value is also
        called cut-off in the literature.
        If float in range of [0.0, 1.0], the parameter represents a proportion
        of documents, integer absolute counts.
        This parameter is ignored if vocabulary is not None.

    max_features : int, default=None
        If not None, build a vocabulary that only consider the top
        `max_features` ordered by term frequency across the corpus.
        Otherwise, all features are used.

        This parameter is ignored if vocabulary is not None.

    vocabulary : Mapping or iterable, default=None
        Either a Mapping (e.g., a dict) where keys are terms and values are
        indices in the feature matrix, or an iterable over terms. If not
        given, a vocabulary is determined from the input documents.

    binary : bool, default=False
        If True, all non-zero term counts are set to 1. This does not mean
        outputs will have only 0/1 values, only that the tf term in tf-idf
        is binary. (Set `binary` to True, `use_idf` to False and
        `norm` to None to get 0/1 outputs).

    dtype : dtype, default=float64
        Type of the matrix returned by fit_transform() or transform().

    norm : {'l1', 'l2'} or None, default='l2'
        Each output row will have unit norm, either:

        - 'l2': Sum of squares of vector elements is 1. The cosine
          similarity between two vectors is their dot product when l2 norm has
          been applied.
        - 'l1': Sum of absolute values of vector elements is 1.
          See :func:`~sklearn.preprocessing.normalize`.
        - None: No normalization.

    use_idf : bool, default=True
        Enable inverse-document-frequency reweighting. If False, idf(t) = 1.

    smooth_idf : bool, default=True
        Smooth idf weights by adding one to document frequencies, as if an
        extra document was seen containing every term in the collection
        exactly once. Prevents zero divisions.

    sublinear_tf : bool, default=False
        Apply sublinear tf scaling, i.e. replace tf with 1 + log(tf).

    Attributes
    ----------
    vocabulary_ : dict
        A mapping of terms to feature indices.

    fixed_vocabulary_ : bool
        True if a fixed vocabulary of term to indices mapping
        is provided by the user.

    idf_ : array of shape (n_features,)
        The inverse document frequency (IDF) vector; only defined
        if ``use_idf`` is True.

    See Also
    --------
    CountVectorizer : Transforms text into a sparse matrix of n-gram counts.

    TfidfTransformer : Performs the TF-IDF transformation from a provided
        matrix of counts.

    Examples
    --------
    >>> from sklearn.feature_extraction.text import TfidfVectorizer
    >>> corpus = [
    ...     'This is the first document.',
    ...     'This document is the second document.',
    ...     'And this is the third one.',
    ...     'Is this the first document?',
    ... ]
    >>> vectorizer = TfidfVectorizer()
    >>> X = vectorizer.fit_transform(corpus)
    >>> vectorizer.get_feature_names_out()
    array(['and', 'document', 'first', 'is', 'one', 'second', 'the', 'third',
           'this'], ...)
    >>> print(X.shape)
    (4, 9)
    r   r   r   Nr   rt  r   r   r5   Tr   r   r   r  r   F)r]   ra   rb   r   r   r/   r-   r,   r1   r   rj   r  r  r  r   r   r   r   ru  rv  rw  c                    t                                          |||||||||	|
|||||||           || _        || _        || _        || _        d S )N)r]   ra   rb   r   r   r/   r-   r,   r1   r   rj   r  r  r  r   r   r   )r   r   r   ru  rv  rw  )re   r]   ra   rb   r   r   r/   r-   r,   r1   r   rj   r  r  r  r   r   r   r   ru  rv  rw  r   s                         r'   r   zTfidfVectorizer.__init__  s~    2 	%'%!'#%!# 	 	
 	
 	
& 	$(r)   c                 r    t          | d          st          | j        j         d          | j        j        S )zInverse document frequency vector, only defined if `use_idf=True`.

        Returns
        -------
        ndarray of shape (n_features,)
        _tfidfzV is not fitted yet. Call 'fit' with appropriate arguments before using this attribute.)r   r   r   r   r  r  r   s    r'   r  zTfidfVectorizer.idf_  sO     tX&& 	 >* E E E   {r)   c                    | j         st          d          t          | d          s,t          | j        | j         | j        | j                  | _        |                                  t          | d          rXt          | j
                  t          |          k    r3t          dt          |          t          | j                  fz            || j        _        d S )Nz+`idf_` cannot be set when `user_idf=False`.r  rt  r   z5idf length = %d must be equal to vocabulary size = %d)ru  rS   r   r   r   rv  rw  r  r   rl   r   r   r  )re   values     r'   r  zTfidfVectorizer.idf_  s    | 	LJKKKtX&& 		 +Y?!.	  DK 	!!###4'' 	4#$$E

22 K5zz3t#7#789   !r)   c                     | j         t          vr:t          j        d                    t          | j                   t
                     d S d S )NzKOnly {} 'dtype' should be used. {} 'dtype' will be converted to np.float64.)r   r   r   r   r
  UserWarningr   s    r'   _check_paramszTfidfVectorizer._check_params  sN    :\))M..4f\4:.N.N     *)r)   r   c                 &   |                                   |                                  t          | j        | j        | j        | j                  | _        t                      	                    |          }| j        
                    |           | S )al  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 : object
            Fitted vectorizer.
        rt  )r  r   r   r   ru  rv  rw  r  r   r   r   re   r  r   r   r   s       r'   r   zTfidfVectorizer.fit  s    " 	$$&&&&L*	
 
 
 GG!!-00r)   c                 2   |                                   t          | j        | j        | j        | j                  | _        t                                          |          }| j        	                    |           | j        
                    |d          S )a  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 : None
            This parameter is ignored.

        Returns
        -------
        X : sparse matrix of (n_samples, n_features)
            Tf-idf-weighted document-term matrix.
        rt  Fr|  )r  r   r   ru  rv  rw  r  r   r   r   r   r  s       r'   r   zTfidfVectorizer.fit_transform  s    & 	&L*	
 
 
 GG!!-00 {$$QU$333r)   c                     t          | d           t                                          |          }| j                            |d          S )a  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
        -------
        X : sparse matrix of (n_samples, n_features)
            Tf-idf-weighted document-term matrix.
        z#The TF-IDF vectorizer is not fitted)r   Fr|  )r   r   r   r  )re   r  r   r   s      r'   r   zTfidfVectorizer.transform>  sK      	"GHHHHGGm,,{$$QU$333r)   c                     t                                                      }d|j        _        d|j        _        d|_        |S r   )r   r   r   r   r   
_skip_testr   s     r'   r   z TfidfVectorizer.__sklearn_tags__S  s8    ww''))!%&+#r)   r   )r   r   r   r   r   r   r   r   updater   rc   r  r   propertyr  setterr  r   r   r   r   r   r  r  s   @r'   r   r     s        L L\ $No&L#MDMMM!!Zt--t4!{$+&K		
 	
   &j//) /) /) /) /) /) /)h     X  
[! ! [!,   \555     6584 4 4 4 4 4@4 4 4 4 4*        r)   r   )NF)NNNNNN)=r   rd  rK   r:   r   collectionsr   collections.abcr   	functoolsr   numbersr   operatorr   numpyrc   scipy.sparser  r  sklearn.utilsr   baser
   r   r   r   
exceptionsr   preprocessingr   utils._param_validationr   r   r   r   utils.fixesr   utils.validationr   r   r   r   _hashr   _stop_wordsr   __all__r(   r2   r!   r    r"   rV   rX   r   r  r   rA  r   r   r+   r)   r'   <module>r     s[   = =
  				      # # # # # # # # # # # #                             * * * * * * V V V V V V V V V V V V ' ' ' ' ' ' % % % % % % R R R R R R R R R R R R # # # # # # X X X X X X X X X X X X             + + + + + +	 	 	   8 , , , ,^P P P@? ? ?0B B B&  b b b b b b b bJg g g g g&Tg g g gT! ! !j j j j j& j j jZ! ! !
q q q q q*MQUq q q qhR R R R Ro R R R R Rr)   