i have a pdf which is a homework for me, help me in completing the tasks mentioned in the notebook,
also i have a boiler colab notebook, where i have to fill the code and add if anything is necessary..
Download the CIFAR-10 dataset, which contains 60,000 32x32 color images across 10
different classes, including airplanes, cars, birds, cats, and others. You can download it
using the torchvision.datasets.CIFAR 10 module. Load the dataset and split it into
training (50,000 images) and testing (10,000 images) sets. (5 points)
2. To perform analysis on these images, use ResNet-18 (torchvision.models.resnet18), a
well-known convolutional neural network (CNN) designed for image classification.
Remove the final classification layer of ResNet18 (since it’s trained for ImageNet) and
use the rest of the network to extract embeddings (features) from the test set. (5 points)
3. After extracting the embeddings, apply the t-SNE algorithm (sklearn.manifold.TSNE),
which reduces the high-dimensional data (embeddings) into 2D for visualization. The
resulting plot will show how well the model clusters similar images. How well do the
embeddings reflect the structure of the classes? (5 points)
4. Nearest neighbor classification: Construct the centroid of each object class in embedding
space from the training data. Now perform object classification by the label of the
nearest neighbor among the 10 centroids.
a. Experiment with both cosine similarity and Euclidean distance. For each object
construct the confusion matrix and evaluate how well the nearest neighbor
classification works. (5 points)
b. For each of the ten object types, identify which image is furthest from its centroid,
ie. is an outlier to its class? Are these difficult cases? Are they mislabeled by
mean closest to another centroid? (5 points)
Image Classification from a model: Build a classification model that uses the top level
embedding as features to classify the objects. This could be logistic regression, random
forests, or other methods.
a. As above, build the confusion matrix and evaluate how well it works. (5 points)
b. Compare the performance of nearest-neighbor and model based classification:
do they make similar mistakes or not? Which approach does best? (5 points)
6. Experiment with dimension reduction on these embeddings, using PCA or SVD. Cut
them down to 10 dimensions and 50 dimensions, and compare the performance on
classification and TSNE to the full embeddings. Do we lose much performance? Or
might it even get better? Explain your findings. (10 points)
I need all of the code in a notebook or corresponding code snippets.
Assistant
Sure, I'll help guide you through these tasks step-by-step by providing code snippets for your Google Colab notebook. Let's tackle each question one by one.
1. Load the CIFAR-10 Dataset
First, you need to import the dataset and split it into training and testing sets.
python
import torch
import torchvision
import torchvision.transforms as transforms
# Define transformations for the training set, flip the images randomly
transform = transforms.Compose(
[transforms.ToTensor(),
transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))])
# Download and load the training data
trainset = torchvision.datasets.CIFAR10(root='./data', train=True,
download=True, transform=transform)
trainloader = torch.utils.data.DataLoader(trainset, batch_size=100,
shuffle=True, num_workers=2)
# Download and load the testing data
testset = torchvision.datasets.CIFAR10(root='./data', train=False,
download=True, transform=transform)
testloader = torch.utils.data.DataLoader(testset, batch_size=100,
shuffle=False, num_workers=2)
2. Use ResNet-18 to Extract Embeddings
Next, we need to use ResNet-18 without the final classification layer to extract embeddings.
python
import torch.nn as nn
import torchvision.models as models
# Load the pre-trained ResNet-18 model
resnet18 = models.resnet18(pretrained=True)
# Remove the final classification layer
modules = list(resnet18.children())[:-1]
resnet18 = nn.Sequential(*modules)
# Set the model to evaluation mode
resnet18.eval()
# Ensure model is on the right device (GPU if available, else CPU)
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
resnet18 = resnet18.to(device)
# Function to get embeddings
def get_embeddings(dataloader):
embeddings = []
labels = []
with torch.no_grad():
for inputs, targets in dataloader:
inputs = inputs.to(device)
output = resnet18(inputs)
embeddings.append(output.view(output.size(0), -1))
labels.append(targets)
embeddings = torch.cat(embeddings).cpu()
labels = torch.cat(labels).cpu()
return embeddings, labels
# Get test set embeddings
test_embeddings, test_labels = get_embeddings(testloader)
3. Apply t-SNE on the Test Embeddings
Now, we'll reduce the embeddings to 2D using t-SNE and plot the results.
python
import matplotlib.pyplot as plt
import seaborn as sns
from sklearn.manifold import TSNE
# Apply t-SNE
tsne = TSNE(n_components=2, random_state=0)
test_embeddings_2d = tsne.fit_transform(test_embeddings)
# Plot
plt.figure(figsize=(10, 8))
sns.scatterplot(
x=test_embeddings_2d[:, 0], y=test_embeddings_2d[:, 1],
hue=test_labels.numpy(), palette=sns.color_palette("hsv", 10),
legend="full", alpha=0.3
)
plt.title('t-SNE of CIFAR-10 test embeddings')
plt.show()
4. Nearest Neighbor Classification
a. Calculate Centroids and Classify
We will calculate class centroids in the embedding space and perform a nearest centroid classification.
python
from sklearn.metrics import confusion_matrix, ConfusionMatrixDisplay
import numpy as np
from scipy.spatial.distance import cdist
def compute_centroids(embeddings, labels):
centroids = []
for label in range(10): # 10 classes
indexes = (labels == label).nonzero(as_tuple=True)[0]
centroid = embeddings[indexes].mean(dim=0)
centroids.append(centroid.numpy())
return np.array(centroids)
def nearest_centroid_classification(embeddings, centroids, metric='euclidean'):
distances = cdist(embeddings, centroids, metric=metric)
return distances.argmin(axis=1)
# Compute centroids from the training data
train_embeddings, train_labels = get_embeddings(trainloader)
centroids = compute_centroids(train_embeddings, train_labels)
# Classify test data
predicted_labels_euclidean = nearest_centroid_classification(test_embeddings, centroids, metric='euclidean')
predicted_labels_cosine = nearest_centroid_classification(test_embeddings, centroids, metric='cosine')
# Display confusion matrix - Euclidean
conf_matrix_euclidean = confusion_matrix(test_labels, predicted_labels_euclidean)
ConfusionMatrixDisplay(conf_matrix_euclidean).plot()
plt.title('Confusion Matrix - Euclidean')
plt.show()
# Display confusion matrix - Cosine
conf_matrix_cosine = confusion_matrix(test_labels, predicted_labels_cosine)
ConfusionMatrixDisplay(conf_matrix_cosine).plot()
plt.title('Confusion Matrix - Cosine')
plt.show()
You can incorporate these code snippets into your Colab notebook. Remember to install any missing dependencies and ensure your runtime environment (e.g., correct version of PyTorch and torchvision) is properly set. Additionally, analyze the plots and confusion matrices to answer the qualitative questions about clustering quality, classification performance, and dimensionality reduction effects.