Learn TensorFlow Β· 8/11

Natural Language Processing (NLP) Basics

8 min read

Welcome to the world where we teach silicon chips to understand Shakespeare, sarcasm, and your angry customer support emails. πŸ€–πŸ“œ

Computers are fantastic at math. They love numbers. Give a computer a matrix multiplication, and it does a little happy dance. Give a computer the sentence "I saw a bat in the cave," and it panics. It doesn't know if you saw a flying mammal or a piece of wooden sports equipment.

Natural Language Processing (NLP) is the branch of AI focused on bridging the gap between human communication and computer understanding.

In this guide, we are going to take raw text, grind it down into numbers, and feed it into a neural network to predict sentiment.


1. Text Vectorization and Tokenization

The Problem

Neural networks are mathematical functions. They operate on tensors (multidimensional arrays of numbers). You cannot multiply the string "Hello" by 5. If you try, Python just gives you "HelloHelloHelloHelloHello", which is enthusiastic, but mathematically useless for calculus.

We need to convert text into numbers.

The Solution

We use a two-step process: Tokenization followed by Vectorization.

Tokenization

Definition: Tokenization is the process of breaking a stream of text up into words, phrases, symbols, or other meaningful elements called tokens.

  • Input: "TensorFlow is cool."
  • Tokens: ["TensorFlow", "is", "cool", "."]

Vectorization (Integer Encoding)

Once we have tokens, we assign a unique integer to every unique word in our vocabulary.

  • "TensorFlow" β†’\rightarrow 1
  • "is" β†’\rightarrow 2
  • "cool" β†’\rightarrow 3

Now our sentence is just [1, 2, 3]. The computer is happy again.

Industry Standard: TextVectorization Layer

In modern TensorFlow (Keras), we don't manually build dictionaries. We use the tf.keras.layers.TextVectorization layer. This layer handles everything: standardizing (lowercasing/removing punctuation), splitting, and mapping to integers.

Why this layer? It becomes part of your model. When you save the model and deploy it to a phone or server, the text processing logic goes with it. No more "Wait, did I map 'cat' to 45 or 46?" nightmares.

πŸ’» Hands-on Code

python
import tensorflow as tf
from tensorflow.keras import layers

# Sample data: A tiny corpus of text
training_data = [
    "I love coding in Python",
    "TensorFlow makes AI easy",
    "Natural Language Processing is fun"
]

# 1. Define the Vectorization Layer
# max_tokens: The size of your vocabulary (e.g., top 1000 words).
# output_mode: 'int' converts words to index numbers.
vectorize_layer = layers.TextVectorization(
    max_tokens=1000,
    output_mode='int',
    output_sequence_length=10  # Pads or cuts sentences to exactly 10 tokens
)

# 2. Adapt the layer to your data (This is where it learns the vocabulary)
vectorize_layer.adapt(training_data)

# 3. Test it out
sample_text = ["I love TensorFlow"]
vectorized_output = vectorize_layer(sample_text)

print("Original:", sample_text[0])
print("Vectorized:", vectorized_output.numpy())

# Vocabulary check
print("Vocab:", vectorize_layer.get_vocabulary())

What just happened?
The layer learned the words in training_data. When we fed it "I love TensorFlow", it replaced words with their integer IDs and padded the rest with 0s to reach length 10.


2. Understanding and Using Word Embeddings

The Problem

So we turned "Dog" into 4 and "Cat" into 2.
Mathematically, 4=2Γ—24 = 2 \times 2. Does that mean a "Dog" is twice a "Cat"?
No. (Unless you ask a dog person).

Integer encoding implies a relationship of magnitude that doesn't exist in language. Also, "Good" and "Excellent" might be assigned numbers 50 and 900 purely by chance, so the model doesn't know they are synonyms.

The Solution: Word Embeddings

Definition: An embedding is a dense vector representation of words where words with similar meanings are closer together in geometric space.

