When using TF-IDF (Term Frequency–Inverse Document Frequency) in libraries like scikit-learn, the main hyperparameters depend on your goal, dataset size, and text preprocessing. Here's a breakdown of the key hyperparameters and how to tune them:
Key TF-IDF Hyperparameters
max_features
Limits the vocabulary size to the top n features ordered by term frequency.
User
The number of unique words in the corpus is 24,017
Assistant
Got it — your corpus has 24,017 unique words, so you’re dealing with a moderate vocabulary size.
Here’s how I’d adjust TF-IDF hyperparameters based on that:
tfidf = TfidfVectorizer(
max_features=None, # Keep all words since 24k is manageable
ngram_range=(1, 2), # Include unigrams + bigrams for richer context
min_df=2, # Remove words appearing in < 2 docs
max_df=0.85, # Remove very common words (in > 85% of docs)
stop_words='english', # Remove common English stopwords
sublinear_tf=True, # Use 1 + log(tf) for better scaling
norm='l2', # Normalize feature vectors
use_idf=True, # Apply inverse document frequency
smooth_idf=True # Prevent division by zero in IDF
)
Typical values: 5,000 – 50,000 depending on dataset size.
Use case: Prevents overfitting and reduces dimensionality.
ngram_range
Controls the size of token combinations.
(1,1) → Unigrams only.
(1,2) → Unigrams + bigrams.
Recommendation: Start with (1,1), try (1,2) if you want phrases or context.
Small datasets: Lower max_features, maybe (1,1) n-grams.
Large datasets: Higher max_features, allow bigrams (1,2).
Use grid search or cross-validation to test combinations.
For deep learning models, sometimes no normalization works better since embeddings handle scaling differently.
If you want, I can give you a hyperparameter tuning grid for TF-IDF in scikit-learn so you can use it with GridSearchCV or RandomizedSearchCV.
Do you want me to create that for you?
Reasoning
max_features=None:
24k isn’t too big for most ML models, so we can use the full vocabulary unless memory or computation is tight.
If you run into performance issues, limit to top 10k–15k features.
ngram_range=(1,2):
Bigrams capture phrases like "new york" or "machine learning" that unigrams miss.
min_df=2:
Removes rare terms that might be typos or irrelevant. If your dataset is huge, consider min_df=5.
max_df=0.85:
Removes words that appear in almost every document, as they have little discriminative power.
sublinear_tf=True and norm='l2':
Both help balance out word frequency differences.
If you want, I can also create a GridSearchCV parameter grid with reasonable ranges for your 24k vocabulary so you can automatically find the best combination.
Do you want me to make that for you?