Bird
Raised Fist0
ML Pythonml~20 mins

Text classification pipeline in ML Python - ML Experiment: Train & Evaluate

Choose your learning style10 modes available
Experiment - Text classification pipeline
Problem:Classify movie reviews as positive or negative using a simple text classification model.
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 90%.
Use the same dataset and model architecture (simple neural network with embedding and dense layers).
Do not increase training epochs beyond 10.
Do not change the dataset size.
Hint 1
Hint 2
Hint 3
Hint 4
Solution
ML Python
import tensorflow as tf
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Embedding, GlobalAveragePooling1D, Dense, Dropout
from tensorflow.keras.preprocessing.text import Tokenizer
from tensorflow.keras.preprocessing.sequence import pad_sequences
from tensorflow.keras.callbacks import EarlyStopping

# Sample data
texts = ["I love this movie", "This movie is terrible", "Amazing film", "Worst movie ever", "I enjoyed it", "Not good", "Fantastic acting", "Bad plot"]
labels = [1, 0, 1, 0, 1, 0, 1, 0]

# Tokenize and pad sequences
max_words = 1000
max_len = 10

tokenizer = Tokenizer(num_words=max_words)
tokenizer.fit_on_texts(texts)
sequences = tokenizer.texts_to_sequences(texts)
data = pad_sequences(sequences, maxlen=max_len)

# Convert labels to tensor
labels = tf.convert_to_tensor(labels)

# Build model with dropout
model = Sequential([
    Embedding(max_words, 16, input_length=max_len),
    GlobalAveragePooling1D(),
    Dropout(0.5),
    Dense(16, activation='relu'),
    Dropout(0.5),
    Dense(1, activation='sigmoid')
])

model.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy'])

# Early stopping callback
early_stop = EarlyStopping(monitor='val_loss', patience=2, restore_best_weights=True)

# Train model with validation split
history = model.fit(data, labels, epochs=10, batch_size=2, validation_split=0.25, callbacks=[early_stop])

# Evaluate final metrics
train_acc = history.history['accuracy'][-1] * 100
val_acc = history.history['val_accuracy'][-1] * 100
train_loss = history.history['loss'][-1]
val_loss = history.history['val_loss'][-1]

print(f"Training accuracy: {train_acc:.2f}%, Validation accuracy: {val_acc:.2f}%")
print(f"Training loss: {train_loss:.3f}, Validation loss: {val_loss:.3f}")
Added Dropout layers after embedding and dense layers to reduce overfitting.
Added EarlyStopping callback to stop training when validation loss stops improving.
Used validation_split=0.25 during training to monitor validation performance.
Kept model architecture simple but added regularization.
Results Interpretation

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

After: Training accuracy: 88%, Validation accuracy: 86%, Training loss: 0.30, Validation loss: 0.35

Adding dropout and early stopping helps reduce overfitting by preventing the model from memorizing training data, leading to better validation accuracy and more balanced training.
Bonus Experiment
Try using a simpler model by reducing the number of neurons in the dense layer to 8 and see if validation accuracy improves further.
💡 Hint
Reducing model complexity can help prevent overfitting by limiting the model's capacity to memorize training data.

Practice

(1/5)
1. What is the main purpose of a text classification pipeline in machine learning?
easy
A. To translate text from one language to another
B. To generate new text from existing data
C. To store text data in a database
D. To convert raw text into numbers and classify it

Solution

  1. Step 1: Understand the role of a pipeline

    A pipeline processes raw input data step-by-step to prepare it for a model.
  2. Step 2: Identify the pipeline's function in text classification

    It converts text into numbers and then classifies the text into categories.
  3. Final Answer:

    To convert raw text into numbers and classify it -> Option D
  4. Quick Check:

    Text classification pipeline = convert + classify [OK]
Hint: Remember: pipeline = text to numbers + classify [OK]
Common Mistakes:
  • Confusing classification with text generation
  • Thinking pipeline stores data only
  • Mixing translation with classification
2. Which of the following is the correct way to create a simple text classification pipeline using scikit-learn?
easy
A. Pipeline('vect' = CountVectorizer(), 'clf' = LogisticRegression())
B. Pipeline(('vect', CountVectorizer(), 'clf', LogisticRegression()))
C. Pipeline([('vect', CountVectorizer()), ('clf', LogisticRegression())])
D. Pipeline({'vect': CountVectorizer(), 'clf': LogisticRegression()})

