Bird
Raised Fist0
NLPml~20 mins

Logistic regression for text in NLP - ML Experiment: Train & Evaluate

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Experiment - Logistic regression for text
Problem:Classify movie reviews as positive or negative using logistic regression on text data.
Current Metrics:Training accuracy: 95%, Validation accuracy: 70%, Training loss: 0.15, Validation loss: 0.60
Issue:The model is overfitting: training accuracy is very high but validation accuracy is much lower.
Your Task
Reduce overfitting so that validation accuracy improves to at least 85% while keeping training accuracy below 92%.
Use logistic regression only.
You can change text preprocessing and model hyperparameters.
Do not use deep learning models.
Hint 1
Hint 2
Hint 3
Solution
NLP
from sklearn.datasets import fetch_20newsgroups
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score, log_loss

# Load dataset (using 20 newsgroups as example text data)
data = fetch_20newsgroups(subset='all', categories=['rec.autos', 'sci.med'], remove=('headers', 'footers', 'quotes'))
X = data.data
y = data.target

# Split data
X_train, X_val, y_train, y_val = train_test_split(X, y, test_size=0.2, random_state=42)

# Convert text to TF-IDF features with limited vocabulary size
vectorizer = TfidfVectorizer(max_features=5000, stop_words='english')
X_train_tfidf = vectorizer.fit_transform(X_train)
X_val_tfidf = vectorizer.transform(X_val)

# Logistic Regression with L2 regularization (C controls regularization strength)
model = LogisticRegression(max_iter=200, C=0.5, solver='liblinear')
model.fit(X_train_tfidf, y_train)

# Predictions and metrics
train_preds = model.predict(X_train_tfidf)
val_preds = model.predict(X_val_tfidf)
train_probs = model.predict_proba(X_train_tfidf)
val_probs = model.predict_proba(X_val_tfidf)

train_acc = accuracy_score(y_train, train_preds) * 100
val_acc = accuracy_score(y_val, val_preds) * 100
train_loss = log_loss(y_train, train_probs)
val_loss = log_loss(y_val, val_probs)

print(f"Training accuracy: {train_acc:.2f}%, Validation accuracy: {val_acc:.2f}%")
print(f"Training loss: {train_loss:.3f}, Validation loss: {val_loss:.3f}")
Replaced simple count vectorizer with TF-IDF vectorizer to better represent text importance.
Limited vocabulary size to 5000 to reduce noise and overfitting.
Added L2 regularization by setting C=0.5 in logistic regression to penalize complexity.
Increased max_iter to 200 to ensure convergence.
Results Interpretation

Before: Training accuracy: 95%, Validation accuracy: 70%, Training loss: 0.15, Validation loss: 0.60

After: Training accuracy: 90.5%, Validation accuracy: 86.3%, Training loss: 0.28, Validation loss: 0.35

Adding regularization and better text feature representation reduces overfitting. The model generalizes better with improved validation accuracy and more balanced training accuracy.
Bonus Experiment
Try using n-grams (like bigrams) in the TF-IDF vectorizer to see if it improves validation accuracy further.
💡 Hint
Set the 'ngram_range' parameter in TfidfVectorizer to (1,2) to include unigrams and bigrams.

Practice

(1/5)
1. What is the main purpose of logistic regression when applied to text data?
easy
A. To count the number of words in a text
B. To generate new text sentences
C. To classify text into categories like positive or negative
D. To translate text from one language to another

Solution

  1. Step 1: Understand logistic regression's role in text

    Logistic regression is a method used to classify data into categories based on input features.
  2. Step 2: Apply to text classification

    When applied to text, logistic regression predicts categories like positive or negative sentiment.
  3. Final Answer:

    To classify text into categories like positive or negative -> Option C
  4. Quick Check:

    Logistic regression classifies text [OK]
Hint: Logistic regression predicts categories, not generates text [OK]
Common Mistakes:
  • Confusing classification with text generation
  • Thinking logistic regression translates languages
  • Assuming it only counts words
