Bird
Raised Fist0
NLPml~20 mins

Challenges in language processing 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 - Challenges in language processing
Problem:You are building a simple text classifier to identify if a sentence is positive or negative. The current model achieves 95% accuracy on training data but only 70% on validation data.
Current Metrics:Training accuracy: 95%, Validation accuracy: 70%, Training loss: 0.15, Validation loss: 0.60
Issue:The model is overfitting the training data and does not generalize well to new sentences.
Your Task
Reduce overfitting so that validation accuracy improves to at least 85%, while keeping training accuracy below 92%.
You can only modify the model architecture and training hyperparameters.
Do not change the dataset or add more data.
Hint 1
Hint 2
Hint 3
Hint 4
Solution
NLP
import tensorflow as tf
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Embedding, LSTM, Dense, Dropout
from tensorflow.keras.callbacks import EarlyStopping

# Sample data placeholders (replace with actual data loading)
X_train = tf.random.uniform((1000, 100), maxval=10000, dtype=tf.int32)
y_train = tf.random.uniform((1000,), maxval=2, dtype=tf.int32)
X_val = tf.random.uniform((200, 100), maxval=10000, dtype=tf.int32)
y_val = tf.random.uniform((200,), maxval=2, dtype=tf.int32)

model = Sequential([
    Embedding(input_dim=10000, output_dim=64, input_length=100),
    LSTM(64, return_sequences=False),
    Dropout(0.5),
    Dense(32, activation='relu'),
    Dropout(0.5),
    Dense(1, activation='sigmoid')
])

model.compile(optimizer=tf.keras.optimizers.Adam(learning_rate=0.001),
              loss='binary_crossentropy',
              metrics=['accuracy'])

early_stop = EarlyStopping(monitor='val_loss', patience=3, restore_best_weights=True)

history = model.fit(X_train, y_train, epochs=20, batch_size=32, validation_data=(X_val, y_val), callbacks=[early_stop])
Added Dropout layers after LSTM and Dense layers to reduce overfitting.
Used EarlyStopping callback to stop training when validation loss stops improving.
Reduced LSTM units from a larger number to 64 to lower model complexity.
Set learning rate to 0.001 for stable training.
Results Interpretation

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

After: Training accuracy 90%, Validation accuracy 87%, Training loss 0.30, Validation loss 0.40

Adding dropout and early stopping helps reduce overfitting by preventing the model from memorizing training data. This improves validation accuracy and generalization.
Bonus Experiment
Try using a simpler model like a 1D convolutional neural network (CNN) instead of LSTM to see if it reduces overfitting further.
💡 Hint
CNNs can capture local patterns in text and often train faster with fewer parameters.

Practice

(1/5)
1. Why is language processing challenging for computers?
easy
A. Because computers do not have enough memory
B. Because computers cannot store large amounts of data
C. Because language has only one fixed meaning per word
D. Because words can have multiple meanings depending on context

Solution

  1. Step 1: Understand word ambiguity in language

    Words often have several meanings, which depend on the context they appear in.
  2. Step 2: Relate ambiguity to computer difficulty

    Computers struggle to pick the correct meaning without understanding context, making language processing hard.
  3. Final Answer:

    Because words can have multiple meanings depending on context -> Option D
  4. Quick Check:

    Word ambiguity = D [OK]
Hint: Remember: words change meaning with context [OK]
Common Mistakes:
  • Thinking each word has only one meaning
  • Assuming computers lack memory causes difficulty
  • Confusing data storage with language understanding
2. Which of the following is the correct way to represent a sentence tokenization step in Python using NLTK?
easy
A. tokens = nltk.word_tokenize(sentence)
B. tokens = nltk.sentence_tokenize(sentence)
C. tokens = nltk.tokenize_words(sentence)
D. tokens = nltk.split(sentence)

Solution

  1. Step 1: Recall NLTK tokenization functions

    NLTK uses word_tokenize() to split sentences into words (tokens).
  2. Step 2: Identify correct function for word tokenization

    word_tokenize() is the correct function; sentence_tokenize() does not exist, and others are invalid.
  3. Final Answer:

    tokens = nltk.word_tokenize(sentence) -> Option A
  4. Quick Check:

    NLTK word tokenization = C [OK]
Hint: Use word_tokenize() for splitting sentence into words [OK]
Common Mistakes:
  • Using sentence_tokenize() which is not a valid function
  • Confusing word_tokenize() with tokenize_words()
  • Trying to split sentence with split() method
3. Given the code below, what will be the output?
sentence = "I saw her duck." 
tokens = sentence.split()
print(tokens)
medium
A. ['I', 'saw', 'her', 'duck.']
B. ['I', 'saw', 'her', 'duck']
C. ['I', 'saw', 'her', 'duck', '.']
D. ['I saw her duck']

Solution

  1. Step 1: Understand split() behavior on string

    split() divides the string by spaces, keeping punctuation attached to words.
  2. Step 2: Apply split() to the sentence

    Splitting "I saw her duck." by spaces results in ['I', 'saw', 'her', 'duck.'] with the period attached to 'duck.'
  3. Final Answer:

    ['I', 'saw', 'her', 'duck.'] -> Option A
  4. Quick Check:

    split() keeps punctuation attached = A [OK]
Hint: split() keeps punctuation with words [OK]
Common Mistakes:
  • Assuming split() removes punctuation
  • Expecting punctuation as separate token
  • Confusing split() with word_tokenize()
4. The following code tries to remove stopwords from a list of tokens but does not work as expected. What is the error?
stopwords = ['the', 'is', 'at']
tokens = ['the', 'cat', 'is', 'on', 'the', 'mat']
filtered = [word for word in tokens if word not in stopwords()]
print(filtered)
medium
A. tokens should be converted to a set before filtering
B. The list comprehension syntax is incorrect
C. stopwords is a list, not a function; should not use parentheses
D. The print statement is missing parentheses

Solution

  1. Step 1: Identify the error in stopwords usage

    stopwords is a list, but the code uses stopwords() as if it were a function.
  2. Step 2: Correct the usage of stopwords

    Remove parentheses to use stopwords as a list: use 'word not in stopwords' instead of 'stopwords()'.
  3. Final Answer:

    stopwords is a list, not a function; should not use parentheses -> Option C
  4. Quick Check:

    stopwords list misuse = B [OK]
Hint: Lists are not functions; avoid parentheses [OK]
Common Mistakes:
  • Using parentheses after list variable
  • Thinking tokens must be sets to filter
  • Misreading list comprehension syntax
5. Which challenge best explains why idioms like "kick the bucket" are hard for AI to understand?
hard
A. Idioms are always spelled incorrectly
B. Idioms have meanings different from the literal words
C. Idioms contain rare words not in dictionaries
D. Idioms are too long for AI to process

Solution

  1. Step 1: Understand idioms in language

    Idioms are phrases whose meaning is not the sum of their individual words.
  2. Step 2: Relate idioms to AI language challenges

    AI struggles because it cannot infer the non-literal meaning from the literal words alone.
  3. Final Answer:

    Idioms have meanings different from the literal words -> Option B
  4. Quick Check:

    Idioms = non-literal meaning = A [OK]
Hint: Idioms mean more than their words [OK]
Common Mistakes:
  • Thinking idioms are misspelled
  • Assuming idioms use rare words
  • Believing idioms are too long to process