`L ih.dZddlZddlZddlZddlZddlmZddlmZddl m Z ddl m Z ddl mZddlZddlmZddlmZd d lmZmZmZmZd d lmZd d lmZd d lm Z m!Z!m"Z"m#Z#d dl$m%Z%d dl&m'Z'm(Z(m)Z)m*Z*ddl+m,Z,ddl-m.Z.gdZ/d'dZ0 d(dZ1dZ2dZ3dZ4dZ5GddZ6Gddee6edZ7dZ8Gd d!e6eZ9d"Z:Gd#d$eeedZ;Gd%d&e9Z|r|j}|||}|S)aChain 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)docaccent_functionr$s e/mnt/ssd/data/python-lab/Trading/venv/lib/python3.12/site-packages/sklearn/feature_extraction/text.py _preprocessr(*s'& iik"c" Jc|||}| ||}|S|||}|||}|| |||}|S||}|S)aChain 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 tokenizerngrams preprocessordecoder stop_wordss r'_analyzer2Dsy<clsm J  #s#C  C.C  %S*- JSk Jr)c  |jdd|S#t$rTtjd|}dj |Dcgc]}tj |r|ncc}wc}cYSwxYw)aTransform 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. ASCIIstrict)errorsNFKD)encodeUnicodeEncodeError unicodedatarjoin combining)s normalizedcs r'r!r!ssl,P * P **615 ww:Na[5J5J15MNNOOPs!.A4A% A% $ A43A4cptjd|}|jddjdS)aTransform 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. r7r4ignore)r;rr9decode)r> nkfd_forms r'r r s4(%%fa0I   GX . 5 5g >>r)cltjdtjjd|S)a8Basic 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 )recompileUNICODEsub)r>s r'r"r"s& ::l"** 5 9 9#q AAr)cp|dk(rtSt|trtd|z|yt |S)Nenglishznot a built-in stop list: %s)r isinstancestr ValueError frozenset)stops r'_check_stop_listrSs= y!! D# 7$>?? r)ceZdZdZej dZdZddZdZ dZ dZ d Z d Z d Zd Zd ZdZdZdZy)_VectorizerMixinz?Provides common code for text vectorizers (tokenization logic).z\s\s+cl|jdk(r&t|d5}|j}dddn|jdk(r|j}t|tr&|j |j |j}|tjur td|S#1swY^xYw)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. filenamerbNfilez?np.nan is an invalid document, expected byte or unicode string.) inputopenreadrNbytesrCencoding decode_errornpnanrP)selfr%fhs r'rCz_VectorizerMixin.decodes :: #c4 Bggi  ZZ6 !((*C c5 !**T]]D,=,=>C "&&=Q    s B**B3Nc t||Dcgc] }||vs| }}|j\}}|dk7r|}|dk(rt|}|dz }ng}t|}|j}dj} t |t |dz|dzD],} t || z dzD]} || || | | z.|Scc}w)zATurn tokens into a sequence of n-grams after stop words filteringrrG) ngram_rangelistlenappendr<rangemin) rbtokensr1wmin_nmax_noriginal_tokensn_original_tokens tokens_append space_joinnis r' _word_ngramsz_VectorizerMixin._word_ngramss  !!'?A1J+>a?F?'' u A:$Ozo.  #O 4 #MMMJ5#eai1BQ1F"GH J014q89JA!*_QQ-G"HIJ J 1@s B5B5cD|jjd|}t|}|j\}}|dk(rt |}|dz }ng}|j }t |t|dz|dzD]&}t ||z dzD]}|||||z(|S)z;Tokenize text_document into a sequence of character n-gramsrGr) _white_spacesrKrgrerfrhrirj) rb text_documenttext_lenrmrnr. ngrams_appendrsrts r' _char_ngramsz_VectorizerMixin._char_ngrams s**..sMB }%'' u A:-(F QJEF uc%!)X\:; 8A8a> %>> ! 4#5#56   ! #,  $$$r)c,t|jS)zBuild or fetch the effective stop words list. Returns ------- stop_words: list or None A list of stop words. )rSr1rbs r'get_stop_wordsz_VectorizerMixin.get_stop_wordsns 00r)ct|jt|ddk(ry t}|xsdD]6}t |||}|D]}||vs|j |8t|j|_|r!tjdt|z| S#t$rt|j|_YywxYw)aCheck 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) idr1getattrsetrfaddrwarningswarnsorted Exception)rbr1 preprocesstokenize inconsistentrlrktokens r'_check_stop_words_consistencyz._VectorizerMixin._check_stop_words_consistencyxs doo '$0@$"G G 5L%2 0hz!}56#0EJ.$((/0 0 #%T__"5D  "%+<$89 $# # #%T__"5D   s3B/AB//#CCcvt|jr&tt|j|jS|j }|jdk(r'tt|j ||jS|jdk(r'tt|j||jS|jdk(r\|j}|j}|j|||tt|j|||j|Std|jz)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,r0char)r.r/r0char_wbword)r.r-r/r0r1z.%s is not a valid tokenization scheme/analyzer) rr,rr2rCrr{rrrrrurP)rbrr1rs r'build_analyzerz_VectorizerMixin.build_analyzers DMM "8dmmT[[Q Q,,. ==F "(('  ]]i '++'  ]]f $,,.J++-H  . .z:x P(("' %  @4==P r)c0|j}|t|tr t|}t|ts=i}t |D]*\}}|j |||k7sd|z}t||}nst|j}t|t|k7r tdtt|D]!}||vsdt||fz}t||s tdd|_ t||_ yd|_ y)Nz Duplicate term in vocabulary: %rz%Vocabulary contains repeated indices.z/Vocabulary of size %d doesn't contain index %d.zempty vocabulary passed to fitTF) vocabularyrNrrr enumerate setdefaultrPvaluesrgrifixed_vocabulary_dict vocabulary_)rbrvocabrttmsgindicess r'_validate_vocabularyz%_VectorizerMixin._validate_vocabularys__  !*c*#J/ j'2%j1.DAq''1-2@1D(o-.# j//12w<3z?2$%LMMs:/.A'O OS)o- . !ABB%)D "#J/D %*D "r)ct|ds'|j|js tdt |j dk(r t dy)z4Check if vocabulary is empty or missing (not fitted)rz!Vocabulary not fitted or providedrzVocabulary is emptyN)hasattrrrrrgrrPrs r'_check_vocabularyz"_VectorizerMixin._check_vocabularysQt]+  % % '))$%HII t A %23 3 &r)cn|j\}}||kDr!tdt|jzy)z'Check validity of ngram_range parameterzOInvalid value for ngram_range=%s lower boundary larger than the upper boundary.N)rerPrO)rbrmmax_ms r'_validate_ngram_rangez&_VectorizerMixin._validate_ngram_rangesD'' u 5=ACFtGWGWCXY  r)c|j!|jtjd|j*t |j rtjd|jdk7r6|j*t |j rtjd|j dk7st |j rt|jtjd|j$|jdk7rtjd|jtjd yyy) NzMThe parameter 'token_pattern' will not be used since 'tokenizer' is not None'zKThe parameter 'preprocessor' will not be used since 'analyzer' is callable'rrzJThe parameter 'ngram_range' will not be used since 'analyzer' is callable'rzFThe 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-rrrr/rr,rer1rs r'_warn_for_unused_paramsz(_VectorizerMixin._warn_for_unused_paramss >> %$*<*<*H MM2     (Xdmm-D MM1     &  ,' MM1  ==F "ht}}&=* 2 "".&&*:: 2~~) 2*'>r)N)__name__ __module__ __qualname____doc__rHrIrwrCrur{rrrrrrrrrrr+r)r'rUrUsZIBJJx(M@<.8Y6%(1%N1f+<4(r)rUceZdZUdZidehdgdegdehdgdedd hd egd d gd ed gded gdedhed gded gdegdehdegde e de je jjdgdd gdeddhd gdd gddZeed <d!d"d#d d$d d d d%d&d'd(d)dd$e j$d*d+Zed$,d3d-Zed$,d3d.Zd/Zd3d0Zd1Zfd2ZxZS)4raConvert 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 `. 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) rZ>rYcontentrWr^r_>rBr5replacerrrNrbooleanr/r-r1rMrrer,>rrr n_featuresrleftclosedbinarynorml1l2alternate_signdtype no_validation_parameter_constraintsrutf-8r5TrrriF)rZr^r_rrr/r-r1rrer,rrrrrc||_||_||_||_||_||_| |_||_| |_||_ | |_ | |_ | |_ ||_ ||_||_yr)rZr^r_rr/r-r,rrr1rrerrrr)rbrZr^r_rrr/r-r1rrer,rrrrrs r'__init__zHashingVectorizer.__init__sz(   (*("  "*$$&  , 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+rbXys r' partial_fitzHashingVectorizer.partial_fit!s ( r)ct|tr td|j|j |j j |||S)rBIterable over raw text documents expected, string object received.)r)rNrOrPrr _get_hasherfitrs r'rzHashingVectorizer.fit7sY* a T  $$& ""$ qA& r)cdt|tr td|j|j |j j fd|D}|jr|jjd|jt||jd}|S)aTransform 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. rc3.K|] }|ywrr+).0r%r,s r' z.HashingVectorizer.transform..ns(D3#(DsrFrcopy) rNrOrPrrr transformrdatafillrr)rbrr,s @r'rzHashingVectorizer.transformWs a T  ""$&&(     ( ((D!(D D ;; FFKKN 99 !$))%8Ar)cD|j||j|S)aTransform 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. )rrrs r' fit_transformzHashingVectorizer.fit_transformus$xx1~''**r)c\t|jd|j|jS)Nstring)r input_typerr)rrrrrs r'rzHashingVectorizer._get_hashers)**..   r)cvt|}d|j_d|j_d|_|SNTF)super__sklearn_tags__ input_tagsr two_d_array requires_fitrbtags __class__s r'rz"HashingVectorizer.__sklearn_tags__s5w')!%&+#! r)r)rrrrrrOrrftuplerrr`iinfoint32maxrr__annotations__float64rr rrrrrr __classcell__rs@r'rr.svp$*<=>$SE$ $CDE$ *gy%9:D(K $ i[ $ 4( $ h%$ z9+.d;$ #t$ w$ Z ;<+( r)r)auto_wrap_output_keysctj|r=|jdk(r.tj|j |j dStj|jS)zACount the number of non-zero values for each feature in sparse X.csrr) minlength) spissparseformatr`bincountrshapediffindptr)rs r'_document_frequencyr sH {{1~!((e+{{199 ;;wwqxx  r)cXeZdZUdZdej iZdej iZidehdgde gdehdgded d hd e gd d gde d gde d gdedhe d gde d gde gdehde gde eddde edd dgde eddde edd dgde edd dd gdeedd gd d gd!d"Zeed#<d$d%d&d d'd d d d(d)d*d+dd d d,ej,d-d.Zd/Zd9d0Zd1Zd:d2Zed'3d:d4Zd5Zd6Zd:d7Z fd8Z!xZ"S);ra 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 `. 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_documentsrZ>rYrrWr^r_>rBr5rrrrNrrr/r-r1rMrrer,>rrrmax_dfrrbothrrmin_df max_featuresr__iter__rrrrrrr5Trrr?F)rZr^r_rrr/r-r1rrer,rrrrrrc||_||_||_||_||_||_| |_||_| |_||_ | |_ | |_ ||_ | |_ ||_||_||_yr)rZr^r_rr/r-r,rrr1rrrrerrr)rbrZr^r_rrr/r-r1rrer,rrrrrrs r'rzCountVectorizer.__init__s*   (*("  "*$  (&$  r)c$t|j}tjt ||j j }t|D]\}\}}|||<|||<|j|j d|_|S)zgSort features by name Returns a reordered matrix and modifies the vocabulary in place rclip)mode) ritemsr`emptyrgrrrtake)rbrrsorted_features map_indexnew_valtermold_vals r'_sort_featureszCountVectorizer._sort_featuress !!1!1!34HHS1I (1/(B ) $G_dG&Jt !(Ig  )NN1996N: r)c||| |tfSt|}tjt |t }||||kz}||||k\z}||j |kDrtj|j dj}|| jd|} tjt |t } d| tj|d| <| }tj|dz } t|jD]\} } || r | | || <|| =tj|d}t |dk(r td|dd|fS)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. Nrr)axisTrzFAfter pruning, no terms remain. Try a lower min_df or a higher max_df.)rr r`onesrgboolsumasarrayravelargsortzeroswherecumsumrfrrP)rbrrhighlowlimitdfsmasktfs mask_indsnew_mask new_indicesr old_index kept_indicess r'_limit_featureszCountVectorizer._limit_featuressz  F-8vRWW5 MM Y 'v;?C O4**  1}O s-H H&%H&c(|j||S)anLearn 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)rbr rs r'rzCountVectorizer.fit s =) r)rcpt|tr td|j|j |j |j }|j}|j}|jrW|jrK|jD]<}tttj|s'tj dn|j#||j\}}|j$r|j&j)d|js|j*d} t|t,r|n|| z} t|t,r|n|| z} | | kr td||j/||}|j1||| | |}||j/||}||_|S)aLearn 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. rzyUpper case characters found in vocabulary while 'lowercase' is True. These entries will not be matched with any documentsrrz-max_df corresponds to < documents than min_df)rNrOrPrrrrrrrrranymapisupperrrrMrrrrrr!r8r) rbr rrrrrrrn_doc max_doc_count min_doc_counts r'rzCountVectorizer.fit_transform3s. mS )T  ""$ $$& !!#((  ! !dnn s3;;-.MM9  ))-9O9OP A ;; FFKKN%%GGAJE&0&BFQVM&0&BFQVM}, !PQQ''':6$$:}m\A#'':6)D r)ct|tr td|j|j |d\}}|j r|j jd|S)aTransform 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. rT)rFr)rNrOrPrrMrrr)rbr _rs r'rzCountVectorizer.transformwsb mS )T     D A1 ;; FFKKNr)c |jt|d}|jd}tjt |j j}tjt |j j}|tj|}tj|rBt|Dcgc]-}|||ddfjdj/c}St|Dcgc]/}|tj||ddfj1c}Scc}wcc}w)aOReturn 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_sparserNr)rrrr`arrayrfrr@rr)rrrinonzeror( flatnonzero)rbr n_samplestermsrinverse_vocabularyrts r'inverse_transformz!CountVectorizer.inverse_transforms   /GGAJ d..33567((4 0 0 7 7 9:;"2::g#67 ;;q>y)#1QT7??#4Q#78>>@ y)#2>>!AqD'#:;AAC   s 2E 4Ec|jtjt|jj t dDcgc]\}}| c}}tScc}}w)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)rr`r'rrrrobject)rbinput_featuresrrts r'get_feature_names_outz%CountVectorizer.get_feature_names_outsS  zz!$"2"2"8"8": 1 N O41aQ O  Os A+ cht|}d|j_d|j_|Sr)rrrrrrs r'rz CountVectorizer.__sklearn_tags__s-w')!%&+# r))NNNr)#rrrrrUNUSED'_CountVectorizer__metadata_request__fit-_CountVectorizer__metadata_request__transformrrOrrfrrrrrrrrrr`rArr!r8rMrr rrr`rerrrs@r'rrs>@H /0@0G0GH%46F6M6M$N!$*<=>$SE$ $CDE$ *gy%9:D(K $ i[ $ 4( $ h%$ z9+.d;$ #t$ w$ Z ;tjtdS)zEConstruct an array.array of a type suitable for scipy.sparse indices.rt)rZrOr+r)r'r=r=s ;;s3x  r)ceZdZUdZeddhdgdgdgdgdZeed<dddd dd Ze d dd Z dd Z fdZ xZ S)ruTransform 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 `. 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) rrNrruse_idf smooth_idf sublinear_tfrTFc<||_||_||_||_yrrl)rbrrmrnros r'rzTfidfTransformer.__init__]s  $(r)rct||dt }tj|stj|}|j t jt jfvr |j nt j}|jr|j\}}t|}|j|d}|t|jz }|t|jz }t j ||||_|xj"|zc_t j$|j"|j"|xj"dz c_|S)afLearn 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. )rcsc)rYaccept_large_sparseFr) fill_valuer)outr)rrrrrDrr`rfloat32rmrr astypefloatrnint full_likeidf_log)rbrrrr]rWdfs r'rzTfidfTransformer.fitcs(  !>9} {{1~ a A77rzz2::&>>BJJ <<77LIq$Q'B5u-B %( (B T__- -I  RIUKDI IIOI FF499$)) , II I r)c4t|t||dtjtjg|d}t j |s!t j||j}|jr?tj|j|j|xjdz c_ t|dr,|xj|j|jzc_ |jt!||jd}|S)aTransform 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. rF)rYrrresetrrr|r)rrr`rrwrrrDrror}rrr|rrr)rbrrs r'rzTfidfTransformer.transforms"    ::rzz*  {{1~ aqww/A    FF166166 " FFcMF 4  FFdii * *F 99 !$))%8Ar)clt|}d|j_ddg|j_|S)NTrrw)rrrsparsetransformer_tagspreserves_dtypers r'rz!TfidfTransformer.__sklearn_tags__s6w')!%2;I0F- r)r)T)rrrrrrrrrr rrrrrs@r'rrsv~BT4L)40; k" $D $TdQV) 5-6-^)Vr)rcPeZdZUdZiej Zeed<eje ddhdgdgdgdgddd d dd ddd dd dddddde jdd d ddfd Z e dZejdZdZed dfd Zdfd ZfdZfdZxZS)ra"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 `. 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) rrrNrrlrrr5TrrrrrF)rZr^r_rrr/r-r,r1rrerrrrrrrrmrnroc~t|||||||||| | | | | ||||||_||_||_||_y)N)rZr^r_rrr/r-r,r1rrerrrrrr)rrrrmrnro)rbrZr^r_rrr/r-r,r1rrerrrrrrrrmrnrors r'rzTfidfVectorizer.__init__si2 %'%!'#%!#  &  $(r)ct|ds"t|jjd|jj 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.)rrrrrr|rs r'r|zTfidfVectorizer.idf_sItX& >>**+,EE {{r)c|js tdt|dsrs=  ##*VV'%RR#XX + 8  ,^P@?0B&bbJ h& ThV !j& jZ! q*MQUqhRoRr)