Upload folder using huggingface_hub
Browse files- .gitattributes +5 -0
- Evaluation Results/Eval 1.png +3 -0
- Evaluation Results/Eval 2.png +3 -0
- Evaluation Results/desktop.ini +3 -0
- Notebooks/Autoencoder_on_Image_Compression.ipynb +0 -0
- README.md +27 -11
- Testing Results/Result of Test 1.png +3 -0
- Testing Results/Result of Test 2.png +3 -0
- Testing Results/Result of Test 3.png +3 -0
- Testing Results/Screenshot 2026-03-30 013519.png +0 -0
- Testing Results/desktop.ini +4 -0
- autoencoder_celeba.pth +3 -0
- autoencoder_on_image_compression.py +437 -0
- inference.py +48 -0
- model.py +36 -0
- requirements.txt +5 -0
.gitattributes
CHANGED
|
@@ -33,3 +33,8 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
|
|
| 33 |
*.zip filter=lfs diff=lfs merge=lfs -text
|
| 34 |
*.zst filter=lfs diff=lfs merge=lfs -text
|
| 35 |
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 33 |
*.zip filter=lfs diff=lfs merge=lfs -text
|
| 34 |
*.zst filter=lfs diff=lfs merge=lfs -text
|
| 35 |
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
| 36 |
+
Evaluation[[:space:]]Results/Eval[[:space:]]1.png filter=lfs diff=lfs merge=lfs -text
|
| 37 |
+
Evaluation[[:space:]]Results/Eval[[:space:]]2.png filter=lfs diff=lfs merge=lfs -text
|
| 38 |
+
Testing[[:space:]]Results/Result[[:space:]]of[[:space:]]Test[[:space:]]1.png filter=lfs diff=lfs merge=lfs -text
|
| 39 |
+
Testing[[:space:]]Results/Result[[:space:]]of[[:space:]]Test[[:space:]]2.png filter=lfs diff=lfs merge=lfs -text
|
| 40 |
+
Testing[[:space:]]Results/Result[[:space:]]of[[:space:]]Test[[:space:]]3.png filter=lfs diff=lfs merge=lfs -text
|
Evaluation Results/Eval 1.png
ADDED
|
Git LFS Details
|
Evaluation Results/Eval 2.png
ADDED
|
Git LFS Details
|
Evaluation Results/desktop.ini
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
[LocalizedFileNames]
|
| 2 |
+
Screenshot 2026-03-30 001932.png=@Screenshot 2026-03-30 001932,0
|
| 3 |
+
Screenshot 2026-03-29 120202.png=@Screenshot 2026-03-29 120202,0
|
Notebooks/Autoencoder_on_Image_Compression.ipynb
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
README.md
CHANGED
|
@@ -1,11 +1,27 @@
|
|
| 1 |
-
|
| 2 |
-
|
| 3 |
-
|
| 4 |
-
|
| 5 |
-
|
| 6 |
-
|
| 7 |
-
|
| 8 |
-
|
| 9 |
-
-
|
| 10 |
-
|
| 11 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
|
| 2 |
+
# CelebA Autoencoder
|
| 3 |
+
|
| 4 |
+
## Overview
|
| 5 |
+
This project implements a **Convolutional Autoencoder** trained on the [*CelebA dataset*](https://www.kaggle.com/datasets/jessicali9530/celeba-dataset) for image compression and reconstruction.
|
| 6 |
+
|
| 7 |
+
## Features
|
| 8 |
+
- Learns compressed latent representation of face images
|
| 9 |
+
- Reconstructs images from compressed representation
|
| 10 |
+
- Evaluated using PSNR and SSIM metrics
|
| 11 |
+
|
| 12 |
+
## Dataset
|
| 13 |
+
- [CelebA Dataset (Kaggle)](https://www.kaggle.com/datasets/jessicali9530/celeba-dataset)
|
| 14 |
+
|
| 15 |
+
## Model
|
| 16 |
+
- Encoder: Convolutional layers with downsampling
|
| 17 |
+
- Decoder: Transposed convolution layers for reconstruction
|
| 18 |
+
|
| 19 |
+
## Results
|
| 20 |
+
- Average PSNR: 31.126471439997356
|
| 21 |
+
- Average SSIM: 0.9329655667146047
|
| 22 |
+
|
| 23 |
+
# Notes
|
| 24 |
+
- Model performs lossy compression
|
| 25 |
+
- Some blurring is expected due to reconstruction loss
|
| 26 |
+
|
| 27 |
+
# Please Fell Free to Use this Project in what ever way you like.
|
Testing Results/Result of Test 1.png
ADDED
|
Git LFS Details
|
Testing Results/Result of Test 2.png
ADDED
|
Git LFS Details
|
Testing Results/Result of Test 3.png
ADDED
|
Git LFS Details
|
Testing Results/Screenshot 2026-03-30 013519.png
ADDED
|
Testing Results/desktop.ini
ADDED
|
@@ -0,0 +1,4 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
[LocalizedFileNames]
|
| 2 |
+
Screenshot 2026-03-30 002049.png=@Screenshot 2026-03-30 002049,0
|
| 3 |
+
Screenshot 2026-03-30 002744.png=@Screenshot 2026-03-30 002744,0
|
| 4 |
+
Screenshot 2026-03-30 003604.png=@Screenshot 2026-03-30 003604,0
|
autoencoder_celeba.pth
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:ac878db94da7550230514654c1cfa9b77703d9f0a46caacaebe0a8076516a54d
|
| 3 |
+
size 22076037
|
autoencoder_on_image_compression.py
ADDED
|
@@ -0,0 +1,437 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# -*- coding: utf-8 -*-
|
| 2 |
+
"""Autoencoder on Image Compression.ipynb
|
| 3 |
+
|
| 4 |
+
Automatically generated by Colab.
|
| 5 |
+
|
| 6 |
+
Original file is located at
|
| 7 |
+
https://colab.research.google.com/drive/13X8ZS11V0GCWpowuJZ3igEYJa6kRx9DL
|
| 8 |
+
"""
|
| 9 |
+
|
| 10 |
+
from google.colab import files
|
| 11 |
+
files.upload()
|
| 12 |
+
|
| 13 |
+
import os
|
| 14 |
+
|
| 15 |
+
os.makedirs('/root/.kaggle', exist_ok=True)
|
| 16 |
+
!cp kaggle.json /root/.kaggle/
|
| 17 |
+
!chmod 600 /root/.kaggle/kaggle.json
|
| 18 |
+
|
| 19 |
+
!kaggle datasets download -d jessicali9530/celeba-dataset
|
| 20 |
+
!unzip -q celeba-dataset.zip
|
| 21 |
+
|
| 22 |
+
import os
|
| 23 |
+
import numpy as np
|
| 24 |
+
import matplotlib.pyplot as plt
|
| 25 |
+
from PIL import Image
|
| 26 |
+
|
| 27 |
+
import torch
|
| 28 |
+
import torch.nn as nn
|
| 29 |
+
import torch.optim as optim
|
| 30 |
+
from torchvision import transforms
|
| 31 |
+
from torch.utils.data import Dataset, DataLoader, random_split
|
| 32 |
+
|
| 33 |
+
from torch.amp import autocast, GradScaler
|
| 34 |
+
|
| 35 |
+
class CelebADataset(Dataset):
|
| 36 |
+
def __init__(self, img_dir, transform=None):
|
| 37 |
+
self.img_dir = img_dir
|
| 38 |
+
self.image_names = sorted(os.listdir(img_dir))
|
| 39 |
+
self.transform = transform
|
| 40 |
+
|
| 41 |
+
def __len__(self):
|
| 42 |
+
return len(self.image_names)
|
| 43 |
+
|
| 44 |
+
def __getitem__(self, idx):
|
| 45 |
+
img_path = os.path.join(self.img_dir, self.image_names[idx])
|
| 46 |
+
image = Image.open(img_path).convert('RGB')
|
| 47 |
+
|
| 48 |
+
if self.transform:
|
| 49 |
+
image = self.transform(image)
|
| 50 |
+
|
| 51 |
+
return image
|
| 52 |
+
|
| 53 |
+
transform = transforms.Compose([
|
| 54 |
+
transforms.Resize((128, 128)),
|
| 55 |
+
transforms.ToTensor()
|
| 56 |
+
])
|
| 57 |
+
|
| 58 |
+
dataset = CelebADataset("img_align_celeba/img_align_celeba", transform=transform)
|
| 59 |
+
|
| 60 |
+
dataset.image_names = dataset.image_names[:60000]
|
| 61 |
+
|
| 62 |
+
train_size = int(0.8 * len(dataset))
|
| 63 |
+
val_size = len(dataset) - train_size
|
| 64 |
+
|
| 65 |
+
train_dataset, val_dataset = random_split(dataset, [train_size, val_size])
|
| 66 |
+
|
| 67 |
+
train_loader = DataLoader(
|
| 68 |
+
train_dataset,
|
| 69 |
+
batch_size=512,
|
| 70 |
+
shuffle=True,
|
| 71 |
+
num_workers=2,
|
| 72 |
+
pin_memory=True,
|
| 73 |
+
persistent_workers=False
|
| 74 |
+
)
|
| 75 |
+
|
| 76 |
+
val_loader = DataLoader(
|
| 77 |
+
val_dataset,
|
| 78 |
+
batch_size=512,
|
| 79 |
+
shuffle=False,
|
| 80 |
+
num_workers=2,
|
| 81 |
+
pin_memory=True,
|
| 82 |
+
persistent_workers=False
|
| 83 |
+
)
|
| 84 |
+
|
| 85 |
+
class Autoencoder(nn.Module):
|
| 86 |
+
def __init__(self):
|
| 87 |
+
super(Autoencoder, self).__init__()
|
| 88 |
+
|
| 89 |
+
self.encoder = nn.Sequential(
|
| 90 |
+
nn.Conv2d(3, 64, 4, 2, 1),
|
| 91 |
+
nn.ReLU(),
|
| 92 |
+
nn.Conv2d(64, 128, 4, 2, 1),
|
| 93 |
+
nn.BatchNorm2d(128),
|
| 94 |
+
nn.ReLU(),
|
| 95 |
+
nn.Conv2d(128, 256, 4, 2, 1),
|
| 96 |
+
nn.BatchNorm2d(256),
|
| 97 |
+
nn.ReLU(),
|
| 98 |
+
nn.Conv2d(256, 512, 4, 2, 1),
|
| 99 |
+
nn.ReLU()
|
| 100 |
+
)
|
| 101 |
+
|
| 102 |
+
self.decoder = nn.Sequential(
|
| 103 |
+
nn.ConvTranspose2d(512, 256, 4, 2, 1),
|
| 104 |
+
nn.BatchNorm2d(256),
|
| 105 |
+
nn.ReLU(),
|
| 106 |
+
nn.ConvTranspose2d(256, 128, 4, 2, 1),
|
| 107 |
+
nn.BatchNorm2d(128),
|
| 108 |
+
nn.ReLU(),
|
| 109 |
+
nn.ConvTranspose2d(128, 64, 4, 2, 1),
|
| 110 |
+
nn.ReLU(),
|
| 111 |
+
nn.ConvTranspose2d(64, 3, 4, 2, 1),
|
| 112 |
+
nn.Sigmoid()
|
| 113 |
+
)
|
| 114 |
+
|
| 115 |
+
def forward(self, x):
|
| 116 |
+
return self.decoder(self.encoder(x))
|
| 117 |
+
|
| 118 |
+
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
| 119 |
+
|
| 120 |
+
model = Autoencoder().to(device).to(memory_format=torch.channels_last)
|
| 121 |
+
|
| 122 |
+
model = torch.compile(model)
|
| 123 |
+
|
| 124 |
+
criterion = nn.L1Loss()
|
| 125 |
+
optimizer = optim.Adam(model.parameters(), lr=0.001)
|
| 126 |
+
|
| 127 |
+
scaler = GradScaler()
|
| 128 |
+
|
| 129 |
+
torch.backends.cudnn.benchmark = True
|
| 130 |
+
|
| 131 |
+
epochs = 50
|
| 132 |
+
|
| 133 |
+
for epoch in range(epochs):
|
| 134 |
+
model.train()
|
| 135 |
+
train_loss = 0
|
| 136 |
+
|
| 137 |
+
for images in train_loader:
|
| 138 |
+
images = images.to(device, non_blocking=True).to(memory_format=torch.channels_last)
|
| 139 |
+
|
| 140 |
+
optimizer.zero_grad()
|
| 141 |
+
|
| 142 |
+
with autocast(device_type='cuda'):
|
| 143 |
+
outputs = model(images)
|
| 144 |
+
loss = criterion(outputs, images)
|
| 145 |
+
|
| 146 |
+
scaler.scale(loss).backward()
|
| 147 |
+
scaler.step(optimizer)
|
| 148 |
+
scaler.update()
|
| 149 |
+
|
| 150 |
+
train_loss += loss.item()
|
| 151 |
+
|
| 152 |
+
train_loss /= len(train_loader)
|
| 153 |
+
|
| 154 |
+
model.eval()
|
| 155 |
+
val_loss = 0
|
| 156 |
+
|
| 157 |
+
with torch.no_grad():
|
| 158 |
+
for images in val_loader:
|
| 159 |
+
images = images.to(device, non_blocking=True).to(memory_format=torch.channels_last)
|
| 160 |
+
|
| 161 |
+
with autocast(device_type='cuda'):
|
| 162 |
+
outputs = model(images)
|
| 163 |
+
loss = criterion(outputs, images)
|
| 164 |
+
|
| 165 |
+
val_loss += loss.item()
|
| 166 |
+
|
| 167 |
+
val_loss /= len(val_loader)
|
| 168 |
+
|
| 169 |
+
print(f"Epoch [{epoch+1}/{epochs}] | Train Loss: {train_loss:.4f} | Val Loss: {val_loss:.4f}")
|
| 170 |
+
|
| 171 |
+
dataiter = iter(val_loader)
|
| 172 |
+
images = next(dataiter).to(device)
|
| 173 |
+
|
| 174 |
+
with torch.no_grad():
|
| 175 |
+
outputs = model(images)
|
| 176 |
+
|
| 177 |
+
images = images.cpu().numpy()
|
| 178 |
+
outputs = outputs.cpu().numpy()
|
| 179 |
+
|
| 180 |
+
fig, axes = plt.subplots(2, 6, figsize=(12,4))
|
| 181 |
+
|
| 182 |
+
for i in range(6):
|
| 183 |
+
axes[0, i].imshow(np.transpose(images[i], (1,2,0)))
|
| 184 |
+
axes[0, i].axis('off')
|
| 185 |
+
|
| 186 |
+
axes[1, i].imshow(np.transpose(outputs[i], (1,2,0)))
|
| 187 |
+
axes[1, i].axis('off')
|
| 188 |
+
|
| 189 |
+
plt.show()
|
| 190 |
+
|
| 191 |
+
!pip install pytorch-msssim
|
| 192 |
+
|
| 193 |
+
loss = criterion(outputs, images)
|
| 194 |
+
|
| 195 |
+
import torch
|
| 196 |
+
|
| 197 |
+
def calculate_psnr(original, reconstructed):
|
| 198 |
+
mse = torch.mean((original - reconstructed) ** 2)
|
| 199 |
+
if mse == 0:
|
| 200 |
+
return 100
|
| 201 |
+
psnr = 20 * torch.log10(1.0 / torch.sqrt(mse))
|
| 202 |
+
return psnr
|
| 203 |
+
|
| 204 |
+
from pytorch_msssim import ssim
|
| 205 |
+
|
| 206 |
+
model.eval()
|
| 207 |
+
|
| 208 |
+
total_psnr = 0
|
| 209 |
+
total_ssim = 0
|
| 210 |
+
count = 0
|
| 211 |
+
|
| 212 |
+
with torch.no_grad():
|
| 213 |
+
for images in val_loader:
|
| 214 |
+
images = images.to(device)
|
| 215 |
+
outputs = model(images)
|
| 216 |
+
|
| 217 |
+
total_psnr += calculate_psnr(images, outputs).item()
|
| 218 |
+
total_ssim += ssim(images, outputs, data_range=1.0, size_average=True).item()
|
| 219 |
+
count += 1
|
| 220 |
+
|
| 221 |
+
print("Average PSNR:", total_psnr / count)
|
| 222 |
+
print("Average SSIM:", total_ssim / count)
|
| 223 |
+
|
| 224 |
+
from google.colab import files
|
| 225 |
+
uploaded = files.upload()
|
| 226 |
+
|
| 227 |
+
from PIL import Image
|
| 228 |
+
|
| 229 |
+
img_path = list(uploaded.keys())[0]
|
| 230 |
+
|
| 231 |
+
image = Image.open(img_path).convert('RGB')
|
| 232 |
+
|
| 233 |
+
transform = transforms.Compose([
|
| 234 |
+
transforms.Resize((128, 128)),
|
| 235 |
+
transforms.ToTensor()
|
| 236 |
+
])
|
| 237 |
+
|
| 238 |
+
input_image = transform(image).unsqueeze(0).to(device)
|
| 239 |
+
|
| 240 |
+
model.eval()
|
| 241 |
+
|
| 242 |
+
with torch.no_grad():
|
| 243 |
+
output_image = model(input_image)
|
| 244 |
+
|
| 245 |
+
input_np = input_image.squeeze().cpu().numpy()
|
| 246 |
+
output_np = output_image.squeeze().cpu().numpy()
|
| 247 |
+
|
| 248 |
+
import matplotlib.pyplot as plt
|
| 249 |
+
|
| 250 |
+
fig, axes = plt.subplots(1, 2, figsize=(8,4))
|
| 251 |
+
|
| 252 |
+
axes[0].imshow(input_np.transpose(1,2,0))
|
| 253 |
+
axes[0].set_title("Original")
|
| 254 |
+
axes[0].axis('off')
|
| 255 |
+
|
| 256 |
+
axes[1].imshow(output_np.transpose(1,2,0))
|
| 257 |
+
axes[1].set_title("Reconstructed")
|
| 258 |
+
axes[1].axis('off')
|
| 259 |
+
|
| 260 |
+
plt.show()
|
| 261 |
+
|
| 262 |
+
torch.save(model.state_dict(), "autoencoder_celeba.pth")
|
| 263 |
+
|
| 264 |
+
torch.save(model, "autoencoder_full.pth")
|
| 265 |
+
|
| 266 |
+
from google.colab import files
|
| 267 |
+
files.download("autoencoder_celeba.pth")
|
| 268 |
+
|
| 269 |
+
state_dict = torch.load("autoencoder_celeba.pth")
|
| 270 |
+
|
| 271 |
+
new_state_dict = {}
|
| 272 |
+
for k, v in state_dict.items():
|
| 273 |
+
new_key = k.replace("_orig_mod.", "")
|
| 274 |
+
new_state_dict[new_key] = v
|
| 275 |
+
|
| 276 |
+
model = Autoencoder().to(device)
|
| 277 |
+
model.load_state_dict(new_state_dict)
|
| 278 |
+
model.eval()
|
| 279 |
+
|
| 280 |
+
model.load_state_dict(torch.load("autoencoder_celeba.pth"), strict=False)
|
| 281 |
+
|
| 282 |
+
import os
|
| 283 |
+
|
| 284 |
+
project_dir = "celeba-autoencoder"
|
| 285 |
+
os.makedirs(project_dir, exist_ok=True)
|
| 286 |
+
|
| 287 |
+
model_code = """
|
| 288 |
+
import torch
|
| 289 |
+
import torch.nn as nn
|
| 290 |
+
|
| 291 |
+
class Autoencoder(nn.Module):
|
| 292 |
+
def __init__(self):
|
| 293 |
+
super(Autoencoder, self).__init__()
|
| 294 |
+
|
| 295 |
+
self.encoder = nn.Sequential(
|
| 296 |
+
nn.Conv2d(3, 64, 4, 2, 1),
|
| 297 |
+
nn.ReLU(),
|
| 298 |
+
nn.Conv2d(64, 128, 4, 2, 1),
|
| 299 |
+
nn.BatchNorm2d(128),
|
| 300 |
+
nn.ReLU(),
|
| 301 |
+
nn.Conv2d(128, 256, 4, 2, 1),
|
| 302 |
+
nn.BatchNorm2d(256),
|
| 303 |
+
nn.ReLU(),
|
| 304 |
+
nn.Conv2d(256, 512, 4, 2, 1),
|
| 305 |
+
nn.ReLU()
|
| 306 |
+
)
|
| 307 |
+
|
| 308 |
+
self.decoder = nn.Sequential(
|
| 309 |
+
nn.ConvTranspose2d(512, 256, 4, 2, 1),
|
| 310 |
+
nn.BatchNorm2d(256),
|
| 311 |
+
nn.ReLU(),
|
| 312 |
+
nn.ConvTranspose2d(256, 128, 4, 2, 1),
|
| 313 |
+
nn.BatchNorm2d(128),
|
| 314 |
+
nn.ReLU(),
|
| 315 |
+
nn.ConvTranspose2d(128, 64, 4, 2, 1),
|
| 316 |
+
nn.ReLU(),
|
| 317 |
+
nn.ConvTranspose2d(64, 3, 4, 2, 1),
|
| 318 |
+
nn.Sigmoid()
|
| 319 |
+
)
|
| 320 |
+
|
| 321 |
+
def forward(self, x):
|
| 322 |
+
return self.decoder(self.encoder(x))
|
| 323 |
+
"""
|
| 324 |
+
|
| 325 |
+
with open(f"{project_dir}/model.py", "w") as f:
|
| 326 |
+
f.write(model_code)
|
| 327 |
+
|
| 328 |
+
inference_code = """
|
| 329 |
+
import torch
|
| 330 |
+
from torchvision import transforms
|
| 331 |
+
from PIL import Image
|
| 332 |
+
import matplotlib.pyplot as plt
|
| 333 |
+
import sys
|
| 334 |
+
|
| 335 |
+
from model import Autoencoder
|
| 336 |
+
|
| 337 |
+
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
| 338 |
+
|
| 339 |
+
model = Autoencoder().to(device)
|
| 340 |
+
|
| 341 |
+
state_dict = torch.load("autoencoder_celeba.pth", map_location=device)
|
| 342 |
+
|
| 343 |
+
# Fix for torch.compile prefix
|
| 344 |
+
new_state_dict = {k.replace("_orig_mod.", ""): v for k, v in state_dict.items()}
|
| 345 |
+
|
| 346 |
+
model.load_state_dict(new_state_dict)
|
| 347 |
+
model.eval()
|
| 348 |
+
|
| 349 |
+
image_path = sys.argv[1]
|
| 350 |
+
|
| 351 |
+
transform = transforms.Compose([
|
| 352 |
+
transforms.Resize((128, 128)),
|
| 353 |
+
transforms.ToTensor()
|
| 354 |
+
])
|
| 355 |
+
|
| 356 |
+
image = Image.open(image_path).convert("RGB")
|
| 357 |
+
input_tensor = transform(image).unsqueeze(0).to(device)
|
| 358 |
+
|
| 359 |
+
with torch.no_grad():
|
| 360 |
+
output = model(input_tensor)
|
| 361 |
+
|
| 362 |
+
input_np = input_tensor.squeeze().cpu().numpy()
|
| 363 |
+
output_np = output.squeeze().cpu().numpy()
|
| 364 |
+
|
| 365 |
+
fig, axes = plt.subplots(1, 2, figsize=(8,4))
|
| 366 |
+
|
| 367 |
+
axes[0].imshow(input_np.transpose(1,2,0))
|
| 368 |
+
axes[0].set_title("Original")
|
| 369 |
+
axes[0].axis("off")
|
| 370 |
+
|
| 371 |
+
axes[1].imshow(output_np.transpose(1,2,0))
|
| 372 |
+
axes[1].set_title("Reconstructed")
|
| 373 |
+
axes[1].axis("off")
|
| 374 |
+
|
| 375 |
+
plt.show()
|
| 376 |
+
"""
|
| 377 |
+
|
| 378 |
+
with open(f"{project_dir}/inference.py", "w") as f:
|
| 379 |
+
f.write(inference_code)
|
| 380 |
+
|
| 381 |
+
requirements = """torch
|
| 382 |
+
torchvision
|
| 383 |
+
pillow
|
| 384 |
+
matplotlib
|
| 385 |
+
pytorch-msssim
|
| 386 |
+
"""
|
| 387 |
+
|
| 388 |
+
with open(f"{project_dir}/requirements.txt", "w") as f:
|
| 389 |
+
f.write(requirements)
|
| 390 |
+
|
| 391 |
+
readme = """
|
| 392 |
+
# CelebA Autoencoder
|
| 393 |
+
|
| 394 |
+
## Overview
|
| 395 |
+
This project implements a Convolutional Autoencoder trained on the CelebA dataset for image compression and reconstruction.
|
| 396 |
+
|
| 397 |
+
## Features
|
| 398 |
+
- Learns compressed latent representation of face images
|
| 399 |
+
- Reconstructs images from compressed representation
|
| 400 |
+
- Evaluated using PSNR and SSIM metrics
|
| 401 |
+
|
| 402 |
+
## Dataset
|
| 403 |
+
- CelebA Dataset (Kaggle)
|
| 404 |
+
|
| 405 |
+
## Model
|
| 406 |
+
- Encoder: Convolutional layers with downsampling
|
| 407 |
+
- Decoder: Transposed convolution layers for reconstruction
|
| 408 |
+
|
| 409 |
+
## Results
|
| 410 |
+
- PSNR: ~31 dB
|
| 411 |
+
- SSIM: ~0.93
|
| 412 |
+
|
| 413 |
+
## Usage
|
| 414 |
+
|
| 415 |
+
### Run Inference
|
| 416 |
+
```bash
|
| 417 |
+
python inference.py path_to_image.jpg
|
| 418 |
+
|
| 419 |
+
Notes
|
| 420 |
+
Model performs lossy compression
|
| 421 |
+
Some blurring is expected due to reconstruction loss
|
| 422 |
+
Author
|
| 423 |
+
|
| 424 |
+
Autoencoder project for Deep Learning experiment
|
| 425 |
+
"""
|
| 426 |
+
|
| 427 |
+
with open(f"{project_dir}/README.md", "w") as f:
|
| 428 |
+
f.write(readme)
|
| 429 |
+
|
| 430 |
+
import shutil
|
| 431 |
+
|
| 432 |
+
shutil.copy("autoencoder_celeba.pth", f"{project_dir}/autoencoder_celeba.pth")
|
| 433 |
+
|
| 434 |
+
shutil.make_archive("celeba-autoencoder", 'zip', project_dir)
|
| 435 |
+
|
| 436 |
+
from google.colab import files
|
| 437 |
+
files.download("celeba-autoencoder.zip")
|
inference.py
ADDED
|
@@ -0,0 +1,48 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
|
| 2 |
+
import torch
|
| 3 |
+
from torchvision import transforms
|
| 4 |
+
from PIL import Image
|
| 5 |
+
import matplotlib.pyplot as plt
|
| 6 |
+
import sys
|
| 7 |
+
|
| 8 |
+
from model import Autoencoder
|
| 9 |
+
|
| 10 |
+
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
| 11 |
+
|
| 12 |
+
model = Autoencoder().to(device)
|
| 13 |
+
|
| 14 |
+
state_dict = torch.load("autoencoder_celeba.pth", map_location=device)
|
| 15 |
+
|
| 16 |
+
# Fix for torch.compile prefix
|
| 17 |
+
new_state_dict = {k.replace("_orig_mod.", ""): v for k, v in state_dict.items()}
|
| 18 |
+
|
| 19 |
+
model.load_state_dict(new_state_dict)
|
| 20 |
+
model.eval()
|
| 21 |
+
|
| 22 |
+
image_path = sys.argv[1]
|
| 23 |
+
|
| 24 |
+
transform = transforms.Compose([
|
| 25 |
+
transforms.Resize((128, 128)),
|
| 26 |
+
transforms.ToTensor()
|
| 27 |
+
])
|
| 28 |
+
|
| 29 |
+
image = Image.open(image_path).convert("RGB")
|
| 30 |
+
input_tensor = transform(image).unsqueeze(0).to(device)
|
| 31 |
+
|
| 32 |
+
with torch.no_grad():
|
| 33 |
+
output = model(input_tensor)
|
| 34 |
+
|
| 35 |
+
input_np = input_tensor.squeeze().cpu().numpy()
|
| 36 |
+
output_np = output.squeeze().cpu().numpy()
|
| 37 |
+
|
| 38 |
+
fig, axes = plt.subplots(1, 2, figsize=(8,4))
|
| 39 |
+
|
| 40 |
+
axes[0].imshow(input_np.transpose(1,2,0))
|
| 41 |
+
axes[0].set_title("Original")
|
| 42 |
+
axes[0].axis("off")
|
| 43 |
+
|
| 44 |
+
axes[1].imshow(output_np.transpose(1,2,0))
|
| 45 |
+
axes[1].set_title("Reconstructed")
|
| 46 |
+
axes[1].axis("off")
|
| 47 |
+
|
| 48 |
+
plt.show()
|
model.py
ADDED
|
@@ -0,0 +1,36 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
|
| 2 |
+
import torch
|
| 3 |
+
import torch.nn as nn
|
| 4 |
+
|
| 5 |
+
class Autoencoder(nn.Module):
|
| 6 |
+
def __init__(self):
|
| 7 |
+
super(Autoencoder, self).__init__()
|
| 8 |
+
|
| 9 |
+
self.encoder = nn.Sequential(
|
| 10 |
+
nn.Conv2d(3, 64, 4, 2, 1),
|
| 11 |
+
nn.ReLU(),
|
| 12 |
+
nn.Conv2d(64, 128, 4, 2, 1),
|
| 13 |
+
nn.BatchNorm2d(128),
|
| 14 |
+
nn.ReLU(),
|
| 15 |
+
nn.Conv2d(128, 256, 4, 2, 1),
|
| 16 |
+
nn.BatchNorm2d(256),
|
| 17 |
+
nn.ReLU(),
|
| 18 |
+
nn.Conv2d(256, 512, 4, 2, 1),
|
| 19 |
+
nn.ReLU()
|
| 20 |
+
)
|
| 21 |
+
|
| 22 |
+
self.decoder = nn.Sequential(
|
| 23 |
+
nn.ConvTranspose2d(512, 256, 4, 2, 1),
|
| 24 |
+
nn.BatchNorm2d(256),
|
| 25 |
+
nn.ReLU(),
|
| 26 |
+
nn.ConvTranspose2d(256, 128, 4, 2, 1),
|
| 27 |
+
nn.BatchNorm2d(128),
|
| 28 |
+
nn.ReLU(),
|
| 29 |
+
nn.ConvTranspose2d(128, 64, 4, 2, 1),
|
| 30 |
+
nn.ReLU(),
|
| 31 |
+
nn.ConvTranspose2d(64, 3, 4, 2, 1),
|
| 32 |
+
nn.Sigmoid()
|
| 33 |
+
)
|
| 34 |
+
|
| 35 |
+
def forward(self, x):
|
| 36 |
+
return self.decoder(self.encoder(x))
|
requirements.txt
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
torch
|
| 2 |
+
torchvision
|
| 3 |
+
pillow
|
| 4 |
+
matplotlib
|
| 5 |
+
pytorch-msssim
|