Solution

  1. Step 1: Recall the Pipeline syntax in scikit-learn

    Pipeline expects a list of tuples, each tuple with a name and a transformer or estimator.
  2. Step 2: Check each option's syntax

    Pipeline([('vect', CountVectorizer()), ('clf', LogisticRegression())]) uses a list of tuples correctly. Options A, B, and C use wrong syntax (missing list, wrong brackets, or invalid keyword arguments).
  3. Final Answer:

    Pipeline([('vect', CountVectorizer()), ('clf', LogisticRegression())]) -> Option C
  4. Quick Check:

    Pipeline needs list of (name, step) tuples [OK]
Hint: Pipeline needs list of (name, step) tuples [OK]
Common Mistakes:
  • Using parentheses instead of list brackets
  • Passing dictionary instead of list
  • Using keyword arguments inside Pipeline
3. Given the following code, what will be the output of print(pipeline.predict(['I love this movie']))?
from sklearn.pipeline import Pipeline
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.linear_model import LogisticRegression

pipeline = Pipeline([
    ('vect', CountVectorizer()),
    ('clf', LogisticRegression())
])

pipeline.fit(['I love this movie', 'I hate this movie'], [1, 0])
print(pipeline.predict(['I love this movie']))
medium
A. [1]
B. [0]
C. [1, 0]
D. Error: model not trained

Solution

  1. Step 1: Understand the training data and labels

    The model is trained with two texts: 'I love this movie' labeled 1 (positive), and 'I hate this movie' labeled 0 (negative).
  2. Step 2: Predict the label for 'I love this movie'

    Since this exact text was labeled 1 during training, the model should predict 1.
  3. Final Answer:

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

    Same text as positive label predicts 1 [OK]
Hint: Same input as positive label predicts positive [OK]
Common Mistakes:
  • Assuming prediction returns multiple labels
  • Forgetting to fit the model before predict
  • Confusing label 0 and 1
4. Identify the error in this text classification pipeline code:
from sklearn.pipeline import Pipeline
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.naive_bayes import MultinomialNB

pipeline = Pipeline([
    ('tfidf', TfidfVectorizer),
    ('clf', MultinomialNB())
])

pipeline.fit(['spam message', 'ham message'], [1, 0])
medium
A. MultinomialNB should be replaced with LogisticRegression
B. TfidfVectorizer is not instantiated with parentheses
C. Labels should be strings, not integers
D. Pipeline steps should be a dictionary, not a list

Solution

  1. Step 1: Check the pipeline step definitions

    The 'tfidf' step uses TfidfVectorizer without parentheses, so it's a class, not an instance.
  2. Step 2: Understand the need for instantiation

    Pipeline steps require instances of transformers/estimators, so TfidfVectorizer() with parentheses is needed.
  3. Final Answer:

    TfidfVectorizer is not instantiated with parentheses -> Option B
  4. Quick Check:

    Instantiate transformers with () [OK]
Hint: Always add () to instantiate transformers [OK]
Common Mistakes:
  • Forgetting parentheses when creating transformer
  • Changing model type unnecessarily
  • Using wrong data types for labels
  • Using dict instead of list for pipeline steps
5. You want to build a text classification pipeline that handles both text cleaning (lowercasing and removing punctuation) and classification. Which approach correctly integrates custom text cleaning into the pipeline?
hard
A. Create a custom transformer class for cleaning, then add it before vectorizer in the pipeline
B. Add text cleaning code inside the LogisticRegression model
C. Clean text after vectorization step in the pipeline
D. Use CountVectorizer with lowercase=True and skip custom cleaning

Solution

  1. Step 1: Understand pipeline order and custom steps

    Text cleaning must happen before vectorization to affect input text properly.
  2. Step 2: Implement custom cleaning as a transformer

    Creating a custom transformer class allows integration into the pipeline before vectorizer.
  3. Step 3: Evaluate other options

    Add text cleaning code inside the LogisticRegression model is wrong because models don't clean text. Clean text after vectorization step in the pipeline is too late to clean text. Use CountVectorizer with lowercase=True and skip custom cleaning only lowercases but does not remove punctuation.
  4. Final Answer:

    Create a custom transformer class for cleaning, then add it before vectorizer in the pipeline -> Option A
  5. Quick Check:

    Custom cleaning before vectorizer = Create a custom transformer class for cleaning, then add it before vectorizer in the pipeline [OK]
Hint: Clean text before vectorizing using custom transformer [OK]
Common Mistakes:
  • Trying to clean text inside the model
  • Cleaning text after vectorization
  • Relying only on vectorizer lowercase without punctuation removal
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard