import os
import tarfile
import random
import torch
import numpy as np
from torchvision import models, transforms
from sklearn.mixture import GaussianMixture
from sklearn.metrics import accuracy_score
from sklearn.linear_model import LogisticRegression
import tempfile
import shutil
# Define MemoryBuffer class
class MemoryBuffer:
def __init__(self, capacity):
self.capacity = capacity
self.buffer = []
def add_samples(self, images, labels):
"""Add images and labels to the memory buffer."""
for image, label in zip(images, labels):
if len(self.buffer) >= self.capacity:
self.buffer.pop(0) # Remove the oldest sample if buffer is full
self.buffer.append((image, label))
def get_replay_data(self, sample_size=1000):
"""Randomly sample a subset of data from the buffer for replay."""
if len(self.buffer) == 0:
return np.array([]), np.array([]) # Return empty if no data
sample_size = min(sample_size, len(self.buffer))
sampled_data = random.sample(self.buffer, sample_size)
images, labels = zip(*sampled_data)
return torch.stack(images), torch.tensor(labels)
# Define LwPClassifier
class LwPClassifier:
def __init__(self):
self.model = LogisticRegression(max_iter=1000)
def train(self, features, labels):
self.model.fit(features, labels)
def predict(self, features):
return self.model.predict(features)
def update(self, features_new, labels_new, replay_features, replay_labels, domain_adaptation=False):
# Combine new data with replay data
if replay_features.size > 0:
combined_features = np.vstack((features_new, replay_features))
combined_labels = np.hstack((labels_new, replay_labels))
else:
combined_features = features_new
combined_labels = labels_new
self.model.fit(combined_features, combined_labels)
# Define GMM related functions
def fit_gmm(features, n_components=10):
"""Fit a Gaussian Mixture Model to the features."""
gmm = GaussianMixture(n_components=n_components, covariance_type='full', random_state=42)
gmm.fit(features)
return gmm
def consolidate_gmm(existing_gmm, new_gmm):
"""Combine two GMMs."""
if existing_gmm is None:
return new_gmm
combined_means = np.vstack((existing_gmm.means_, new_gmm.means_))
combined_covariances = np.vstack((existing_gmm.covariances_, new_gmm.covariances_))
combined_weights = np.hstack((existing_gmm.weights_, new_gmm.weights_))
consolidated_gmm = GaussianMixture(n_components=combined_means.shape[0],
covariance_type='full',
random_state=42)
consolidated_gmm.weights_ = combined_weights / combined_weights.sum()
consolidated_gmm.means_ = combined_means
consolidated_gmm.covariances_ = combined_covariances
return consolidated_gmm
def align_features(features, gmm):
"""Align features based on the internal GMM."""
# Placeholder: Implement actual alignment if needed
return features
# Function to load dataset from .tar.pth
def load_tar_pth_dataset(file_path):
"""Load a .tar.pth file and extract the contained .pth dataset."""
try:
temp_dir = tempfile.mkdtemp()
with tarfile.open(file_path, 'r') as archive:
archive_contents = archive.getnames()
print(f"Contents of the archive '{file_path}': {archive_contents}")
archive.extractall(temp_dir)
# Search for a .pth file within the extracted contents
pth_files = [f for f in os.listdir(temp_dir) if f.endswith('.pth')]
if not pth_files:
print(f"Error: No .pth file found in the archive '{file_path}'.")
shutil.rmtree(temp_dir)
return None, None
pth_file_path = os.path.join(temp_dir, pth_files[0])
dataset = torch.load(pth_file_path)
images = dataset['images'] # Tensor of shape (N, C, H, W)
labels = dataset['labels'] # Tensor of shape (N,)
# Clean up temporary directory
shutil.rmtree(temp_dir)
return images, labels
except Exception as e:
print(f"Error loading tar file '{file_path}': {e}")
return None, None
# Initialize ResNet50 feature extractor
def initialize_resnet50():
"""Initialize the ResNet50 model and preprocessing pipeline."""
preprocess = transforms.Compose([
transforms.ToPILImage(), # Convert tensor to PIL Image
transforms.Resize(256), # Resize to 256x256
transforms.CenterCrop(224), # Crop to 224x224
transforms.ToTensor(), # Convert back to tensor
transforms.Normalize(mean=[0.485, 0.456, 0.406],
std=[0.229, 0.224, 0.225]) # Normalize
])
resnet50 = models.resnet50(pretrained=True)
resnet50.eval()
# Remove the final classification layer to get features
feature_extractor = torch.nn.Sequential(*list(resnet50.children())[:-1])
return feature_extractor, preprocess
def extract_features_resnet50(images, feature_extractor, preprocess):
"""Extract features from images using a pre-initialized ResNet50 feature extractor."""
features = []
for image in images:
image = preprocess(image)
image = image.unsqueeze(0) # Add batch dimension
with torch.no_grad():
feature = feature_extractor(image)
features.append(feature.squeeze().cpu().numpy()) # Remove batch dimension and convert to numpy
return np.array(features)
# Initialize feature extractor
feature_extractor, preprocess = initialize_resnet50()
# Initialize memory buffer
BUFFER_SIZE = 10000 # Set your buffer size
memory_buffer = MemoryBuffer(capacity=BUFFER_SIZE)
# Initialize internal distribution
internal_gmm = None
# Accuracy matrices to store the evaluation results
accuracy_matrix_task1 = np.zeros((10, 10)) # Task 1 accuracy matrix
accuracy_matrix_task2 = np.zeros((10, 20)) # Task 2 accuracy matrix
# Task 1: Handle D1 to D10
for i in range(1, 11):
dataset_path = f"{i}_train_data.tar.pth"
if not os.path.exists(dataset_path):
print(f"Dataset file {dataset_path} does not exist. Skipping...")
continue
dataset = load_tar_pth_dataset(dataset_path)
if dataset == (None, None):
print(f"Dataset {i} could not be loaded. Skipping...")
continue
images, labels = dataset
features = extract_features_resnet50(images, feature_extractor, preprocess)
if i == 1:
# Train initial model f1 on D1
model = LwPClassifier()
model.train(features, labels.numpy())
# Fit initial GMM
internal_gmm = fit_gmm(features)
# Update memory buffer
memory_buffer.add_samples(images, labels)
else:
# Predict pseudo-labels on D_i using f_{i-1}
pseudo_labels = model.predict(features)
# Update model to f_i using pseudo-labeled D_i and memory buffer
replay_features_tensor, replay_labels_tensor = memory_buffer.get_replay_data(sample_size=1000)
if replay_features_tensor.size > 0:
replay_features = extract_features_resnet50(replay_features_tensor, feature_extractor, preprocess).reshape(replay_features_tensor.size(0), -1)
replay_labels = replay_labels_tensor.numpy()
else:
replay_features = np.array([])
replay_labels = np.array([])
model.update(features, pseudo_labels, replay_features, replay_labels)
# Update internal GMM
new_gmm = fit_gmm(features)
internal_gmm = consolidate_gmm(internal_gmm, new_gmm)
# Update memory buffer
memory_buffer.add_samples(images, labels)
# Evaluation on held-out datasets
heldout_datasets = []
for j in range(1, i+1):
heldout_path = f"hat_D{j}.tar.pth"
if os.path.exists(heldout_path):
heldout = load_tar_pth_dataset(heldout_path)
if heldout != (None, None):
heldout_datasets.append(heldout)
else:
print(f"Held-out dataset {j} could not be loaded.")
else:
print(f"Held-out dataset file {heldout_path} does not exist.")
accuracies = []
for heldout in heldout_datasets:
heldout_images, heldout_labels = heldout
heldout_features = extract_features_resnet50(heldout_images, feature_extractor, preprocess)
acc = accuracy_score(heldout_labels.numpy(), model.predict(heldout_features))
accuracies.append(acc)
accuracy_matrix_task1[i-1, :len(accuracies)] = accuracies
# Save Task 1 accuracy matrix
def save_accuracy_matrix(accuracy_matrix, filename):
np.savetxt(filename, accuracy_matrix, delimiter=",")
print(f"Accuracy matrix saved to {filename}")
save_accuracy_matrix(accuracy_matrix_task1, "accuracy_task1.csv")
# Task 2: Handle D11 to D20
model = model # Continue using the last model from Task 1
for i in range(11, 21):
dataset_path = f"{i}_train_data.tar.pth"
if not os.path.exists(dataset_path):
print(f"Dataset file {dataset_path} does not exist. Skipping...")
continue
dataset = load_tar_pth_dataset(dataset_path)
if dataset == (None, None):
print(f"Dataset {i} could not be loaded. Skipping...")
continue
images, labels = dataset
features = extract_features_resnet50(images, feature_extractor, preprocess)
# Predict pseudo-labels on D_i using f_{i-1}
pseudo_labels = model.predict(features)
# Align features with internal distribution
aligned_features = align_features(features, internal_gmm)
# Update model to f_i using pseudo-labeled D_i, aligned features, and memory buffer
replay_features_tensor, replay_labels_tensor = memory_buffer.get_replay_data(sample_size=1000)
if replay_features_tensor.size > 0:
replay_features = extract_features_resnet50(replay_features_tensor, feature_extractor, preprocess).reshape(replay_features_tensor.size(0), -1)
replay_labels = replay_labels_tensor.numpy()
else:
replay_features = np.array([])
replay_labels = np.array([])
model.update(aligned_features, pseudo_labels, replay_features, replay_labels, domain_adaptation=True)
# Update internal GMM
new_gmm = fit_gmm(aligned_features)
internal_gmm = consolidate_gmm(internal_gmm, new_gmm)
# Update memory buffer
memory_buffer.add_samples(images, labels)
# Evaluation on held-out datasets
heldout_datasets = []
for j in range(1, i+1):
heldout_path = f"hat_D{j}.tar.pth"
if os.path.exists(heldout_path):
heldout = load_tar_pth_dataset(heldout_path)
if heldout != (None, None):
heldout_datasets.append(heldout)
else:
print(f"Held-out dataset {j} could not be loaded.")
else:
print(f"Held-out dataset file {heldout_path} does not exist.")
accuracies = []
for heldout in heldout_datasets:
heldout_images, heldout_labels = heldout
heldout_features = extract_features_resnet50(heldout_images, feature_extractor, preprocess)
acc = accuracy_score(heldout_labels.numpy(), model.predict(heldout_features))
accuracies.append(acc)
# Ensure the accuracy_matrix_task2 has sufficient columns
if accuracy_matrix_task2.shape[1] < i:
# Resize the matrix to accommodate more columns
new_matrix = np.zeros((10, i))
new_matrix[:, :accuracy_matrix_task2.shape[1]] = accuracy_matrix_task2[:, :accuracy_matrix_task2.shape[1]]
accuracy_matrix_task2 = new_matrix
accuracy_matrix_task2[i-11, :len(accuracies)] = accuracies
# Save Task 2 accuracy matrix
save_accuracy_matrix(accuracy_matrix_task2, "accuracy_task2.csv")