
    -ih.             	          S r SSKrSSKrSSKrSSKrSSKJr  SSKJr  SSK	J
r
  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Jr  S	SKJr  S	SKJr  S	SKJ r J!r!J"r"J#r#  S	SK$J%r%  S	SK&J'r'J(r(J)r)J*r*  SSK+J,r,  SSK-J.r.  / SQr/S'S jr0      S(S jr1S r2S r3S r4S r5 " S S5      r6 " S S\\6\SS9r7S r8 " S  S!\6\5      r9S" r: " S# S$\\\SS9r; " S% S&\95      r<g))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)r   CountVectorizerHashingVectorizerTfidfTransformerTfidfVectorizerstrip_accents_asciistrip_accents_unicode
strip_tagsc                 J    U(       a  U R                  5       n Ub  U" U 5      n U $ )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      R/var/www/html/venv/lib/python3.13/site-packages/sklearn/feature_extraction/text.py_preprocessr(   *   s'    & iik"c"J    c                     Ub  U" U 5      n Ub
  U" U 5      n U $ Ub  U" U 5      n Ub  U" U 5      n Ub  Ub
  U" X5      n U $ U" U 5      n U $ )aW  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   sw    < clsm J #s#C C.C%S- J SkJr)   c           	           U R                  SSS9  U $ ! [         a_    [        R                  " SU 5      nSR	                  U Vs/ s H"  n[        R
                  " U5      (       a  M   UPM$     Os  snf sn5      s $ f = f)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 )encodeUnicodeEncodeErrorunicodedatar   join	combining)s