Instead of a single number, "King" becomes a list of floating-point numbers (coordinates), like [0.2, -0.9, 1.4, ...].

  • Imagine a 3D space: If you plot the coordinates for "King", "Queen", "Man", and "Woman", you will find that the distance and direction from "Man" to "King" is roughly the same as "Woman" to "Queen".
  • The model learns these vectors during training, just like it learns weights in a Dense layer.

πŸ’» Hands-on Code

In Keras, this is handled by layers.Embedding. It is essentially a lookup table that trains itself.

python
# input_dim = Size of vocabulary (1000 from previous step)
# output_dim = Size of the vector space (e.g., 16 dimensions per word)
embedding_layer = layers.Embedding(input_dim=1000, output_dim=16)

# Test it with the vectorized output from step 1
# Input shape: (1, 10) -> One sentence, 10 tokens
# Output shape: (1, 10, 16) -> One sentence, 10 tokens, each token is a vector of 16 numbers
embedded_output = embedding_layer(vectorized_output)

print("Shape after embedding:", embedded_output.shape)
# Output: (1, 10, 16)

Fun Fact: In massive models like GPT-4, the output_dim (embedding size) is huge (thousands of numbers). This allows the model to capture nuances like "sarcasm" or "melancholy" inside those numbers.


3. Building Recurrent Neural Networks (RNNs) and LSTMs

The Problem

Standard Dense (Feed-Forward) networks have no memory. They process inputs independently.
If I say: "I did NOT enjoy the movie, it was terrible," a simple network might see "enjoy" and think "Positive!", ignoring the "NOT" that came before it.

Language is sequential. The meaning depends on the order.

The Solution: RNNs

Definition: A Recurrent Neural Network (RNN) processes data in a sequence. It maintains a hidden state (memory) that gets passed from one step to the next. It reads word 1, updates memory, reads word 2 using that memory, and so on.

The "Better" Solution: LSTM

Standard RNNs suffer from the Vanishing Gradient Problem. Essentially, they have the memory span of a goldfish. By the time they read a long paragraph, they forget the first sentence.

Long Short-Term Memory (LSTM) networks were designed to solve this. They have internal "gates" that decide:

  1. What to forget (Forget Gate).
  2. What new info to store (Input Gate).
  3. What to output (Output Gate).

This allows them to remember context over long sequences.

Industry Standard: Bidirectional LSTM

In English, context comes from both directions.
"The bank of the river." vs "The bank of America."
To understand "bank," you need to see the words after it too. We use Bidirectional wrappers to read the text forwards and backwards simultaneously.


4. Practical Project: Sentiment Analysis

Let's build a model that reads movie reviews and determines if they are Positive (1) or Negative (0).

The Pipeline:
Text β†’\rightarrow Vectorization β†’\rightarrow Embedding β†’\rightarrow Bidirectional LSTM β†’\rightarrow Dense Classification.

πŸ’» Full Project Code

We will use the IMDB dataset available in TensorFlow, but for this example, we will treat it as raw strings to demonstrate the full flow.

python
import tensorflow as tf
from tensorflow.keras import layers, models, losses

# 1. SETUP DATA (Simulating a dataset of thousands of reviews)
# In real life, use: tf.keras.datasets.imdb.load_data() or load from CSV
train_sentences = [
    "This movie was fantastic and thrilling",
    "Absolute garbage, waste of time",
    "I loved the acting and the plot",
    "Terrible direction and boring story",
    "Best film of the year hands down",
    "I fell asleep it was so bad"
]
train_labels = [1, 0, 1, 0, 1, 0] # 1 = Positive, 0 = Negative

train_dataset = tf.data.Dataset.from_tensor_slices((train_sentences, train_labels))
train_dataset = train_dataset.batch(2)

# 2. PREPROCESSING LAYER
VOCAB_SIZE = 1000
MAX_LENGTH = 20

encoder = layers.TextVectorization(
    max_tokens=VOCAB_SIZE,
    output_mode='int',
    output_sequence_length=MAX_LENGTH
)
encoder.adapt(train_sentences)

