Certainly! Below is a comprehensive guide with code snippets to help you complete each task in your homework using a Jupyter or Google Colab notebook. Ensure that all necessary libraries are installed in your environment. You can run each cell sequentially.
1. Download and Split the CIFAR-10 Dataset
We will use torchvision.datasets.CIFAR10 to download and load the dataset, then split it into training and testing sets.
# Import necessary libraries
import torch
import torchvision
import torchvision.transforms as transforms
from torch.utils.data import DataLoader, random_split
# Define transformations for the dataset
transform = transforms.Compose([
transforms.ToTensor(),
transforms.Normalize((0.5, 0.5, 0.5), # mean for each channel
(0.5, 0.5, 0.5)) # std for each channel
])
# Download and load the training set
train_dataset = torchvision.datasets.CIFAR10(root='./data', train=True,
download=True, transform=transform)
# Download and load the test set
test_dataset = torchvision.datasets.CIFAR10(root='./data', train=False,
download=True, transform=transform)
# Verify dataset sizes
print(f"Training set size: {len(train_dataset)}")
print(f"Test set size: {len(test_dataset)}")
# Create data loaders
train_loader = DataLoader(train_dataset, batch_size=64, shuffle=True, num_workers=2)
test_loader = DataLoader(test_dataset, batch_size=64, shuffle=False, num_workers=2)
Explanation:
- We define a transformation to convert images to tensors and normalize them.
- Download the CIFAR-10 training and test datasets.
- Create data loaders for batching.
2. Extract Embeddings Using ResNet-18
We'll use a pre-trained ResNet-18 model, remove its final fully connected layer, and use it to extract embeddings from the test set.
import torch.nn as nn
import torchvision.models as models
# Load pre-trained ResNet-18 model
resnet18 = models.resnet18(pretrained=True)
# Modify the model to remove the final classification layer
# The last layer is 'fc', so we'll replace it with an identity function
resnet18.fc = nn.Identity()
# Move the model to GPU if available
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
resnet18 = resnet18.to(device)
resnet18.eval() # Set to evaluation mode
# Function to extract embeddings
def extract_embeddings(dataloader, model):
embeddings = []
labels = []
with torch.no_grad():
for images, lbls in dataloader:
images = images.to(device)
output = model(images)
embeddings.append(output.cpu())
labels.append(lbls)
embeddings = torch.cat(embeddings)
labels = torch.cat(labels)
return embeddings, labels
# Extract embeddings for test set
test_embeddings, test_labels = extract_embeddings(test_loader, resnet18)
print(f"Test Embeddings Shape: {test_embeddings.shape}")
print(f"Test Labels Shape: {test_labels.shape}")
Explanation:
- Load the pre-trained ResNet-18 model.
- Replace the final fully connected layer with an identity function to get embeddings instead of class scores.
- Define a function to extract embeddings from a given dataloader.
- Extract embeddings for the test set.
3. Apply t-SNE for Visualization
Use t-SNE to reduce the high-dimensional embeddings to 2D and visualize the clusters.
import matplotlib.pyplot as plt
from sklearn.manifold import TSNE
import numpy as np
# For visualization, we'll take a subset to speed up t-SNE
subset_size = 2000
indices = np.random.choice(len(test_embeddings), subset_size, replace=False)
subset_embeddings = test_embeddings[indices].numpy()
subset_labels = test_labels[indices].numpy()
# Apply t-SNE
tsne = TSNE(n_components=2, random_state=42, perplexity=30, n_iter=300)
tsne_results = tsne.fit_transform(subset_embeddings)
# Plotting
plt.figure(figsize=(10, 8))
scatter = plt.scatter(tsne_results[:,0], tsne_results[:,1], c=subset_labels, cmap='tab10', alpha=0.6)
plt.legend(*scatter.legend_elements(), title="Classes")
plt.title("t-SNE Visualization of CIFAR-10 Test Set Embeddings")
plt.xlabel("t-SNE Dimension 1")
plt.ylabel("t-SNE Dimension 2")
plt.show()
Explanation:
- Select a random subset of embeddings for faster t-SNE computation.
- Apply t-SNE to reduce embeddings to 2D.
- Plot the 2D embeddings with colors representing different classes.
Interpretation:
- Analyze the plot to see how well different classes cluster. Tight clusters indicate that embeddings effectively capture class structures.
4. Nearest Neighbor Classification
a. Nearest Neighbor with Cosine Similarity and Euclidean Distance
We'll compute the centroids for each class in the training embeddings and classify test samples based on the nearest centroid using both cosine similarity and Euclidean distance.
from sklearn.metrics import confusion_matrix, accuracy_score
import torch.nn.functional as F
# First, extract embeddings for the training set
train_embeddings, train_labels = extract_embeddings(train_loader, resnet18)
# Compute centroids for each class
num_classes = 10
centroids = []
for c in range(num_classes):
class_embeddings = train_embeddings[train_labels == c]
centroid = class_embeddings.mean(dim=0)
centroids.append(centroid)
centroids = torch.stack(centroids) # Shape: [10, embedding_dim]
# Function to compute nearest neighbor classification
def nearest_centroid_classification(test_emb, centroids, metric='euclidean'):
if metric == 'euclidean':
# Compute Euclidean distances
distances = torch.cdist(test_emb, centroids)
preds = torch.argmin(distances, dim=1)
elif metric == 'cosine':
# Normalize embeddings and centroids
test_norm = F.normalize(test_emb, p=2, dim=1)
centroids_norm = F.normalize(centroids, p=2, dim=1)
# Compute cosine similarity
similarities = torch.mm(test_norm, centroids_norm.t())
preds = torch.argmax(similarities, dim=1)
return preds
# Perform classification with Euclidean distance
euclidean_preds = nearest_centroid_classification(test_embeddings, centroids, metric='euclidean')
# Perform classification with Cosine similarity
cosine_preds = nearest_centroid_classification(test_embeddings, centroids, metric='cosine')
# Compute confusion matrices
import seaborn as sns
def plot_confusion(y_true, y_pred, title):
cm = confusion_matrix(y_true, y_pred)
plt.figure(figsize=(8,6))
sns.heatmap(cm, annot=True, fmt='d', cmap='Blues',
xticklabels=train_dataset.classes,
yticklabels=train_dataset.classes)
plt.ylabel('Actual')
plt.xlabel('Predicted')
plt.title(title)
plt.show()
# Confusion matrix for Euclidean
plot_confusion(test_labels.numpy(), euclidean_preds.numpy(), "Confusion Matrix - Euclidean Distance")
# Confusion matrix for Cosine
plot_confusion(test_labels.numpy(), cosine_preds.numpy(), "Confusion Matrix - Cosine Similarity")
# Accuracy scores
euclidean_acc = accuracy_score(test_labels.numpy(), euclidean_preds.numpy())
cosine_acc = accuracy_score(test_labels.numpy(), cosine_preds.numpy())
print(f"Nearest Centroid Classification Accuracy:")
print(f"Euclidean Distance: {euclidean_acc * 100:.2f}%")
print(f"Cosine Similarity: {cosine_acc * 100:.2f}%")
Explanation:
- Extract embeddings for the training set.
- Compute centroids for each class by averaging embeddings.
- Define a function for nearest centroid classification using either Euclidean distance or cosine similarity.
- Compute predictions for the test set using both metrics.
- Plot confusion matrices and compute accuracy scores.
b. Identifying Outliers in Each Class
For each class, find the test image furthest from its centroid.
import pandas as pd
# Function to find the furthest image from centroid for each class
def find_furthest_images(test_emb, test_lbls, centroids, metric='euclidean'):
furthest_indices = []
for c in range(num_classes):
class_mask = (test_lbls == c)
class_emb = test_emb[class_mask]
indices = torch.where(class_mask)[0]
if metric == 'euclidean':
distances = torch.norm(class_emb - centroids[c], dim=1)
elif metric == 'cosine':
distances = 1 - F.cosine_similarity(class_emb, centroids[c].unsqueeze(0))
max_dist, max_idx = torch.max(distances, dim=0)
furthest_index = indices[max_idx].item()
furthest_indices.append(furthest_index)
return furthest_indices
# Find furthest images using Euclidean distance
furthest_euclidean = find_furthest_images(test_embeddings, test_labels, centroids, metric='euclidean')
# Find furthest images using Cosine similarity
furthest_cosine = find_furthest_images(test_embeddings, test_labels, centroids, metric='cosine')
# Function to display images
def show_image(dataset, index, title="Image"):
img, label = dataset[index]
# Undo normalization
img = img * 0.5 + 0.5 # unnormalize
np_img = img.numpy().transpose((1, 2, 0))
plt.imshow(np_img)
plt.title(f"{title} - {dataset.classes[label]}")
plt.axis('off')
plt.show()
# Display furthest images
print("Furthest Images from Centroids (Euclidean Distance):")
for c, idx in enumerate(furthest_euclidean):
show_image(test_dataset, idx, title=f"Class: {test_dataset.classes[c]}")
print("Furthest Images from Centroids (Cosine Similarity):")
for c, idx in enumerate(furthest_cosine):
show_image(test_dataset, idx, title=f"Class: {test_dataset.classes[c]}")
Explanation:
- Define a function to find the furthest test image from the centroid for each class using the specified metric.
- Identify the furthest images using both Euclidean distance and cosine similarity.
- Display these images to analyze if they are outliers, difficult cases, or potentially mislabeled.
Interpretation:
- Examine the displayed images to see if they indeed appear as outliers or are possibly mislabeled by checking their nearest centroid assignments.
5. Image Classification Using a Model
We'll build a simple classification model using logistic regression to classify images based on their embeddings.
a. Building and Evaluating the Classification Model
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import classification_report
# Convert embeddings and labels to NumPy
train_emb_np = train_embeddings.numpy()
train_lbl_np = train_labels.numpy()
test_emb_np = test_embeddings.numpy()
test_lbl_np = test_labels.numpy()
# Initialize and train logistic regression model
log_reg = LogisticRegression(max_iter=1000, multi_class='multinomial', solver='saga', verbose=1, n_jobs=-1)
log_reg.fit(train_emb_np, train_lbl_np)
# Predict on test set
log_reg_preds = log_reg.predict(test_emb_np)
# Confusion matrix
plot_confusion(test_lbl_np, log_reg_preds, "Confusion Matrix - Logistic Regression")
# Classification report
print("Classification Report - Logistic Regression:")
print(classification_report(test_lbl_np, log_reg_preds, target_names=train_dataset.classes))
Explanation:
- Convert PyTorch tensors to NumPy arrays for compatibility with scikit-learn.
- Train a logistic regression model on the training embeddings.
- Predict on the test embeddings.
- Plot the confusion matrix and display a detailed classification report.
b. Comparing Nearest Neighbor and Model-Based Classification
# Compare predictions
print("Accuracy Comparison:")
print(f"Nearest Centroid (Euclidean): {euclidean_acc * 100:.2f}%")
print(f"Nearest Centroid (Cosine): {cosine_acc * 100:.2f}%")
log_reg_acc = accuracy_score(test_lbl_np, log_reg_preds)
print(f"Logistic Regression: {log_reg_acc * 100:.2f}%")
# Analyze confusion matrices side by side
# For simplicity, visualize only the logistic regression confusion matrix here,
# since the nearest centroid confusion matrices were already plotted earlier.
# Check if they make similar mistakes
# Example: Identify specific classes where predictions differ
# Find indices where models disagree
diff_indices = np.where((euclidean_preds.numpy() != log_reg_preds) & (log_reg_preds != test_lbl_np))[0]
print(f"Number of test samples where Nearest Centroid and Logistic Regression disagree and are incorrect: {len(diff_indices)}")
# Optionally, display some examples
for i in range(min(5, len(diff_indices))):
idx = diff_indices[i]
show_image(test_dataset, idx, title=f"Misclassified by Both Models - Actual: {test_dataset.classes[test_lbl_np[idx]]}, "
f"Euclidean Pred: {train_dataset.classes[euclidean_preds[idx]]}, "
f"LogReg Pred: {train_dataset.classes[log_reg_preds[idx]]}")
Explanation:
- Compare the accuracy of nearest centroid methods with logistic regression.
- Optionally, analyze where the models disagree and investigate specific misclassifications.
Interpretation:
- Determine which approach (nearest centroid vs. logistic regression) performs better overall.
- Check if models make similar or different types of errors.
6. Experiment with Dimension Reduction
We'll use PCA to reduce the embedding dimensions and observe the impact on classification and t-SNE visualization.
from sklearn.decomposition import PCA
# Function to perform PCA and evaluate
def pca_evaluation(train_emb, test_emb, train_lbl, test_lbl, n_components):
pca = PCA(n_components=n_components, random_state=42)
train_emb_pca = pca.fit_transform(train_emb)
test_emb_pca = pca.transform(test_emb)
print(f"PCA reduced embeddings to {n_components} dimensions.")
# Train logistic regression on reduced embeddings
log_reg_pca = LogisticRegression(max_iter=1000, multi_class='multinomial', solver='saga', verbose=0, n_jobs=-1)
log_reg_pca.fit(train_emb_pca, train_lbl)
preds_pca = log_reg_pca.predict(test_emb_pca)
acc_pca = accuracy_score(test_lbl, preds_pca)
print(f"Logistic Regression Accuracy with {n_components}D embeddings: {acc_pca * 100:.2f}%")
# Perform t-SNE on reduced embeddings
subset_size = 2000
indices = np.random.choice(len(test_emb_pca), subset_size, replace=False)
subset_emb = test_emb_pca[indices]
subset_lbl = test_lbl[indices]
tsne = TSNE(n_components=2, random_state=42, perplexity=30, n_iter=300)
tsne_results = tsne.fit_transform(subset_emb)
# Plotting
plt.figure(figsize=(10, 8))
scatter = plt.scatter(tsne_results[:,0], tsne_results[:,1], c=subset_lbl, cmap='tab10', alpha=0.6)
plt.legend(*scatter.legend_elements(), title="Classes")
plt.title(f"t-SNE Visualization with {n_components}D PCA-Reduced Embeddings")
plt.xlabel("t-SNE Dimension 1")
plt.ylabel("t-SNE Dimension 2")
plt.show()
return acc_pca
# Evaluate with 10 dimensions
acc_pca_10 = pca_evaluation(train_emb_np, test_emb_np, train_lbl_np, test_lbl_np, n_components=10)
# Evaluate with 50 dimensions
acc_pca_50 = pca_evaluation(train_emb_np, test_emb_np, train_lbl_np, test_lbl_np, n_components=50)
# Compare with full embeddings
log_reg_full = LogisticRegression(max_iter=1000, multi_class='multinomial', solver='saga', verbose=0, n_jobs=-1)
log_reg_full.fit(train_emb_np, train_lbl_np)
preds_full = log_reg_full.predict(test_emb_np)
acc_full = accuracy_score(test_lbl_np, preds_full)
print(f"Logistic Regression Accuracy with full embeddings: {acc_full * 100:.2f}%")
Explanation:
- Define a function to perform PCA, train a logistic regression model, and visualize with t-SNE.
- Reduce embeddings to 10 and 50 dimensions and evaluate the impact.
- Compare the performance with full (original) embeddings.
Interpretation:
- Analyze whether reducing dimensions affects classification accuracy and the quality of t-SNE visualizations.
- Determine if there's a trade-off between dimensionality and performance or if dimensionality reduction even improves performance due to noise reduction.
Summary and Findings
Ensure to document your observations based on the results obtained from each task:
-
Dataset Loading: Successfully loaded and split the CIFAR-10 dataset into training and testing sets.
-
Embedding Extraction: ResNet-18 effectively extracted meaningful embeddings from the images by removing the final classification layer.
-
t-SNE Visualization: The 2D t-SNE plot should show distinct clusters for each class, indicating that the embeddings capture class-related features well.
-
Nearest Neighbor Classification:
- Euclidean distance and cosine similarity provide different perspectives on similarity.
- Evaluate which metric yields higher accuracy and better confusion matrices.
-
Outlier Detection: Identified furthest images from centroids could reveal challenging or mislabeled samples.
-
Model-Based Classification:
- Logistic regression might outperform nearest centroid methods due to its ability to find decision boundaries.
- Compare confusion matrices to understand different error patterns.
-
Dimension Reduction: Applying PCA can reduce computational complexity and possibly improve generalization by eliminating noise. Assess whether reducing to 10 or 50 dimensions maintains or enhances classification performance and visualization quality.
Recommendations:
- Choose the classification method that best balances accuracy and computational efficiency based on your findings.
- Consider using dimension reduction techniques to optimize model performance without significant loss in accuracy.
Feel free to integrate these code snippets and explanations into your Colab notebook. Ensure to run each cell sequentially and verify the outputs at each step. Good luck with your homework!