TfidfVectorizer: TF-IDF Vectorizer scikit-learn

Tfidfvectorizer TF-IDF Vectorizer scikit-learn
Spread the love

In this article, you will learn everything about TfidfVectorizer. You can learn about what is TfidfVectorizer along with examples, codes, formulas and the concept of TfidfVectorizer. You will also learn about calculating td-idf values using sklearn’s Tfidfvectorizer.


What is TfidfVectorizer?

TfidfVectorizer converts a collection of raw documents to a matrix of TF-IDF features. Each document is represented as a set of words, and the number of times each word appears in the collection is used to compute its TF-IDF feature.

The tfidf_vectorizer class implements a vectorizer for calculating term frequency/inverse document frequency (TF/IDF), which can be used as a measure for modeling the importance of terms within documents. It takes in raw texts and returns an array of feature vectors for each input text.


Example: How TfidfVectorizer Works?

This is an example to show how TfidfVectorizer works and its output. It uses the text5_train dataset to perform tf-idf on the train data. What we get after applying TfidfVectorizer is a matrix of dimensions (2397, 75889). We have 2397 documents and 75889 different words in our corpus. The sklearn library uses a sparse matrix format for storing this matrix which means that it only stores the non-zero values and indices. The above matrix looks like the following:

(0, 34) 0.0137375136421

(0, 111) 0.0885292502069

(0, 646) 0.0556173066805

(0, 962) 0.0556173066805

(0, 2249)

The following example shows how to use TfidfVectorizer to perform tf-idf on the train data. It uses the text5_train dataset, which was created in the previous section.

“`python

import pandas as pd

from sklearn import datasets, metrics, preprocessing, feature_extraction, linear_model

from sklearn.feature_extraction.text import TfidfVectorizer

It uses the text5_train dataset to perform tf-idf on the train data.

To understand tf-idf, let’s take a look at the following example. A document is made up of words, each word is assigned a weight from 1 to 100 (where 1 is the most important and 100 means it has no importance in that particular context). Given this information, TfidfVectorizer will output a vector for each document in which the values correspond to these weights.

  • Vectorization: tfidfVectorizer performs this task by first creating an array where each value represents a word in your training data set and its corresponding weight.*

What we get after applying TfidfVectorizer is a matrix of dimensions (2397, 75889).

This is where the magic happens.

Once you have applied TfidfVectorizer to your corpus, what you get is a sparse matrix of dimensions (2397, 75889). This means that there are only non-zero values in this matrix. The first dimension represents the document IDs and second dimension represents our words or terms in the corpus. Each row of this matrix contains information about how often was a given word used across all documents in our corpus along with TFIDF value for that term/word (float).

So basically we can say TfidfVectorizer has turned our text data into numerical form so that it can be used by other ML algorithms such as LDA

In this example, we have 2397 documents and 75889 different words in our corpus.

The sklearn library uses a sparse matrix format for storing this matrix which means that it only stores the non-zero values and indices. This makes the process of loading and saving the model extremely fast as well as saves memory space. The sparse format also allows us to use less memory when dealing with large datasets.

The above matrix looks like following –

1 1 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387

(0, 34) 0.0137375136421

In this example, the document id is 0 and word id is 34. The tf-idf weight for the words in this document are shown here:

(0, 111) 0.0885292502069

You can check the output of ‘tfidfVectorizer’ with the following code:

>>> import sklearn.feature_extraction.text as text

>>> vectorizer = text.TfidfVectorizer(min_df=5, stop_words=’english’, ngram_range=(1, 2), max_features=4000)

(0, 646) the 0.0556173066805

This is the index of the word “the” in the vocabulary vector. According to this row, it has a value of 0.0556173066805 which means that this word appears 556 times more often than other words in our corpus. This value also indicates how important this word is for your document since it should have higher TF-IDF score compared with other words in your corpus. If you want to know more about TF-IDF check out this link: https://www2.csaille pourcentage ça n’existe pas !

(0, 962) 0.0556173066805

In this section, we will present an example of TfidfVectorizer and its output.

In the code below, we will show you how to create a tfidf vectorizer using text5_train data set in python 3.6.8 using sklearn module. It also shows how to compute tf-idf for each word in the corpus (all words having non-zero values). The input variable is a matrix where each row represents a document and columns are words from that document (dictionary). This dictionary can be obtained from nltk package or can be created manually by listing out all unique terms that appear in all documents of your corpus (which is generally done when building corpora).

(0, 2249) 0.0556173066805

In the following matrix,

(0, 34) 0.0137375136421

means that when the word ‘i’ appears in a sentence of length 34 letters, its tfidf vector is (0, 34) and it’s frequency is 1/34.

The above matrix represents how frequently each word appears in the dataset.


How sklearn’s Tfidfvectorizer Calculates tf-idf Values?

The TfidfVectorizer is a class in the sklearn library. It calculates tf-idf values (term frequency-inverse document frequency) for each string in a corpus, or set of documents.

The TfidfVectorizer works by chopping up the text into individual words and counting how many times each word occurs in each document. Then it takes that number and divides it by the total number of words that occur in all of the documents combined—so if there are 100 words in one document and 500 words in another, then if “word A” occurs twice in one and five times in another, word A’s tf value would be 2/100=0.02 and 5/500=0.1 respectively. Then it will take these two numbers (tf) and multiply them by an inverse document count multiplier (idf), which means that words that occur frequently overall but not frequently within single documents will be downweighted relative to extremely rare words with high frequencies within single documents.


Sklearn’s Forumula to Calculate TF_IDF

tf-idf stands for term frequency-inverse document frequency. This is a metric used to determine how important a word is to a document or corpus. It is calculated using the formula:

tfidf = log(N/df) * ln(1+M/T), where N is the number of occurrences of the word in the corpus, Df is the total number of documents in the collection, M is the number of times the word occurs in this document, and T is the total number of words in this particular document.

In sklearn’s TfidfVectorizer, this formula is applied iteratively on each document as follows:

For each text token: Calculate tfidf scores using all terms in other documents as features; Find weighting coefficients that maximize cosine similarity between tfidf vectorized documents and training set vectors; Sort by descending similarity; Return top N vectors with highest weights.


Spread the love

Posted on July 6, 2022 in Search Engine Optimization

Author: Jobin John

Jobin is the founder & CEO of Egochi, a United States digital marketing agency specializing in SEO and content marketing that helps businesses grow online. He is well known & respected for his expertise in the search engine optimization industry and has helped a huge number of local businesses grow their business.
Back to Top
Top