# 3. BUILD THE MODEL
model = models.Sequential([
    # Input is raw text strings!
    tf.keras.Input(shape=(1,), dtype=tf.string),
    
    # Text Processing
    encoder,
    
    # Embedding: Turn integers into dense vectors (32 dimensions)
    # mask_zero=True tells the LSTM to ignore the '0' padding we added
    layers.Embedding(input_dim=VOCAB_SIZE, output_dim=32, mask_zero=True),
    
    # The Brain: Bidirectional LSTM
    # 64 units is the size of the hidden memory state
    layers.Bidirectional(layers.LSTM(64)),
    
    # Dense layer for final reasoning
    layers.Dense(64, activation='relu'),
    
    # Output layer: Single neuron (0 to 1)
    layers.Dense(1, activation='sigmoid')
])

# 4. COMPILE
model.compile(
    loss=losses.BinaryCrossentropy(),
    optimizer=tf.keras.optimizers.Adam(1e-4),
    metrics=['accuracy']
)

# 5. TRAIN
print("Training Model...")
history = model.fit(train_dataset, epochs=5)

# 6. PREDICT
print("\n--- Predictions ---")
reviews = [
    "The movie was okay but the ending was bad",
    "What a masterpiece, truly loved it"
]
predictions = model.predict(reviews)

for review, score in zip(reviews, predictions):
    label = "POSITIVE" if score > 0.5 else "NEGATIVE"
    print(f"Review: '{review}'")
    print(f"Sentiment: {label} ({score[0]:.4f})\n")

Explanation of the Mechanics

  1. Input: The model accepts raw strings.
  2. Encoder: Converts strings to [45, 2, 99, 0, 0...].
  3. Masking: The mask_zero=True in Embedding is crucial. It tells the LSTM, "Hey, these zeros are just padding to fill space, don't do math on them." This saves computation and improves accuracy.
  4. Bidirectional LSTM: Reads the vector sequence. It understands that "bad" at the end of the sentence flips the sentiment of "okay" at the start.
  5. Sigmoid: Squashes the final result between 0 and 1. 0.99 is super positive, 0.01 is super negative.

Interesting Reality Check 🌍

While LSTMs are powerful, the industry has largely moved toward Transformers (like BERT and GPT) for complex tasks. However, LSTMs are still widely used for simpler tasks, time-series data, and audio generation because they are much lighter to run than Transformers. Learning LSTMs is the "learning to drive manual" before you hop into the Tesla that is the Transformer architecture.

Useful Links & References

Challenge

Challenge: Build a Sentiment Analysis Model

Your task is to construct a tf.keras.Sequential model for binary sentiment analysis. You must add the layers in the correct sequence with the specified parameters to create a functional NLP pipeline.

Requirements:

  1. TextVectorization Layer: This should be the first layer. Configure it for a vocabulary size of 10000 tokens and to pad or truncate all input sequences to a length of 250.
  2. Embedding Layer: This layer follows vectorization. It must map the integer vocabulary to a dense vector space of 128 dimensions. Crucially, you must enable masking to ensure that padding tokens are ignored by subsequent layers.
  3. Bidirectional LSTM Layer: Add a Bidirectional wrapper around an LSTM layer. The inner LSTM must have 64 units.
  4. Intermediate Dense Layer: After the LSTM, add a Dense layer with 64 units and a relu activation function.
  5. Output Dense Layer: The final layer must be a Dense layer configured for binary classification, using a sigmoid activation function.

Define this architecture inside the provided build_sentiment_model function.

Expected result

Your code should correctly define a Keras Sequential model by instantiating and adding the five required layers in the correct order with the specified parameters.

python
def build_sentiment_model():
    model = keras.Sequential([
        # 1. TextVectorization Layer
        layers.TextVectorization(max_tokens=10000, output_sequence_length=250),

        # 2. Embedding Layer
        layers.Embedding(input_dim=10000, output_dim=128, mask_zero=True),

        # 3. Bidirectional LSTM Layer
        layers.Bidirectional(layers.LSTM(64)),

        # 4. Intermediate Dense Layer
        layers.Dense(64, activation='relu'),

        # 5. Output Dense Layer
        layers.Dense(1, activation='sigmoid')
    ])
    return model
python

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.