LSTM helps computers understand and remember words in sentences. It is good for tasks like predicting the next word or classifying text.
LSTM for text in NLP
model = Sequential() model.add(Embedding(input_dim=vocab_size, output_dim=embedding_dim, input_length=max_length)) model.add(LSTM(units=hidden_units)) model.add(Dense(units=num_classes, activation='softmax')) model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])
Embedding layer turns words into numbers that the model can understand.
LSTM layer remembers important information from the text.
model = Sequential() model.add(Embedding(10000, 64, input_length=100)) model.add(LSTM(128)) model.add(Dense(5, activation='softmax')) model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])
model = Sequential() model.add(Embedding(5000, 32, input_length=50)) model.add(LSTM(64, return_sequences=True)) model.add(LSTM(32)) model.add(Dense(1, activation='sigmoid')) model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])
This program trains a small LSTM model to classify short sentences as positive or negative. It shows training accuracy and predicted classes.
import numpy as np from tensorflow.keras.models import Sequential from tensorflow.keras.layers import Embedding, LSTM, Dense from tensorflow.keras.utils import to_categorical # Sample text data: sentences and labels texts = ['I love machine learning', 'This is a great movie', 'I hate bad weather', 'This movie is terrible'] labels = [1, 1, 0, 0] # 1=positive, 0=negative # Simple word index word_index = {'i':1, 'love':2, 'machine':3, 'learning':4, 'this':5, 'is':6, 'a':7, 'great':8, 'movie':9, 'hate':10, 'bad':11, 'weather':12, 'terrible':13} # Convert texts to sequences of integers max_length = 5 sequences = [] for text in texts: seq = [word_index[word.lower()] for word in text.split()] # Pad sequences with zeros if shorter than max_length seq += [0] * (max_length - len(seq)) sequences.append(seq) X = np.array(sequences) y = to_categorical(labels, num_classes=2) # Build LSTM model model = Sequential() model.add(Embedding(input_dim=14, output_dim=8, input_length=max_length)) model.add(LSTM(16)) model.add(Dense(2, activation='softmax')) model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy']) # Train model history = model.fit(X, y, epochs=10, verbose=0) # Predict on training data predictions = model.predict(X) predicted_classes = np.argmax(predictions, axis=1) print(f'Training accuracy: {history.history["accuracy"][-1]:.2f}') print('Predicted classes:', predicted_classes.tolist())
LSTM is good at remembering the order of words, which is important in sentences.
Embedding size and LSTM units can be changed to improve model performance.
For real projects, use more data and proper text preprocessing.
LSTM models help understand text by remembering word order.
They are useful for tasks like sentiment analysis and text classification.
Embedding layers convert words into numbers before LSTM processes them.
Practice
Solution
Step 1: Understand LSTM's role in text
LSTM models are designed to remember sequences, which means they keep track of word order in sentences.Step 2: Compare options with LSTM function
Only It remembers the order of words in a sentence. correctly describes LSTM's ability to remember word order. Other options describe unrelated tasks.Final Answer:
It remembers the order of words in a sentence. -> Option CQuick Check:
LSTM remembers word order = B [OK]
- Thinking LSTM translates languages
- Confusing LSTM with image processing
- Assuming LSTM removes punctuation
Solution
Step 1: Identify LSTM layer syntax in Keras
The LSTM layer is added with LSTM(units, input_shape=(timesteps, features)). model.add(LSTM(128, input_shape=(timesteps, features))) matches this syntax.Step 2: Check other options for correctness
model.add(Dense(128, input_shape=(timesteps, features))) is a Dense layer, not LSTM. model.add(Conv2D(128, kernel_size=3)) is a Conv2D layer for images. model.add(Embedding(128, input_shape=(timesteps, features))) is an Embedding layer, not LSTM.Final Answer:
model.add(LSTM(128, input_shape=(timesteps, features))) -> Option AQuick Check:
LSTM layer syntax = D [OK]
- Using Dense instead of LSTM for sequence data
- Confusing Embedding with LSTM layer
- Applying Conv2D for text input
model = Sequential() model.add(Embedding(input_dim=1000, output_dim=64, input_length=10)) model.add(LSTM(32)) output = model.output_shape
Solution
Step 1: Understand Embedding and LSTM output shapes
The Embedding layer outputs (batch_size, 10, 64). The LSTM with 32 units returns (batch_size, 32) by default (last output only).Step 2: Match output shape with options
(None, 32) matches (None, 32) where None is batch size. Other options are incorrect shapes.Final Answer:
(None, 32) -> Option BQuick Check:
LSTM output shape = (None, 32) [OK]
- Assuming LSTM outputs full sequence by default
- Confusing embedding output with LSTM output
- Ignoring batch size dimension
model = Sequential() model.add(LSTM(64, input_shape=(100,))) model.add(Dense(1, activation='sigmoid')) model.compile(optimizer='adam', loss='binary_crossentropy')
Solution
Step 1: Check input shape for LSTM layer
LSTM expects input shape as (timesteps, features). Here, (100,) is 1D, missing feature dimension.Step 2: Validate other components
Binary classification uses sigmoid activation and binary_crossentropy loss correctly. Adam optimizer is suitable.Final Answer:
Input shape should be 2D, e.g., (timesteps, features), not (100,) -> Option DQuick Check:
LSTM input shape must be 2D = A [OK]
- Using 1D input shape for LSTM
- Changing activation incorrectly for binary tasks
- Mixing loss functions for binary classification
Solution
Step 1: Understand preprocessing for text in LSTM models
Embedding layers convert words into meaningful numeric vectors, helping LSTM understand word relationships.Step 2: Evaluate other options
Dense layers expect numeric input, not raw text. Conv2D is for images. Feeding raw strings to LSTM causes errors.Final Answer:
Add an Embedding layer to convert words into dense vectors before the LSTM. -> Option AQuick Check:
Embedding before LSTM = C [OK]
- Feeding raw text directly to LSTM
- Using Dense or Conv2D layers on raw text
- Skipping word vector conversion
Ready to prove it?
Pass the test and this pattern moves unknown