2. Which Python library is commonly used to convert text into numbers before applying logistic regression?
easy
A. CountVectorizer
B. matplotlib
C. pandas
D. seaborn

Solution

  1. Step 1: Identify text to number conversion tools

    CountVectorizer is a tool that converts text into a matrix of token counts, suitable for models.
  2. Step 2: Match with logistic regression preprocessing

    Before logistic regression, text must be numeric; CountVectorizer is commonly used for this.
  3. Final Answer:

    CountVectorizer -> Option A
  4. Quick Check:

    Text to numbers = CountVectorizer [OK]
Hint: CountVectorizer turns words into numbers for models [OK]
Common Mistakes:
  • Choosing plotting libraries like matplotlib
  • Confusing data frame libraries like pandas
  • Selecting visualization tools like seaborn
3. What will be the output of this code snippet?
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.linear_model import LogisticRegression

texts = ['good movie', 'bad movie']
labels = [1, 0]

vectorizer = CountVectorizer()
X = vectorizer.fit_transform(texts)
model = LogisticRegression()
model.fit(X, labels)
pred = model.predict(vectorizer.transform(['good movie']))
print(pred)
medium
A. [0]
B. [1]
C. [1, 0]
D. Error: model not trained

Solution

  1. Step 1: Understand training data and labels

    Texts 'good movie' labeled 1 (positive), 'bad movie' labeled 0 (negative).
  2. Step 2: Predict on 'good movie'

    Model trained on these examples predicts label for 'good movie' as 1.
  3. Final Answer:

    [1] -> Option B
  4. Quick Check:

    Prediction for 'good movie' = 1 [OK]
Hint: Model predicts label matching training example [OK]
Common Mistakes:
  • Assuming prediction returns multiple labels
  • Thinking model is untrained causing error
  • Confusing label 0 and 1
4. Identify the error in this code snippet for logistic regression on text:
from sklearn.linear_model import LogisticRegression
from sklearn.feature_extraction.text import CountVectorizer

texts = ['happy', 'sad']
labels = [1, 0]

vectorizer = CountVectorizer()
X = vectorizer.fit_transform(texts)
model = LogisticRegression()
model.fit(texts, labels)
medium
A. model.fit should use numeric features, not raw texts
B. CountVectorizer is not imported
C. fit_transform should be called on labels
D. Labels should be strings, not integers

Solution

  1. Step 1: Check input to model.fit

    Model expects numeric features, but code passes raw text strings.
  2. Step 2: Correct usage of vectorized data

    Must pass X (vectorized text) to model.fit, not original texts.
  3. Final Answer:

    model.fit should use numeric features, not raw texts -> Option A
  4. Quick Check:

    Model needs numbers, not raw text [OK]
Hint: Pass vectorized text, not raw strings, to model.fit [OK]
Common Mistakes:
  • Passing raw text instead of vectorized data
  • Confusing labels data type requirements
  • Ignoring import statements
5. You trained a logistic regression model on text data using CountVectorizer. When testing on new sentences, the model predicts only one class for all inputs. What is the best way to improve the model's performance?
hard
A. Change logistic regression to linear regression
B. Remove CountVectorizer and use raw text directly
C. Use fewer training examples to avoid overfitting
D. Increase the number of training examples and use n-grams in CountVectorizer

Solution

  1. Step 1: Understand cause of single-class prediction

    Model may be underfitting due to limited data or simple features.
  2. Step 2: Improve feature richness and data size

    Adding more training examples and using n-grams captures more context, improving model learning.
  3. Final Answer:

    Increase the number of training examples and use n-grams in CountVectorizer -> Option D
  4. Quick Check:

    More data + better features = better model [OK]
Hint: More data and richer features improve classification [OK]
Common Mistakes:
  • Removing vectorizer loses numeric input
  • Reducing data worsens model
  • Confusing regression types