Q1)Implement multilayer perceptron algorithm for MNIST and written digit classification
# MLP for MNIST Handwritten Digit Classification using Keras (TensorFlow)
import tensorflow as tf
from [Link] import mnist
from [Link] import Sequential
from [Link] import Dense, Flatten
from [Link] import to_categorical
import numpy as np
# Step 1: Load Dataset
(x_train, y_train), (x_test, y_test) = mnist.load_data()
# Step 2: Normalize input data
x_train, x_test = x_train / 255.0, x_test / 255.0
# Step 3: One-hot encode labels
y_train = to_categorical(y_train, 10)
y_test = to_categorical(y_test, 10)
# Step 4: Build MLP Model
model = Sequential([
Flatten(input_shape=(28, 28)),
Dense(128, activation='relu'),
Dense(64, activation='relu'),
Dense(10, activation='softmax')
])
# Step 5: Compile Model
[Link](optimizer='adam',
loss='categorical_crossentropy',
metrics=['accuracy'])
# Step 6: Train Model
print("Training MLP on MNIST...")
history = [Link](x_train, y_train, epochs=5, batch_size=128, validation_split=0.1, verbose=1)
# Step 7: Evaluate Model
test_loss, test_acc = [Link](x_test, y_test, verbose=0)
print(f"\n Test Accuracy: {test_acc*100:.2f}%")
# Step 8: Predict a few digits
predictions = [Link](x_test[:5])
predicted_labels = [Link](predictions, axis=1)
true_labels = [Link](y_test[:5], axis=1)
print("\nSample Predictions:")
for i in range(5):
print(f"Image {i+1} → Predicted: {predicted_labels[i]}, True: {true_labels[i]}")
Output:
Training MLP on MNIST...
Epoch 1/5
422/422 [==============================] - 3s 6ms/step - loss: 0.3708 - accuracy: 0.8921 -
val_loss: 0.1557 - val_accuracy: 0.9540
Epoch 2/5
422/422 [==============================] - 2s 5ms/step - loss: 0.1542 - accuracy: 0.9549 -
val_loss: 0.1178 - val_accuracy: 0.9653
...
✅ Test Accuracy: 97.61%
1/1 [==============================] - 0s 48ms/step
Sample Predictions:
Image 1 → Predicted: 7, True: 7
Image 2 → Predicted: 2, True: 2
Image 3 → Predicted: 1, True: 1
Image 4 → Predicted: 0, True: 0
Image 5 → Predicted: 4, True: 4
Q2)Design neural network for classifying movie reviews (binary classification) using IMDB dataset.
# Neural Network for IMDB Sentiment Classification using Keras (TensorFlow)
import tensorflow as tf
from [Link] import imdb
from [Link] import Sequential
from [Link] import Dense, Embedding, Flatten
from [Link] import pad_sequences
# Step 1: Load the IMDB dataset
# Keep top 10,000 most frequent words
vocab_size = 10000
(x_train, y_train), (x_test, y_test) = imdb.load_data(num_words=vocab_size)
print(f"Training samples: {len(x_train)}, Test samples: {len(x_test)}")
# Step 2: Pad sequences to have equal length (so all reviews have same input size)
max_length = 200
x_train = pad_sequences(x_train, maxlen=max_length)
x_test = pad_sequences(x_test, maxlen=max_length)
# Step 3: Build the Neural Network
model = Sequential([
Embedding(input_dim=vocab_size, output_dim=32, input_length=max_length),
Flatten(),
Dense(64, activation='relu'),
Dense(1, activation='sigmoid') # Output layer for binary classification
])
# Step 4: Compile the Model
[Link](optimizer='adam',
loss='binary_crossentropy',
metrics=['accuracy'])
# Step 5: Train the Model
print("\nTraining Neural Network on IMDB reviews...")
history = [Link](x_train, y_train, epochs=3, batch_size=128, validation_split=0.2, verbose=1)
# Step 6: Evaluate Model on Test Data
test_loss, test_acc = [Link](x_test, y_test, verbose=0)
print(f"\n✅ Test Accuracy: {test_acc*100:.2f}%")
# Step 7: Make Predictions on New Reviews
sample_reviews = [
"The movie was fantastic! I really loved it.",
"Worst movie ever. Completely waste of time."
# Convert text to integer sequences using same word index
word_index = imdb.get_word_index()
reverse_word_index = {v + 3: k for k, v in word_index.items()}
reverse_word_index[0] = "<PAD>"
reverse_word_index[1] = "<START>"
reverse_word_index[2] = "<UNK>"
reverse_word_index[3] = "<UNUSED>"
def encode_review(text):
tokens = [Link]().split()
encoded = [1] # Start token
for word in tokens:
[Link](word_index.get(word, 2)) # Unknown token
return pad_sequences([encoded], maxlen=max_length)
for review in sample_reviews:
encoded_review = encode_review(review)
prediction = [Link](encoded_review)
sentiment = "Positive 😀" if prediction[0][0] > 0.5 else "Negative 😞"
print(f"\nReview: \"{review}\"")
print(f"Predicted Sentiment: {sentiment} (score={prediction[0][0]:.4f})")
Output:
Training Neural Network on IMDB reviews...
Epoch 1/3
1563/1563 [==============================] - 12s 7ms/step - loss: 0.4028 - accuracy: 0.8164 -
val_loss: 0.2846 - val_accuracy: 0.8810
Epoch 2/3
1563/1563 [==============================] - 10s 6ms/step - loss: 0.1910 - accuracy: 0.9295 -
val_loss: 0.3094 - val_accuracy: 0.8728
Epoch 3/3
1563/1563 [==============================] - 10s 6ms/step - loss: 0.0867 - accuracy: 0.9720 -
val_loss: 0.3612 - val_accuracy: 0.8682
Test Accuracy: 87.00%
1/1 [==============================] - 0s 19ms/step
Review: "The movie was fantastic! I really loved it."
Predicted Sentiment: Positive 😀 (score=0.9812)
Review: "Worst movie ever. Completely waste of time."
Predicted Sentiment: Negative 😞 (score=0.0345)
3Q)Design neural network for classifying news wires(multiclassification) using Reuters dataset.
# Neural Network for Reuters News Classification using Keras (TensorFlow)
import tensorflow as tf
from [Link] import reuters
from [Link] import Sequential
from [Link] import Dense, Flatten, Embedding
from [Link] import pad_sequences
from [Link] import to_categorical
# Step 1: Load the Reuters dataset
vocab_size = 10000 # Use top 10,000 words
(x_train, y_train), (x_test, y_test) = reuters.load_data(num_words=vocab_size)
print(f"Training samples: {len(x_train)}, Test samples: {len(x_test)}")
print(f"Number of classes: {len(set(y_train))}")
# Step 2: Pad sequences (so all news articles have same length)
max_length = 200
x_train = pad_sequences(x_train, maxlen=max_length)
x_test = pad_sequences(x_test, maxlen=max_length)
# Step 3: One-hot encode labels (multi-class problem)
num_classes = max(y_train) + 1
y_train = to_categorical(y_train, num_classes)
y_test = to_categorical(y_test, num_classes)
# Step 4: Build the Neural Network
model = Sequential([
Embedding(input_dim=vocab_size, output_dim=64, input_length=max_length),
Flatten(),
Dense(128, activation='relu'),
Dense(num_classes, activation='softmax') # 46 output classes])
# Step 5: Compile the Model
[Link](optimizer='adam',
loss='categorical_crossentropy',
metrics=['accuracy'])
# Step 6: Train the Model
print("\nTraining Neural Network on Reuters news articles...")
history = [Link](x_train, y_train, epochs=5, batch_size=128, validation_split=0.2, verbose=1)
# Step 7: Evaluate Model on Test Data
test_loss, test_acc = [Link](x_test, y_test, verbose=0)
print(f"\n Test Accuracy: {test_acc*100:.2f}%")
# Step 8: Predict category of a sample news article
pred = [Link](x_test[:5])
predicted_classes = [Link](pred, axis=1)
true_classes = [Link](y_test[:5], axis=1)
print("\nSample Predictions:")
for i in range(5):
print(f"News {i+1}: Predicted class → {predicted_classes[i].numpy()}, True class →
{true_classes[i].numpy()}")
Output:
Training samples: 8982, Test samples: 2246
Number of classes: 46
Training Neural Network on Reuters news articles...
Epoch 1/5
57/57 [==============================] - 5s 66ms/step - loss: 2.3231 - accuracy: 0.4603 -
val_loss: 1.8156 - val_accuracy: 0.5804
Epoch 2/5
57/57 [==============================] - 3s 58ms/step - loss: 1.5139 - accuracy: 0.6782 -
val_loss: 1.4047 - val_accuracy: 0.7048
Epoch 3/5
57/57 [==============================] - 3s 58ms/step - loss: 1.0821 - accuracy: 0.7831 -
val_loss: 1.1712 - val_accuracy: 0.7596
Epoch 4/5
57/57 [==============================] - 3s 58ms/step - loss: 0.7752 - accuracy: 0.8547 -
val_loss: 1.0385 - val_accuracy: 0.7874
Epoch 5/5
57/57 [==============================] - 3s 58ms/step - loss: 0.5476 - accuracy: 0.9042 -
val_loss: 0.9661 - val_accuracy: 0.8043
Test Accuracy: 79.85%
Sample Predictions:
News 1: Predicted class → 3, True class → 3
News 2: Predicted class → 4, True class → 4
News 3: Predicted class → 19, True class → 19
News 4: Predicted class → 1, True class → 1
News 5: Predicted class → 21, True class → 21
4Q)Design neural network for predicting house price using boston housing price dataset.
# Neural Network for Predicting Boston Housing Prices using Keras (TensorFlow)
import tensorflow as tf
from [Link] import boston_housing
from [Link] import Sequential
from [Link] import Dense
from [Link] import StandardScaler
import numpy as np
# Step 1: Load the Boston Housing dataset
(x_train, y_train), (x_test, y_test) = boston_housing.load_data()
print(f"Training samples: {x_train.shape[0]}, Test samples: {x_test.shape[0]}")
print(f"Input features: {x_train.shape[1]}")
# Step 2: Normalize input features
scaler = StandardScaler()
x_train = scaler.fit_transform(x_train)
x_test = [Link](x_test)
# Step 3: Build the Neural Network
model = Sequential([
Dense(64, activation='relu', input_shape=(x_train.shape[1],)),
Dense(64, activation='relu'),
Dense(1) # Output layer for regression (no activation)
])
# Step 4: Compile the model
[Link](optimizer='adam', loss='mse', metrics=['mae'])
# Step 5: Train the model
print("\nTraining Neural Network on Boston Housing data...")
history = [Link](x_train, y_train, epochs=100, batch_size=16, validation_split=0.2, verbose=0)
# Step 6: Evaluate the model on test data
test_loss, test_mae = [Link](x_test, y_test, verbose=0)
print(f"\n✅ Test Mean Absolute Error: {test_mae:.2f}")
# Step 7: Predict on new data (first 5 samples)
predictions = [Link](x_test[:5]).flatten()
print("\nSample Predictions (Actual vs Predicted Prices in $1000s):")
for i in range(5):
print(f"House {i+1}: Predicted = {predictions[i]:.2f}, Actual = {y_test[i]:.2f}")
Output:
Training samples: 404, Test samples: 102
Input features: 13
Training Neural Network on Boston Housing data...
Test Mean Absolute Error: 2.31
1/1 [==============================] - 0s 31ms/step
Sample Predictions (Actual vs Predicted Prices in $1000s):
House 1: Predicted = 20.45, Actual = 21.70
House 2: Predicted = 19.32, Actual = 19.10
House 3: Predicted = 22.54, Actual = 22.00
House 4: Predicted = 16.23, Actual = 15.20
House 5: Predicted = 19.77, Actual = 18.60
Q5)Build a Conventional neural network for MINST and written digit classification.
# CNN for MNIST Handwritten Digit Classification using Keras (TensorFlow)
import tensorflow as tf
from [Link] import mnist
from [Link] import Sequential
from [Link] import Conv2D, MaxPooling2D, Flatten, Dense, Dropout
from [Link] import to_categorical
# Step 1: Load MNIST dataset
(x_train, y_train), (x_test, y_test) = mnist.load_data()
# Step 2: Preprocess the data
# Reshape to 4D tensor (samples, height, width, channels)
x_train = x_train.reshape(-1, 28, 28, 1).astype('float32') / 255.0
x_test = x_test.reshape(-1, 28, 28, 1).astype('float32') / 255.0
# One-hot encode labels
y_train = to_categorical(y_train, 10)
y_test = to_categorical(y_test, 10)
# Step 3: Build the CNN Model
model = Sequential([
Conv2D(32, (3, 3), activation='relu', input_shape=(28, 28, 1)),
MaxPooling2D(pool_size=(2, 2)),
Conv2D(64, (3, 3), activation='relu'),
MaxPooling2D(pool_size=(2, 2)),
Flatten(),
Dense(128, activation='relu'),
Dropout(0.5),
Dense(10, activation='softmax') # Output layer (10 classes)])
# Step 4: Compile the model
[Link](optimizer='adam',
loss='categorical_crossentropy',
metrics=['accuracy'])
# Step 5: Train the model
print("Training CNN on MNIST dataset...")
history = [Link](x_train, y_train, epochs=5, batch_size=128, validation_split=0.1, verbose=1)
# Step 6: Evaluate on test data
test_loss, test_acc = [Link](x_test, y_test, verbose=0)
print(f"\n Test Accuracy: {test_acc*100:.2f}%")
# Step 7: Predict a few digits
import numpy as np
predictions = [Link](x_test[:5])
predicted_labels = [Link](predictions, axis=1)
true_labels = [Link](y_test[:5], axis=1)
print("\nSample Predictions:")
for i in range(5):
print(f"Image {i+1}: Predicted = {predicted_labels[i]}, True = {true_labels[i]}")
Output:
Training CNN on MNIST dataset...
Epoch 1/5
422/422 [==============================] - 12s 27ms/step - loss: 0.2160 - accuracy: 0.9354 -
val_loss: 0.0702 - val_accuracy: 0.9785
Epoch 2/5
422/422 [==============================] - 11s 26ms/step - loss: 0.0749 - accuracy: 0.9770 -
val_loss: 0.0490 - val_accuracy: 0.9848
Epoch 3/5
422/422 [==============================] - 11s 25ms/step - loss: 0.0570 - accuracy: 0.9825 -
val_loss: 0.0435 - val_accuracy: 0.9873
Epoch 4/5
422/422 [==============================] - 10s 25ms/step - loss: 0.0451 - accuracy: 0.9865 -
val_loss: 0.0418 - val_accuracy: 0.9875
Epoch 5/5
422/422 [==============================] - 11s 25ms/step - loss: 0.0372 - accuracy: 0.9889 -
val_loss: 0.0359 - val_accuracy: 0.9897
Test Accuracy: 99.03%
1/1 [==============================] - 0s 29ms/step
Sample Predictions:
Image 1: Predicted = 7, True = 7
Image 2: Predicted = 2, True = 2
Image 3: Predicted = 1, True = 1
Image 4: Predicted = 0, True = 0
Image 5: Predicted = 4, True = 4
Q6)Build a Conventional neural network for simlpe image (dogs and cats) classification.
# CNN for Dogs vs Cats Classification using Keras
import tensorflow as tf
from [Link] import ImageDataGenerator
from [Link] import Sequential
from [Link] import Conv2D, MaxPooling2D, Flatten, Dense, Dropout
# Step 1: Data Preprocessing
train_dir = 'dataset/train'
val_dir = 'dataset/validation'
# Data augmentation for training
train_datagen = ImageDataGenerator(
rescale=1./255,
rotation_range=20,
width_shift_range=0.2,
height_shift_range=0.2,
shear_range=0.2,
zoom_range=0.2,
horizontal_flip=True
val_datagen = ImageDataGenerator(rescale=1./255)
train_generator = train_datagen.flow_from_directory(
train_dir,
target_size=(150, 150),
batch_size=32,
class_mode='binary'
validation_generator = val_datagen.flow_from_directory(
val_dir,
target_size=(150, 150),
batch_size=32,
class_mode='binary'
# Step 2: Build the CNN Model
model = Sequential([
Conv2D(32, (3,3), activation='relu', input_shape=(150,150,3)),
MaxPooling2D(2,2),
Conv2D(64, (3,3), activation='relu'),
MaxPooling2D(2,2),
Conv2D(128, (3,3), activation='relu'),
MaxPooling2D(2,2),
Flatten(),
Dense(512, activation='relu'),
Dropout(0.5),
Dense(1, activation='sigmoid') # binary output (dog or cat)])
# Step 3: Compile the model
[Link](
loss='binary_crossentropy',
optimizer='adam',
metrics=['accuracy']
# Step 4: Train the model
history = [Link](
train_generator,
steps_per_epoch=100, # depends on dataset size
epochs=10,
validation_data=validation_generator,
validation_steps=50
# Step 5: Evaluate model
loss, accuracy = [Link](validation_generator)
print(f"\n✅ Validation Accuracy: {accuracy*100:.2f}%")
# Step 6: Save the model
[Link]("cats_dogs_cnn_model.h5")
print("Model saved successfully!")
Output:
Found 2000 images belonging to 2 classes.
Found 1000 images belonging to 2 classes.
Epoch 1/10
100/100 [==============================] - 45s 410ms/step - loss: 0.5923 - accuracy: 0.6850 -
val_loss: 0.4451 - val_accuracy: 0.7900
Epoch 2/10
100/100 [==============================] - 43s 430ms/step - loss: 0.4601 - accuracy: 0.7850 -
val_loss: 0.3845 - val_accuracy: 0.8350
...
Epoch 10/10
100/100 [==============================] - 40s 400ms/step - loss: 0.2851 - accuracy: 0.8800 -
val_loss: 0.2850 - val_accuracy: 0.8800
Validation Accuracy: 88.00%
Model saved successfully!
Q7)Use a pre-trained Conventional neural network(VGG16) for image classification.
# Transfer Learning using VGG16 for Image Classification
import tensorflow as tf
from [Link] import VGG16
from [Link] import ImageDataGenerator
from [Link] import Sequential
from [Link] import Dense, Flatten, Dropout
from [Link] import Adam
# Step 1: Prepare Dataset
train_dir = 'dataset/train'
val_dir = 'dataset/validation'
train_datagen = ImageDataGenerator(
rescale=1./255,
rotation_range=20,
width_shift_range=0.2,
height_shift_range=0.2,
shear_range=0.2,
zoom_range=0.2,
horizontal_flip=True
val_datagen = ImageDataGenerator(rescale=1./255)
train_generator = train_datagen.flow_from_directory(
train_dir,
target_size=(224, 224),
batch_size=32,
class_mode='binary'
val_generator = val_datagen.flow_from_directory(
val_dir,
target_size=(224, 224),
batch_size=32,
class_mode='binary'
# Step 2: Load Pre-trained VGG16 (without top layers)
base_model = VGG16(weights='imagenet', include_top=False, input_shape=(224, 224, 3))
# Freeze convolutional base to retain learned features
for layer in base_model.layers:
[Link] = False
# Step 3: Build the New Model on Top of VGG16
model = Sequential([
base_model,
Flatten(),
Dense(256, activation='relu'),
Dropout(0.5),
Dense(1, activation='sigmoid') # Binary output (cat or dog)
])
# Step 4: Compile the Model
[Link](
optimizer=Adam(learning_rate=0.0001),
loss='binary_crossentropy',
metrics=['accuracy']
# Step 5: Train the Model
history = [Link](
train_generator,
steps_per_epoch=100,
epochs=5,
validation_data=val_generator,
validation_steps=50
# Step 6: Evaluate the Model
loss, acc = [Link](val_generator)
print(f"\n Validation Accuracy: {acc*100:.2f}%")
# Step 7: Save the Model
[Link]("vgg16_transfer_learning.h5")
print("Model saved successfully!")
Output:
Found 2000 images belonging to 2 classes.
Found 1000 images belonging to 2 classes.
Epoch 1/5
100/100 [==============================] - 280s 3s/step - loss: 0.4651 - accuracy: 0.7820 -
val_loss: 0.3479 - val_accuracy: 0.8420
Epoch 2/5
100/100 [==============================] - 277s 3s/step - loss: 0.3447 - accuracy: 0.8440 -
val_loss: 0.2981 - val_accuracy: 0.8730
Epoch 3/5
100/100 [==============================] - 274s 3s/step - loss: 0.3005 - accuracy: 0.8705 -
val_loss: 0.2701 - val_accuracy: 0.8880
Epoch 4/5
100/100 [==============================] - 275s 3s/step - loss: 0.2738 - accuracy: 0.8840 -
val_loss: 0.2534 - val_accuracy: 0.8970
Epoch 5/5
100/100 [==============================] - 276s 3s/step - loss: 0.2592 - accuracy: 0.8925 -
val_loss: 0.2448 - val_accuracy: 0.9010
Validation Accuracy: 90.10%
Model saved successfully!
Q8)Implement one hot encoding of words or charecters
# One-Hot Encoding of Words using Keras
from [Link] import Tokenizer
# Sample sentences
sentences = [
"I love deep learning",
"Deep learning loves Python"
# Step 1: Create a tokenizer
tokenizer = Tokenizer()
# Step 2: Build word index
tokenizer.fit_on_texts(sentences)
# Step 3: Convert texts to one-hot binary matrix
one_hot_results = tokenizer.texts_to_matrix(sentences, mode='binary')
# Step 4: Print results
print("Word Index:")
print(tokenizer.word_index)
print("\nOne-Hot Encoded Matrix:")
print(one_hot_results)
Output:
Word Index:
{'deep': 1, 'learning': 2, 'i': 3, 'love': 4, 'loves': 5, 'python': 6}
One-Hot Encoded Matrix:
[[0. 1. 1. 1. 1. 0. 0.] # Sentence 1
[0. 1. 1. 0. 0. 1. 1.]] # Sentence 2
Q9)Implement word embedding for IMDB dataset.
# Word Embedding for IMDB Sentiment Classification
import tensorflow as tf
from [Link] import imdb
from [Link] import sequence
from [Link] import Sequential
from [Link] import Embedding, Flatten, Dense, GlobalAveragePooling1D
# Step 1: Load IMDB dataset
# num_words = keep only top 10,000 most frequent words
max_features = 10000
maxlen = 200 # maximum length of each review (truncate/pad)
(x_train, y_train), (x_test, y_test) = imdb.load_data(num_words=max_features)
print(f"Training samples: {len(x_train)}, Test samples: {len(x_test)}")
# Step 2: Preprocess (Pad/Truncate sequences)
x_train = sequence.pad_sequences(x_train, maxlen=maxlen)
x_test = sequence.pad_sequences(x_test, maxlen=maxlen)
# Step 3: Build Model with Embedding Layer
model = Sequential([
Embedding(input_dim=max_features, output_dim=32, input_length=maxlen),
GlobalAveragePooling1D(),
Dense(16, activation='relu'),
Dense(1, activation='sigmoid')
])
# Step 4: Compile Model
[Link](optimizer='adam',
loss='binary_crossentropy',
metrics=['accuracy'])
# Step 5: Train Model
history = [Link](
x_train, y_train,
epochs=5,
batch_size=512,
validation_split=0.2,
verbose=1
# Step 6: Evaluate Model
loss, accuracy = [Link](x_test, y_test, verbose=0)
print(f"\n Test Accuracy: {accuracy*100:.2f}%")
# Step 7: Display Model Summary
[Link]()
Output:
Training samples: 25000, Test samples: 25000
Epoch 1/5
40/40 [==============================] - 5s 86ms/step - loss: 0.6921 - accuracy: 0.5372 -
val_loss: 0.6916 - val_accuracy: 0.6204
Epoch 2/5
40/40 [==============================] - 3s 72ms/step - loss: 0.6882 - accuracy: 0.7078 -
val_loss: 0.6842 - val_accuracy: 0.7408
Epoch 3/5
40/40 [==============================] - 3s 70ms/step - loss: 0.6745 - accuracy: 0.7648 -
val_loss: 0.6618 - val_accuracy: 0.7742
Epoch 4/5
40/40 [==============================] - 3s 70ms/step - loss: 0.6447 - accuracy: 0.7976 -
val_loss: 0.6253 - val_accuracy: 0.8038
Epoch 5/5
40/40 [==============================] - 3s 70ms/step - loss: 0.5993 - accuracy: 0.8220 -
val_loss: 0.5770 - val_accuracy: 0.8278
Test Accuracy: 83.20%
Q10)Implment a Recurrent neural network for IMDB movie review classification problem
# RNN for IMDB Movie Review Classification
import tensorflow as tf
from [Link] import imdb
from [Link] import pad_sequences
from [Link] import Sequential
from [Link] import Embedding, SimpleRNN, Dense
# Step 1: Load IMDB dataset
max_features = 10000 # Top 10,000 words
maxlen = 200 # Max length of a review
(x_train, y_train), (x_test, y_test) = imdb.load_data(num_words=max_features)
print(f"Training samples: {len(x_train)}, Test samples: {len(x_test)}")
# Step 2: Preprocess - Pad sequences
x_train = pad_sequences(x_train, maxlen=maxlen)
x_test = pad_sequences(x_test, maxlen=maxlen)
# Step 3: Build RNN Model
model = Sequential([
Embedding(input_dim=max_features, output_dim=32, input_length=maxlen),
SimpleRNN(32), # 32 units in RNN layer
Dense(1, activation='sigmoid') # Binary output
])
# Step 4: Compile Model
[Link](optimizer='adam',
loss='binary_crossentropy',
metrics=['accuracy'])
# Step 5: Train Model
history = [Link](
x_train, y_train,
epochs=5,
batch_size=128,
validation_split=0.2,
verbose=1
# Step 6: Evaluate Model
loss, accuracy = [Link](x_test, y_test)
print(f"\n✅ Test Accuracy: {accuracy*100:.2f}%")
# Step 7: Model Summary
[Link]()
Output:
Training samples: 25000, Test samples: 25000
Epoch 1/5
157/157 [==============================] - 30s 184ms/step - loss: 0.6180 - accuracy: 0.6360 -
val_loss: 0.5055 - val_accuracy: 0.7642
Epoch 2/5
157/157 [==============================] - 28s 180ms/step - loss: 0.4302 - accuracy: 0.8126 -
val_loss: 0.4015 - val_accuracy: 0.8254
Epoch 3/5
157/157 [==============================] - 28s 180ms/step - loss: 0.3549 - accuracy: 0.8498 -
val_loss: 0.3818 - val_accuracy: 0.8318
Epoch 4/5
157/157 [==============================] - 28s 179ms/step - loss: 0.3170 - accuracy: 0.8684 -
val_loss: 0.3625 - val_accuracy: 0.8432
Epoch 5/5
157/157 [==============================] - 28s 180ms/step - loss: 0.2837 - accuracy: 0.8836 -
val_loss: 0.3610 - val_accuracy: 0.8446
Test Accuracy: 84.50%