Bird
Raised Fist0
NLPml~20 mins

Handling imbalanced text data in NLP - Practice Problems & Coding Challenges

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
Challenge - 5 Problems
🎖️
Imbalanced Text Data Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
🧠 Conceptual
intermediate
2:00remaining
Why use SMOTE for imbalanced text data?
You have a text classification task with very few examples of one class. Why might you use SMOTE (Synthetic Minority Over-sampling Technique) on the text features?
ATo create synthetic examples of the minority class by interpolating feature vectors, helping balance the dataset.
BTo remove noisy examples from the majority class to reduce imbalance.
CTo convert text data into numerical vectors using TF-IDF.
DTo randomly duplicate minority class examples without changing their features.
Attempts:
2 left
💡 Hint
Think about how SMOTE creates new data points rather than just copying existing ones.
Predict Output
intermediate
2:00remaining
Output of class distribution after random oversampling
Given the following code that uses RandomOverSampler on text data features, what will be the printed class distribution?
NLP
from collections import Counter
from sklearn.feature_extraction.text import CountVectorizer
from imblearn.over_sampling import RandomOverSampler

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

vectorizer = CountVectorizer()
X = vectorizer.fit_transform(texts)

ros = RandomOverSampler(random_state=42)
X_res, y_res = ros.fit_resample(X, labels)

print(Counter(y_res))
ACounter({0: 6, 1: 6})
BCounter({0: 5, 1: 5})
CCounter({0: 7, 1: 3})
DCounter({0: 6, 1: 4})
Attempts:
2 left
💡 Hint
RandomOverSampler balances classes by duplicating minority class samples until counts match.
Model Choice
advanced
2:00remaining
Best model choice for imbalanced text classification
You have a highly imbalanced text dataset with 95% negative and 5% positive labels. Which model choice is best to handle this imbalance?
AA K-Nearest Neighbors model with k=3 and no class weighting.
BA simple neural network without any class weighting or sampling.
CA decision tree with default parameters and no imbalance handling.
DA logistic regression model with class_weight='balanced' parameter.
Attempts:
2 left
💡 Hint
Consider models that can adjust learning to pay more attention to minority class.
Hyperparameter
advanced
2:00remaining
Choosing the right threshold for imbalanced text classification
After training a binary text classifier on imbalanced data, you notice low recall for the minority class. Which hyperparameter adjustment can help improve recall?
AIncrease the learning rate to speed up training.
BLower the classification threshold below 0.5 to predict more positives.
CIncrease the batch size to stabilize gradients.
DUse early stopping to prevent overfitting.
Attempts:
2 left
💡 Hint
Recall improves when the model predicts more positive cases, even if some are false positives.
Metrics
expert
2:00remaining
Choosing the best metric for imbalanced text data evaluation
You trained a text classifier on imbalanced data. Which metric is best to evaluate model performance focusing on minority class detection?
AAccuracy, because it shows overall correct predictions.
BLog Loss, because it measures probability calibration.
CF1-score, because it balances precision and recall for the minority class.
DMean Squared Error, because it measures prediction error.
Attempts:
2 left
💡 Hint
Accuracy can be misleading when classes are imbalanced.

Practice

(1/5)
1. What is the main problem caused by imbalanced text data in machine learning models?
easy
A. The model may become biased towards the majority class
B. The model will always have perfect accuracy
C. The model will ignore all classes
D. The model will run faster

Solution

  1. Step 1: Understand class imbalance impact

    Imbalanced data means one class has many more examples than others, causing the model to favor that class.
  2. Step 2: Recognize bias effect

    This bias leads to poor performance on minority classes, reducing fairness and accuracy for those classes.
  3. Final Answer:

    The model may become biased towards the majority class -> Option A
  4. Quick Check:

    Imbalanced data causes bias = D [OK]
Hint: Imbalance means bias toward bigger class [OK]
Common Mistakes:
  • Thinking imbalance improves accuracy
  • Assuming model ignores all classes
  • Believing imbalance speeds up training
2. Which Python library function is commonly used to perform upsampling on imbalanced text data?
easy
A. numpy.dot
B. pandas.read_csv
C. sklearn.utils.resample
D. matplotlib.plot

Solution

  1. Step 1: Identify upsampling tool

    Upsampling means increasing minority class samples, and sklearn.utils.resample is designed for this.
  2. Step 2: Eliminate unrelated functions

    pandas.read_csv loads data, numpy.dot does matrix multiplication, matplotlib.plot draws graphs, so they don't upsample.
  3. Final Answer:

    sklearn.utils.resample -> Option C
  4. Quick Check:

    Upsampling uses sklearn.utils.resample = A [OK]
Hint: Upsample with sklearn.utils.resample [OK]
Common Mistakes:
  • Confusing data loading with upsampling
  • Using plotting or math functions for sampling
  • Not knowing sklearn utilities
3. Given this Python code snippet for downsampling the majority class in text data, what will be the length of downsampled_majority?
from sklearn.utils import resample
majority = ['a'] * 1000
minority = ['b'] * 100

downsampled_majority = resample(majority, replace=False, n_samples=len(minority), random_state=42)
print(len(downsampled_majority))
medium
A. 1000
B. 42
C. 1100
D. 100

Solution

  1. Step 1: Understand resample parameters

    resample is called with n_samples equal to length of minority (100), so it will pick 100 samples from majority.
  2. Step 2: Check replace and output length

    replace=False means no duplicates, so output length equals n_samples, which is 100.
  3. Final Answer:

    100 -> Option D
  4. Quick Check:

    Downsampled length = minority size = 100 [OK]
Hint: Downsample size matches minority length [OK]
Common Mistakes:
  • Assuming output length equals original majority size
  • Confusing random_state with sample size
  • Ignoring n_samples parameter
4. Identify the error in this code snippet that tries to balance imbalanced text data by upsampling minority class:
from sklearn.utils import resample
minority = ['text1', 'text2']
upsampled_minority = resample(minority, replace=True, n_samples=5)
print(len(upsampled_minority))
medium
A. No error; code runs correctly and prints 5
B. Missing random_state parameter causes error
C. replace=True is invalid for resample
D. n_samples must be less than original minority size

Solution

  1. Step 1: Check resample parameters

    replace=True allows sampling with replacement, so n_samples can be larger than original minority size.
  2. Step 2: Verify code behavior

    random_state is optional; code runs fine and prints length 5 as expected.
  3. Final Answer:

    No error; code runs correctly and prints 5 -> Option A
  4. Quick Check:

    Upsampling with replacement works = A [OK]
Hint: replace=True allows larger sample size [OK]
Common Mistakes:
  • Thinking random_state is mandatory
  • Believing n_samples must be smaller
  • Confusing replace parameter usage
5. You have a text classification dataset with 90% class A and 10% class B. After upsampling class B to balance the data, which metric should you check to ensure your model performs well on both classes?
hard
A. Accuracy only
B. Precision and recall for each class
C. Training time
D. Number of epochs

Solution

  1. Step 1: Understand metric importance

    Accuracy can be misleading with imbalanced data; precision and recall show performance per class.
  2. Step 2: Choose metrics for balanced evaluation

    Precision and recall help check if model correctly identifies minority class without many false positives or negatives.
  3. Final Answer:

    Precision and recall for each class -> Option B
  4. Quick Check:

    Balanced data needs precision & recall check = C [OK]
Hint: Check precision and recall, not just accuracy [OK]
Common Mistakes:
  • Relying only on accuracy
  • Ignoring class-wise metrics
  • Focusing on training time or epochs