AI Using Python
Hands-on Exercise No. 4
Task 1
import tensorflow as tf
from tensorflow import keras
import [Link] as plt
# -------------------------------
# Load Fashion-MNIST Dataset
# -------------------------------
(X_train, y_train), (X_test, y_test) = [Link].fashion_mnist.load_data()
print("Training Images Shape :", X_train.shape)
print("Training Labels Shape :", y_train.shape)
print("Testing Images Shape :", X_test.shape)
print("Testing Labels Shape :", y_test.shape)
# -------------------------------
# Normalize Pixel Values
# -------------------------------
X_train = X_train / 255.0
X_test = X_test / 255.0
# -------------------------------
# Reshape Images for CNN
# (28, 28) -> (28, 28, 1)
# -------------------------------
X_train = X_train.reshape(-1, 28, 28, 1)
X_test = X_test.reshape(-1, 28, 28, 1)
print("\nAfter Reshaping")
print("Training Images :", X_train.shape)
print("Testing Images :", X_test.shape)
# -------------------------------
# Fashion-MNIST Class Names
# -------------------------------
class_names = [
"T-shirt/Top",
"Trouser",
"Pullover",
"Dress",
"Coat",
"Sandal",
"Shirt",
"Sneaker",
"Bag",
"Ankle Boot"
]
# -------------------------------
# Display Sample Images
# -------------------------------
[Link](figsize=(10, 6))
for i in range(10):
[Link](2, 5, i + 1)
[Link](X_train[i].reshape(28, 28), cmap="gray")
[Link](class_names[y_train[i]])
[Link]("off")
plt.tight_layout()
[Link]()
Task 2
Task 3: Compile and Train the CNN
import tensorflow as tf
from tensorflow import keras
# -------------------------------
# Load Dataset
# -------------------------------
(X_train, y_train), (X_test, y_test) = [Link].fashion_mnist.load_data()
# Normalize
X_train = X_train / 255.0
X_test = X_test / 255.0
# Reshape for CNN
X_train = X_train.reshape(-1, 28, 28, 1)
X_test = X_test.reshape(-1, 28, 28, 1)
# -------------------------------
# Build CNN Model
# -------------------------------
model = [Link]([
[Link](shape=(28, 28, 1)),
[Link].Conv2D(32, (3,3), activation="relu"),
[Link].MaxPooling2D((2,2)),
[Link].Conv2D(64, (3,3), activation="relu"),
[Link].MaxPooling2D((2,2)),
[Link](),
[Link](128, activation="relu"),
[Link](10, activation="softmax")
])
# -------------------------------
# Compile Model
# -------------------------------
[Link](
optimizer="adam",
loss="sparse_categorical_crossentropy",
metrics=["accuracy"]
)
# -------------------------------
# Train Model
# -------------------------------
history = [Link](
X_train,
y_train,
epochs=5,
validation_data=(X_test, y_test)
)
print("\nTraining Completed Successfully!")
Task 4: Evaluate the Model and Make Predictions.
import tensorflow as tf
from tensorflow import keras
import [Link] as plt
# -------------------------------
# Load Dataset
# -------------------------------
(X_train, y_train), (X_test, y_test) = [Link].fashion_mnist.load_data()
# Normalize
X_train = X_train / 255.0
X_test = X_test / 255.0
# Reshape for CNN
X_train = X_train.reshape(-1, 28, 28, 1)
X_test = X_test.reshape(-1, 28, 28, 1)
# -------------------------------
# Build CNN Model
# -------------------------------
model = [Link]([
[Link](shape=(28, 28, 1)),
[Link].Conv2D(32, (3, 3), activation="relu"),
[Link].MaxPooling2D((2, 2)),
[Link].Conv2D(64, (3, 3), activation="relu"),
[Link].MaxPooling2D((2, 2)),
[Link](),
[Link](128, activation="relu"),
[Link](10, activation="softmax")
])
# -------------------------------
# Compile Model
# -------------------------------
[Link](
optimizer="adam",
loss="sparse_categorical_crossentropy",
metrics=["accuracy"]
)
# -------------------------------
# Train Model
# -------------------------------
[Link](
X_train,
y_train,
epochs=5,
validation_data=(X_test, y_test),
verbose=1
)
# -------------------------------
# Evaluate Model
# -------------------------------
test_loss, test_accuracy = [Link](X_test, y_test, verbose=0)
print("\n==============================")
print(f"Test Loss : {test_loss:.4f}")
print(f"Test Accuracy : {test_accuracy * 100:.2f}%")
print("==============================")
# -------------------------------
# Fashion-MNIST Labels
# -------------------------------
class_names = [
"T-shirt/Top",
"Trouser",
"Pullover",
"Dress",
"Coat",
"Sandal",
"Shirt",
"Sneaker",
"Bag",
"Ankle Boot"
]
# -------------------------------
# Predict First 10 Images
# -------------------------------
predictions = [Link](X_test[:10])
[Link](figsize=(12, 6))
for i in range(10):
[Link](2, 5, i + 1)
[Link](X_test[i].reshape(28, 28), cmap="gray")
predicted_label = class_names[predictions[i].argmax()]
actual_label = class_names[y_test[i]]
[Link](f"P: {predicted_label}\nA: {actual_label}", fontsize=9)
[Link]("off")
plt.tight_layout()
[Link]()
Task 5
import tensorflow as tf
from tensorflow import keras
import [Link] as plt
# ==========================================================
# Task 1: Load and Prepare Fashion-MNIST Dataset
# ==========================================================
(X_train, y_train), (X_test, y_test) = [Link].fashion_mnist.load_data()
print("Training Images Shape :", X_train.shape)
print("Training Labels Shape :", y_train.shape)
print("Testing Images Shape :", X_test.shape)
print("Testing Labels Shape :", y_test.shape)
# Normalize pixel values
X_train = X_train / 255.0
X_test = X_test / 255.0
# Reshape images for CNN
X_train = X_train.reshape(-1, 28, 28, 1)
X_test = X_test.reshape(-1, 28, 28, 1)
print("\nAfter Reshaping")
print("Training Images :", X_train.shape)
print("Testing Images :", X_test.shape)
# Fashion-MNIST Classes
class_names = [
"T-shirt/Top",
"Trouser",
"Pullover",
"Dress",
"Coat",
"Sandal",
"Shirt",
"Sneaker",
"Bag",
"Ankle Boot"
]
# Display Sample Images
[Link](figsize=(10,6))
for i in range(10):
[Link](2,5,i+1)
[Link](X_train[i].reshape(28,28), cmap="gray")
[Link](class_names[y_train[i]])
[Link]("off")
plt.tight_layout()
[Link]()
# ==========================================================
# Task 2: Build CNN Model
# ==========================================================
model = [Link]([
[Link].Conv2D(
filters=32,
kernel_size=(3,3),
activation='relu',
input_shape=(28,28,1)
),
[Link].MaxPooling2D((2,2)),
[Link].Conv2D(
filters=64,
kernel_size=(3,3),
activation='relu'
),
[Link].MaxPooling2D((2,2)),
[Link](),
[Link](
128,
activation='relu'
),
[Link](
10,
activation='softmax'
)
])
print("\n================ MODEL SUMMARY ================\n")
[Link]()
# ==========================================================
# Task 3: Compile and Train Model
# ==========================================================
[Link](
optimizer='adam',
loss='sparse_categorical_crossentropy',
metrics=['accuracy']
)
history = [Link](
X_train,
y_train,
epochs=10,
validation_data=(X_test, y_test)
)
# ==========================================================
# Task 4: Evaluate Model
# ==========================================================
test_loss, test_accuracy = [Link](X_test, y_test)
print("\n================ RESULTS ================")
print("Test Loss :", test_loss)
print("Test Accuracy :", test_accuracy)
# ==========================================================
# Task 5: Visualization and Analysis
# ==========================================================
# Accuracy Graph
[Link](figsize=(12,5))
[Link](1,2,1)
[Link]([Link]['accuracy'], label='Training Accuracy')
[Link]([Link]['val_accuracy'], label='Validation Accuracy')
[Link]("Training vs Validation Accuracy")
[Link]("Epoch")
[Link]("Accuracy")
[Link]()
# Loss Graph
[Link](1,2,2)
[Link]([Link]['loss'], label='Training Loss')
[Link]([Link]['val_loss'], label='Validation Loss')
[Link]("Training vs Validation Loss")
[Link]("Epoch")
[Link]("Loss")
[Link]()
plt.tight_layout()
[Link]()
# ==========================================================
# Predict Test Images
# ==========================================================
predictions = [Link](X_test)
predicted_labels = [Link](axis=1)
# ==========================================================
# Display Predictions
# ==========================================================
[Link](figsize=(12,6))
for i in range(10):
[Link](2,5,i+1)
[Link](X_test[i].reshape(28,28), cmap="gray")
[Link](
f"Pred: {class_names[predicted_labels[i]]}\nTrue: {class_names[y_test[i]]}",
fontsize=8
)
[Link]("off")
plt.tight_layout()
[Link]()
print("\nTask 5 Completed Successfully!")