Introduction
An autoencoder learns to copy its input to its output by compressing data into a smaller form and then reconstructing it. This helps find important features in data without labels.
class Autoencoder(nn.Module): def __init__(self, input_size, hidden_size, code_size): super().__init__() self.encoder = nn.Sequential( nn.Linear(input_size, hidden_size), nn.ReLU(), nn.Linear(hidden_size, code_size), nn.ReLU() ) self.decoder = nn.Sequential( nn.Linear(code_size, hidden_size), nn.ReLU(), nn.Linear(hidden_size, input_size), nn.Sigmoid() ) def forward(self, x): code = self.encoder(x) reconstructed = self.decoder(code) return reconstructed
class SimpleAutoencoder(nn.Module): def __init__(self): super().__init__() self.encoder = nn.Linear(784, 32) self.decoder = nn.Linear(32, 784) def forward(self, x): code = torch.relu(self.encoder(x)) reconstructed = torch.sigmoid(self.decoder(code)) return reconstructed
class DeepAutoencoder(nn.Module): def __init__(self): super().__init__() self.encoder = nn.Sequential( nn.Linear(784, 128), nn.ReLU(), nn.Linear(128, 64), nn.ReLU(), nn.Linear(64, 12), nn.ReLU(), nn.Linear(12, 3) ) self.decoder = nn.Sequential( nn.Linear(3, 12), nn.ReLU(), nn.Linear(12, 64), nn.ReLU(), nn.Linear(64, 128), nn.ReLU(), nn.Linear(128, 784), nn.Sigmoid() ) def forward(self, x): code = self.encoder(x) reconstructed = self.decoder(code) return reconstructed
import torch import torch.nn as nn import torch.optim as optim from torchvision import datasets, transforms from torch.utils.data import DataLoader # Define Autoencoder class Autoencoder(nn.Module): def __init__(self): super().__init__() self.encoder = nn.Sequential( nn.Linear(28*28, 64), nn.ReLU(), nn.Linear(64, 12), nn.ReLU(), nn.Linear(12, 3) ) self.decoder = nn.Sequential( nn.Linear(3, 12), nn.ReLU(), nn.Linear(12, 64), nn.ReLU(), nn.Linear(64, 28*28), nn.Sigmoid() ) def forward(self, x): code = self.encoder(x) reconstructed = self.decoder(code) return reconstructed # Load MNIST dataset transform = transforms.Compose([transforms.ToTensor(), transforms.Lambda(lambda x: x.view(-1))]) mnist_train = datasets.MNIST(root='.', train=True, download=True, transform=transform) train_loader = DataLoader(mnist_train, batch_size=128, shuffle=True) # Initialize model, loss, optimizer model = Autoencoder() criterion = nn.MSELoss() optimizer = optim.Adam(model.parameters(), lr=0.001) # Train for 1 epoch model.train() for batch_idx, (data, _) in enumerate(train_loader): optimizer.zero_grad() output = model(data) loss = criterion(output, data) loss.backward() optimizer.step() if batch_idx == 0: print(f'Batch {batch_idx} Loss: {loss.item():.4f}') break
class Autoencoder(nn.Module):
def __init__(self):
super().__init__()
self.encoder = nn.Linear(784, 32)
def forward(self, x):
x = self.encoder(x)
return x
model = Autoencoder()
input_tensor = torch.randn(10, 784)
output = model(input_tensor)class Decoder(nn.Module):
def __init__(self):
super().__init__()
self.decoder = nn.Linear(32, 784)
def forward(self, x):
x = self.decoder(x)
x = nn.ReLU(x)
return xPass the test and this pattern moves unknown