normalizedcs      r'   r!   r!   s   sm    ,P 	
* P **615
ww:N:a[5J5J15M:NOOPs!    0A=A.
'A.
-A=<A=c                 r    [         R                  " SU 5      nUR                  SS5      R                  S5      $ )al  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   r9   decode)r>   	nkfd_forms     r'   r    r       s4    ( %%fa0IGX.55g>>r)   c                 h    [         R                  " S[         R                  S9R                  SU 5      $ )a  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)r>   s    r'   r"   r"      s&      ::l"**599#qAAr)   c                 ~    U S:X  a  [         $ [        U [        5      (       a  [        SU -  5      eU c  g [	        U 5      $ )Nenglishznot a built-in stop list: %s)r   
isinstancestr
ValueError	frozenset)stops    r'   _check_stop_listrS      s@    y!!	D#		7$>??	r)   c                       \ rS rSrSr\R                  " S5      rS rSS jr	S r
S rS	 rS
 rS rS rS rS rS rS rS rSrg)_VectorizerMixin   z?Provides common code for text vectorizers (tokenization logic).z\s\s+c                    U R                   S:X  a&  [        US5       nUR                  5       nSSS5        O U R                   S:X  a  UR                  5       n[        U[        5      (       a&  UR                  U R                  U R                  5      nU[        R                  L a  [        S5      eU$ ! , (       d  f       Ni= f)zDecode 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readrN   bytesrC   encodingdecode_errornpnanrP   )selfr%   fhs      r'   rC   _VectorizerMixin.decode   s     ::#c4Bggi ! ZZ6!((*Cc5!!**T]]D,=,=>C"&&=Q  
 !s   B22
C Nc           
         Ub  U Vs/ s H  o3U;  d  M
  UPM     nnU R                   u  pEUS:w  a  UnUS:X  a  [        U5      nUS-  nO/ n[        U5      nUR                  nSR                  n	[        U[        US-   US-   5      5       H,  n
[        Xz-
  S-   5       H  nU" U	" XkX-    5      5        M     M.     U$ s  snf )zATurn tokens into a sequence of n-grams after stop words filteringr   rG   )ngram_rangelistlenappendr<   rangemin)rc   tokensr1   wmin_nmax_noriginal_tokensn_original_tokenstokens_append
space_joinnis               r'   _word_ngrams_VectorizerMixin._word_ngrams   s     !!'?AJ+>aF? ''A:$Oz o.
 #O 4 #MMMJ5#eai1BQ1F"GH04q89A!*_-G"HI : I 1 @s
   	B=B=c                 F   U R                   R                  SU5      n[        U5      nU R                  u  p4US:X  a  [	        U5      nUS-  nO/ nUR
                  n[        U[        US-   US-   5      5       H&  n[        X'-
  S-   5       H  nU" XX-    5        M     M(     U$ )z;Tokenize text_document into a sequence of character n-gramsrG   r   )_white_spacesrK   ri   rg   rh   rj   rk   rl   )	rc   text_documenttext_lenro   rp   r.   ngrams_appendru   rv   s	            r'   _char_ngrams_VectorizerMixin._char_ngrams  s     **..sMB}%''A: -(FQJEF uc%!)X\:;A8<!+,m67 - < r)   c                 h   U R                   R                  SU5      nU R                  u  p#/ nUR                  nUR	                  5        He  nSU-   S-   n[        U5      n[        X#S-   5       H=  nSn	U" XiX-    5        X-   U:  a  U	S-  n	U" XiX-    5        X-   U:  a  M  U	S:X  d  M<    Mc     Mg     U$ )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.rG   r   r   )rz   rK   rg   rj   splitri   rk   )
rc   r{   ro   rp   r.   r}   rn   w_lenru   offsets
             r'   _char_wb_ngrams _VectorizerMixin._char_wb_ngrams#  s     **..sMB'' $$&Aa#AFE5!),a45j5(aKF!!VZ"89 j5( Q; - ' r)   c                 f   U R                   b  U R                   $ U R                  (       d  SnOm[        U R                  5      (       a  U R                  nOFU R                  S:X  a  [        nO/U R                  S:X  a  [        nO[        SU R                  -  5      e[        [        XR                  S9$ )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!   rP   r   r(   	lowercase)rc   r   s     r'   build_preprocessor#_VectorizerMixin.build_preprocessor?  s     ($$$ !! Md(()) ..M7*/M9,1M7$:L:LL  {MXXr)   c                     U R                   b  U R                   $ [        R                  " U R                  5      nUR                  S:  a  [        S5      eUR                  $ )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.
r   zUMore than 1 capturing group in token pattern. Only a single group should be captured.)r-   rH   rI   token_patterngroupsrP   findall)rc   r   s     r'   build_tokenizer _VectorizerMixin.build_tokenizerZ  sZ     >>%>>!

4#5#56!#, 
 $$$r)   c                 ,    [        U R                  5      $ )zvBuild or fetch the effective stop words list.

Returns
-------
stop_words: list or None
        A list of stop words.
)rS   r1   rc   s    r'   get_stop_words_VectorizerMixin.get_stop_wordsn  s      00r)   c                    [        U R                  5      [        U SS5      :X  a  g [        5       nU=(       d    S H;  n[	        U" U" U5      5      5      nU H  nXq;  d  M
  UR                  U5        M     M=     [        U R                  5      U l        U(       a"  [        R                  " S[        U5      -  5        U(       + $ ! [         a    [        U R                  5      U l         gf = f)ar  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setrh   addr   warningswarnsorted	Exception)rc   r1   
preprocesstokenizeinconsistentrn   rm   tokens           r'   _check_stop_words_consistency._VectorizerMixin._check_stop_words_consistencyx  s     doo'$0@$"GG	5L%2%hz!}56#E.$((/ $ &
 #%T__"5D" %+<$89 $## 	 #%T__"5D		s   7C "A"C $C,+C,c           	      l   [        U R                  5      (       a#  [        [        U R                  U R                  S9$ U R                  5       nU R                  S:X  a$  [        [        U R                  UU R                  S9$ U R                  S:X  a$  [        [        U R                  UU R                  S9$ U R                  S:X  aX  U R                  5       nU R                  5       nU R                  X!U5        [        [        U R                  UUU R                  US9$ [        SU R                  -  5      e)zReturn 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   rC   r   r~   r   r   r   r   rw   rP   )rc   r   r1   r   s       r'   build_analyzer_VectorizerMixin.build_analyzer  s    DMM""8dmmT[[QQ,,.
==F"(('	  ]]i'++'	  ]]f$,,.J++-H..zxP(("'%  @4==P r)   c                 Z   U R                   nUGb  [        U[        5      (       a  [        U5      n[        U[        5      (       d>  0 n[        U5       H*  u  p4UR                  XC5      U:w  d  M  SU-  n[        U5      e   UnOw[        UR                  5       5      n[        U5      [        U5      :w  a  [        S5      e[        [        U5      5       H#  nX6;  d  M
  S[        U5      U4-  n[        U5      e   U(       d  [        S5      eSU l        [        U5      U l        g SU l        g )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)
vocabularyrN   r   r   r   	enumerate
setdefaultrP   valuesri   rk   fixed_vocabulary_dictvocabulary_)rc   r   vocabrv   tmsgindicess          r'   _validate_vocabulary%_VectorizerMixin._validate_vocabulary  s   __
!*c**#J/
j'22%j1DA''-2@1D(o- 2 #
j//12w<3z?2$%LMMs:/A'O
OS  )o- 0  !ABB%)D"#J/D%*D"r)   c                     [        U S5      (       d,  U R                  5         U R                  (       d  [        S5      e[	        U R
                  5      S:X  a  [        S5      eg)z4Check if vocabulary is empty or missing (not fitted)r   z!Vocabulary not fitted or providedr   zVocabulary is emptyN)hasattrr   r   r   ri   r   rP   r   s    r'   _check_vocabulary"_VectorizerMixin._check_vocabulary  sT    t]++%%'))$%HIIt A%233 &r)   c                 l    U R                   u  pX:  a!  [        S[        U R                   5      -  5      eg)z'Check validity of ngram_range parameterzOInvalid value for ngram_range=%s lower boundary larger than the upper boundary.N)rg   rP   rO   )rc   ro   max_ms      r'   _validate_ngram_range&_VectorizerMixin._validate_ngram_range  s@    ''=ACFtGWGWCXY  r)   c                    U R                   b#  U R                  b  [        R                  " S5        U R                  b0  [        U R                  5      (       a  [        R                  " S5        U R                  S:w  a=  U R                  b0  [        U R                  5      (       a  [        R                  " S5        U R                  S:w  d  [        U R                  5      (       a{  U R                  b  [        R                  " S5        U R                  b&  U R                  S:w  a  [        R                  " S5        U R                   b  [        R                  " S	5        g g g )
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,   rg   r1   r   s    r'   _warn_for_unused_params(_VectorizerMixin._warn_for_unused_params  s   >>%$*<*<*HMM2
 (Xdmm-D-DMM1 &  ,''MM1 ==F"ht}}&=&=*2
 "".&&*::2 ~~)2 * '>r)   )r   r   r   N)__name__
__module____qualname____firstlineno____doc__rH   rI   rz   rC   rw   r~   r   r   r   r   r   r   r   r   r   r   __static_attributes__r+   r)   r'   rU   rU      sX    IJJx(M@<.8Y6%(1%N1f+<4(r)   rU   c                     ^  \ rS rSr% Sr0 S\" 1 Sk5      /_S\/_S\" 1 Sk5      /_S\" S	S
15      S\/_SS/_S\S/_S\S/_S\" S15      \S/_S\S/_S\	/_S\" 1 Sk5      \/_S\
" \S\R                  " \R                  5      R                  SS9/_SS/_S\" SS15      S/_SS/_SS _r\\S!'   S"S#S$SS%SSSS&S'S(S)S*SS%\R&                  S+.S, jr\" S%S-9S5S. j5       r\" S%S-9S5S/ j5       rS0 rS5S1 jrS2 rU 4S3 jrS4rU =r$ )6r   i.  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[   >   rZ   contentrX   r_   r`   >   rB   r5   replacer   r   r   Nr   booleanr/   r-   r1   rM   r   rg   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[   r_   r`   r   r   r/   r-   r1   r   rg   r,   r   r   r   r   r   c                    Xl         X l        X0l        X@l        X`l        Xpl        Xl        XPl        Xl        Xl	        Xl
        Xl        Xl        Xl        Xl        UU l        g r   )r[   r_   r`   r   r/   r-   r,   r   r   r1   r   rg   r   r   r   r   )rc   r[   r_   r`   r   r   r/   r-   r1   r   rg   r,   r   r   r   r   r   s                    r'   __init__HashingVectorizer.__init__  s\    ( 
 (*(" "*$$&	,
r)   prefer_skip_nested_validationc                     U $ )  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+   rc   Xys      r'   partial_fitHashingVectorizer.partial_fit!  s	    ( r)   c                     [        U[        5      (       a  [        S5      eU R                  5         U R	                  5         U R                  5       R                  XS9  U $ )r   BIterable over raw text documents expected, string object received.)r   )rN   rO   rP   r   r   _get_hasherfitr   s      r'   r   HashingVectorizer.fit7  sZ    * aT  	$$&""$q&r)   c                 t  ^ [        U[        5      (       a  [        S5      eU R                  5         U R	                  5       mU R                  5       R                  U4S jU 5       5      nU R                  (       a  UR                  R                  S5        U R                  b  [        XR                  SS9nU$ )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   4   >#    U  H  nT" U5      v   M     g 7fr   r+   ).0r%   r,   s     r'   	<genexpr>.HashingVectorizer.transform.<locals>.<genexpr>n  s     (D!3#!s   r   Fr   copy)rN   rO   rP   r   r   r   	transformr   datafillr   r   )rc   r   r,   s     @r'   r   HashingVectorizer.transformW  s     aT  	""$&&((((D!(DD;;FFKKN99 !))%8Ar)   c                 B    U R                  X5      R                  U5      $ )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_transformHashingVectorizer.fit_transformu  s    $ xx~''**r)   c                 V    [        U R                  SU R                  U R                  S9$ )Nstring)r   
input_typer   r   )r   r   r   r   r   s    r'   r   HashingVectorizer._get_hasher  s)    **..	
 	
r)   c                 v   > [         TU ]  5       nSUR                  l        SUR                  l        SUl        U$ NTF)super__sklearn_tags__
input_tagsr  two_d_arrayrequires_fitrc   tags	__class__s     r'   r  "HashingVectorizer.__sklearn_tags__  s5    w')!%&+#!r)   )r   r,   r   r`   r   r_   r[   r   r   rg   r   r/   r1   r   r   r-   r   )r   r   r   r   r   r   rO   r   rh   tupler   r   ra   iinfoint32maxr   r   __annotations__float64r   r   r   r   r   r   r   r  r   __classcell__r  s   @r'   r   r   .  s   vp$*<=>$SE$ 	$CDE$ 	*gy%9:D(K	$
 	i[$ 	4($ 	h%$ 	z9+.d;$ 	#t$ 	w$ 	Z ;<hG$ 	x!RXXbhh-?-C-CFST$ 	9+$ 	T4L)40$ 	9+$  	!$D , &jj%#J 5 6* 5 6><+(
 r)   r   )auto_wrap_output_keysc                     [         R                  " U 5      (       a<  U R                  S:X  a,  [        R                  " U R
                  U R                  S   S9$ [        R                  " U R                  5      $ )zACount the number of non-zero values for each feature in sparse X.csrr   )	minlength)	spissparseformatra   bincountr   shapediffindptr)r   s    r'   _document_frequencyr#    sJ    	{{1~~!((e+{{199
;;wwqxx  r)   c                   H  ^  \ rS rSr% SrS\R                  0rS\R                  0r0 S\	" 1 Sk5      /_S\
/_S\	" 1 Sk5      /_S	\	" S
S15      S\/_SS/_S\S/_S\S/_S\	" S15      \S/_S\
S/_S\/_S\	" 1 Sk5      \/_S\" \SSSS9\" \SSSS9/_S\" \SSSS9\" \SSSS9/_S\" \SSSS9S/_S\\" S 5      S/_S!S/_S"S#_r\\S$'   S%S&S'SS(SSSS)S*S+S,SSSS-\R.                  S..S/ jrS0 rS;S1 jrS2 rS<S3 jr\" S(S49S<S5 j5       rS6 rS7 r S<S8 jr!U 4S9 jr"S:r#U =r$$ )=r   i  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[   >   rZ   r   rX   r_   r`   >   rB   r5   r   r   r   r   Nr   r   r/   r-   r1   rM   r   rg   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[   r_   r`   r   r   r/   r-   r1   r   rg   r,   r&  r(  r)  r   r   r   c                    Xl         X l        X0l        X@l        X`l        Xpl        Xl        XPl        Xl        Xl	        Xl
        Xl        Xl        Xl        Xl        UU l        UU l        g r   )r[   r_   r`   r   r/   r-   r,   r   r   r1   r&  r(  r)  rg   r   r   r   )rc   r[   r_   r`   r   r   r/   r-   r1   r   rg   r,   r&  r(  r)  r   r   r   s                     r'   r   CountVectorizer.__init__  sc    * 
 (*(" "*$(&$
r)   c                    [        UR                  5       5      n[        R                  " [	        U5      UR
                  R                  S9n[        U5       H  u  nu  pgXRU'   XTU'   M     UR                  UR
                  SS9Ul        U$ )zWSort features by name

Returns a reordered matrix and modifies the vocabulary in place
r   clip)mode)	r   itemsra   emptyri   r   r   r   take)rc   r   r   sorted_features	map_indexnew_valtermold_vals           r'   _sort_featuresCountVectorizer._sort_features  sz    
 !!1!1!34HHS1I	(1/(B$G_d&t!(g )C NN1996N:	r)   c                    Uc  Uc  Uc  U[        5       4$ [        U5      n[        R                  " [	        U5      [
        S9nUb  XvU:*  -  nUb  XvU:  -  nUb  UR                  5       U:  a  [        R                  " UR                  SS95      R                  5       nX   * R                  5       SU n	[        R                  " [	        U5      [
        S9n
SU
[        R                  " U5      S   U	   '   U
n[        R                  " U5      S-
  n[        UR                  5       5       H  u  pX}   (       a  X   X,'   M  X,	 M     [        R                  " U5      S   n[	        U5      S:X  a  [        S5      eUSS2U4   $ )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#  ra   onesri   boolsumasarrayravelargsortzeroswherecumsumrh   r2  rP   )rc   r   r   highlowlimitdfsmasktfs	mask_indsnew_masknew_indicesr8  	old_indexkept_indicess                  r'   _limit_featuresCountVectorizer._limit_features  se    <CKEMce8O "!$wws3xt,4KD?3JDe!3**QUUU]+113C),,.v6IxxC5H59HRXXd^A&y12Diio)#J$4$4$67OD#.#9
 $	  8
 xx~a(|!X  L!!r)   c                 p   U(       a  U R                   nO[        5       nUR                  Ul        U R	                  5       n/ n/ n[        5       nUR                  S5        U H  n0 n	U" U5       H  n
 X:   nX;  a  SX'   M  X==   S-  ss'   M!     UR                  U	R                  5       5        UR                  U	R                  5       5        UR                  [        U5      5        M     U(       d  [        U5      nU(       d  [        S5      eUS   [        R                  " [        R                   5      R"                  :  a9  [$        (       a  [        SR'                  US   5      5      e[        R(                  nO[        R                   n[        R*                  " X\S9n[        R*                  " XlS9n[        R,                  " U[        R.                  S9n[0        R2                  " XuU4[        U5      S-
  [        U5      4U R4                  S9nUR7                  5         X=4$ ! [         a     GM  f = f)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_arrayrj   KeyErrorextendkeysr   ri   r   rP   ra   r  r  r  r   r  int64rA  
frombufferintcr  
csr_matrixr   sort_indices)rc   r%  fixed_vocabr   analyze	j_indicesr"  r   r%   feature_counterfeaturefeature_idxindices_dtyper   s                 r'   _count_vocabCountVectorizer._count_vocab  s   ))J %J)3););J&%%'	 "a C O"3<","5K"9784'494 ( _1134MM/0023MM#i.) !" j)J U  ":*...y C fVBZ(  HHM HHMJJy>	F8vRWW5MM'v;?C
O4**

 	
}O   s   2H&H&&
H54H5c                 (    U R                  U5        U $ )a  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   )rc   r%  r   s      r'   r   CountVectorizer.fit   s      	=)r)   r   c                    [        U[        5      (       a  [        S5      eU R                  5         U R	                  5         U R                  5         U R                  nU R                  nU R                  nU R                  (       ad  U R                  (       aS  U R                   HC  n[        [        [        R                  U5      5      (       d  M-  [        R                   " S5          O   U R#                  XR                  5      u  pxU R$                  (       a  UR&                  R)                  S5        U R                  (       d  UR*                  S   n	[        U[,        5      (       a  UOX9-  n
[        U[,        5      (       a  UOXI-  nX:  a  [        S5      eUb  U R/                  X5      nU R1                  XXU5      nUc  U R/                  X5      nXpl        U$ )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)rN   rO   rP   r   r   r   r&  r(  r)  r   r   r   anymapisupperr   r   rh  r   r   r   r   r   r:  rR  r   )rc   r%  r   r&  r(  r)  r8  r   r   n_docmax_doc_countmin_doc_counts               r'   r   CountVectorizer.fit_transform3  s   . mS))T  	""$$$&!!#((!!dnns3;;-..MM9  ( ))-9O9OP
;;FFKKN%%GGAJE&0&B&BFM&0&B&BFM, !PQQ'''6$$}\A #''6)r)   c                     [        U[        5      (       a  [        S5      eU R                  5         U R	                  USS9u  p#U R
                  (       a  UR                  R                  S5        U$ )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)ra  r   )rN   rO   rP   r   rh  r   r   r   )rc   r%  _r   s       r'   r   CountVectorizer.transformw  sc      mS))T  	    D A;;FFKKNr)   c           
         U R                  5         [        USS9nUR                  S   n[        R                  " [        U R                  R                  5       5      5      n[        R                  " [        U R                  R                  5       5      5      nU[        R                  " U5         n[        R                  " U5      (       aD  [        U5       Vs/ s H-  nXQUSS24   R                  5       S      R                  5       PM/     sn$ [        U5       Vs/ s H0  nU[        R                  " XSS24   5         R                  5       PM2     sn$ s  snf s  snf )a  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 terms.
r  )accept_sparser   Nr   )r   r   r   ra   arrayrh   r   r[  r   rC  r  r  rk   nonzerorB  flatnonzero)rc   r   	n_samplestermsr   inverse_vocabularyrv   s          r'   inverse_transform!CountVectorizer.inverse_transform  s#    	 /GGAJ	d..33567((4 0 0 7 7 9:;"2::g#67;;q>> y))A #QT7??#4Q#78>>@)  y))A #2>>!qD'#:;AAC) 
s   4E7Ec                     U R                  5         [        R                  " [        U R                  R                  5       [        S5      S9 VVs/ s H  u  p#UPM	     snn[        S9$ s  snnf )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.
r   )keyr/  )r   ra   rA  r   r   r2  r   object)rc   input_featuresr   rv   s       r'   get_feature_names_out%CountVectorizer.get_feature_names_out  sW     	 zz!$"2"2"8"8":
1NON41QNO
 	
Os   A(
c                 h   > [         TU ]  5       nSUR                  l        SUR                  l        U$ r  )r  r  r	  r  r
  r  s     r'   r   CountVectorizer.__sklearn_tags__  s-    w')!%&+#r)   )r,   r   r`   r   r_   r[   r   r&  r)  r(  rg   r/   r1   r   r   r-   r   r   )NNNr   )%r   r   r   r   r   r   UNUSED'_CountVectorizer__metadata_request__fit-_CountVectorizer__metadata_request__transformr   rO   r   rh   r  r   r   r   r   r   r   r   r  ra   r\  r   r:  rR  rh  r   r   r   r   r  r  r  r   r  r  s   @r'   r   r     s>   @H  /0@0G0GH%46F6M6M$N!$*<=>$SE$ 	$CDE$ 	*gy%9:D(K	$
 	i[$ 	4($ 	h%$ 	z9+.d;$ 	#t$ 	w$ 	Z ;<hG$ 	ZAf5Xq$v6
$  	ZAf5Xq$v6
!$( 	(AtFCTJ)$* 	w
: 6=+$, 	9+-$. 	/$D : &hh'%N%"N?B& 5A 6AF8B
& r)   r   c                  @    [         R                   " [        S5      5      $ )zEConstruct an array.array of a type suitable for scipy.sparse indices.rv   )ry  rO   r+   r)   r'   rX  rX    s    ;;s3x  r)   c                      ^  \ rS rSr% Sr\" SS15      S/S/S/S/S.r\\S'   SS	S	S
S.S jr	\
" S	S9SS j5       rSS jrU 4S jrSrU =r$ )r   i  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                4    Xl         X l        X0l        X@l        g r   r  )rc   r   r  r  r  s        r'   r   TfidfTransformer.__init__]  s    	$(r)   r   c                    [        XS[        (       + S9n[        R                  " U5      (       d  [        R                  " U5      nUR
                  [        R                  [        R                  4;   a  UR
                  O[        R                  nU R                  (       a  UR                  u  pE[        U5      nUR                  USS9nU[        U R                  5      -  nU[        U R                  5      -  n[        R                   " XdUS9U l        U =R"                  U-  sl        [        R$                  " U R"                  U R"                  S9  U =R"                  S-  sl        U $ )a  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)rx  accept_large_sparseFr   )
fill_valuer   )outr+  )r   r   r  r  r_  r   ra   r  float32r  r   r#  astypefloatr  int	full_likeidf_log)rc   r   r   r   r|  ru  dfs          r'   r   TfidfTransformer.fitc  s    ( >9}
 {{1~~a A77rzz2::&>>BJJ<<77LI$Q'B5u-B %((BT__--I RUKDIIIOIFF499$)),IIIr)   c           	      D   [        U 5        [        U US[        R                  [        R                  /USS9n[
        R                  " U5      (       d  [
        R                  " XR                  S9nU R                  (       a@  [        R                  " UR                  UR                  5        U=R                  S-  sl        [        U S5      (       a,  U=R                  U R                  UR                     -  sl        U R                  b  [!        XR                  SS9nU$ )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)rx  r   r   resetr/  r+  r  r   )r   r   ra   r  r  r  r  r_  r   r  r  r   r   r  r   r   r   )rc   r   r   s      r'   r   TfidfTransformer.transform  s    " 	::rzz*
 {{1~~aww/AFF166166"FFcMF4   FFdii		**F99 !))%8Ar)   c                 l   > [         TU ]  5       nSUR                  l        SS/UR                  l        U$ )NTr  r  )r  r  r	  sparsetransformer_tagspreserves_dtyper  s     r'   r  !TfidfTransformer.__sklearn_tags__  s6    w')!% 2;I0F-r)   )r  r   r  r  r  r   )T)r   r   r   r   r   r   r   r   r  r   r   r   r   r  r   r  r  s   @r'   r   r     sv    ~B T4L)40; k"	$D   $TdQV ) 5- 6-^)V r)   r   c                   b  ^  \ rS rSr% Sr0 \R                  Er\\S'   \R                  \
" SS15      S/S/S/S/S.5        S	S
SSSSSSSSSSSSSS\R                  SSSSS.U 4S jjr\S 5       r\R                   S 5       rS r\" SS9SU 4S jj5       rSU 4S jjrU 4S jrU 4S jrSrU =r$ )r   i  a5   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   r  r   r   r5   Tr   r   r   r+  r   F)r[   r_   r`   r   r   r/   r-   r,   r1   r   rg   r&  r(  r)  r   r   r   r   r  r  r  c                x   > [         TU ]  UUUUUUUUU	U
UUUUUUUS9  UU l        UU l        UU l        UU l        g )N)r[   r_   r`   r   r   r/   r-   r,   r1   r   rg   r&  r(  r)  r   r   r   )r  r   r   r  r  r  )rc   r[   r_   r`   r   r   r/   r-   r,   r1   r   rg   r&  r(  r)  r   r   r   r   r  r  r  r  s                         r'   r   TfidfVectorizer.__init__  si    2 	%'%!'#%!# 	 	
& 	$(r)   c                     [        U S5      (       d"  [        U R                  R                   S35      eU R                  R
                  $ )zsInverse 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  TfidfVectorizer.idf_  sL     tX&& >>**+ ,E E  {{r)   c                    U R                   (       d  [        S5      e[        U S5      (       d9  [        U R                  U R                   U R
                  U R                  S9U l        U R                  5         [        U S5      (       aN  [        U R                  5      [        U5      :w  a,  [        S[        U5      [        U R                  5      4-  5      eXR                  l        g )Nz+`idf_` cannot be set when `user_idf=False`.r  r  r   z5idf length = %d must be equal to vocabulary size = %d)r  rP   r   r   r   r  r  r  r   ri   r   r   r  )rc   values     r'   r  r    s    ||JKKtX&& +YY??!..	DK 	!!#4''4##$E
2 K5z3t#789  !r)   c                     U R                   [        ;  a:  [        R                  " SR	                  [        U R                   5      [
        5        g g )NzKOnly {} 'dtype' should be used. {} 'dtype' will be converted to np.float64.)r   r   r   r   r  UserWarningr   s    r'   _check_paramsTfidfVectorizer._check_params  s7    ::\)MM..4f\4::.N *r)   r   c                   > U R                  5         U R                  5         [        U R                  U R                  U R
                  U R                  S9U l        [        TU ]%  U5      nU R                  R                  U5        U $ )a  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.
r  )r  r   r   r   r  r  r  r  r  r   r   rc   r%  r   r   r  s       r'   r   TfidfVectorizer.fit  sm    " 	$$&&LL**	
 G!-0r)   c                   > U R                  5         [        U R                  U R                  U R                  U R
                  S9U l        [        TU ]!  U5      nU R                  R                  U5        U R                  R                  USS9$ )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.
r  Fr  )r  r   r   r  r  r  r  r  r   r   r   r  s       r'   r   TfidfVectorizer.fit_transform  sx    & 	&LL**	
 G!-0 {{$$QU$33r)   c                 j   > [        U SS9  [        TU ]	  U5      nU R                  R                  USS9$ )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  )rc   r%  r   r  s      r'   r   TfidfVectorizer.transform?  s9      	"GHGm,{{$$QU$33r)   c                 v   > [         TU ]  5       nSUR                  l        SUR                  l        SUl        U$ r  )r  r  r	  r  r
  
_skip_testr  s     r'   r   TfidfVectorizer.__sklearn_tags__T  s4    w')!%&+#r)   )r  r   r  r  r  r   )r   r   r   r   r   r   r   r   r  updater   ra   r  r   propertyr  setterr  r   r   r   r   r  r   r  r  s   @r'   r   r     s   L\ $No&L&L#MDM!!t-t4!{$+&K		
 &jj//) /)h     
[[! !, 5 684@4* r)   r   )NF)NNNNNN)=r   ry  rH   r;   r   collectionsr   collections.abcr   	functoolsr   numbersr   operatorr   numpyra   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"   rS   rU   r   r#  r   rX  r   r   r+   r)   r'   <module>r     s    =
  	   # #      * V V ' % R R # X X   +	8 ,^P@?0B&b bJh&ThV!j& jZ!
q*MQUqhRo Rr)   