PyTorch Unsupervised Learning Guide

In PyTorch, performing unsupervised learning usually involves training a model such as an autoencoder or generative adversarial network (GAN). Here is a simple example showing how to train a basic autoencoder using PyTorch.

import torch
import torch.nn as nn
import torch.optim as optim
from torch.utils.data import DataLoader
from torchvision import datasets, transforms

# 定义一个简单的自编码器模型
class Autoencoder(nn.Module):
    def __init__(self):
        super(Autoencoder, self).__init__()
        self.encoder = nn.Sequential(
            nn.Linear(784, 128),
            nn.ReLU(),
            nn.Linear(128, 64),
            nn.ReLU()
        )
        
        self.decoder = nn.Sequential(
            nn.Linear(64, 128),
            nn.ReLU(),
            nn.Linear(128, 784),
            nn.Sigmoid()
        )
    
    def forward(self, x):
        x = self.encoder(x)
        x = self.decoder(x)
        return x

# 加载MNIST数据集
transform = transforms.Compose([transforms.ToTensor()])
train_dataset = datasets.MNIST(root='./data', train=True, transform=transform, download=True)
train_loader = DataLoader(train_dataset, batch_size=64, shuffle=True)

# 初始化模型和优化器
model = Autoencoder()
criterion = nn.MSELoss()
optimizer = optim.Adam(model.parameters(), lr=0.001)

# 训练模型
num_epochs = 10
for epoch in range(num_epochs):
    for data in train_loader:
        img, _ = data
        img = img.view(img.size(0), -1)
        
        optimizer.zero_grad()
        recon = model(img)
        loss = criterion(recon, img)
        loss.backward()
        optimizer.step()
    
    print(f'Epoch [{epoch+1}/{num_epochs}], Loss: {loss.item()}')

# 使用训练好的模型重建输入图像
test_img, _ = next(iter(train_loader))
test_img = test_img.view(test_img.size(0), -1)
output_img = model(test_img)

In the above example, we first defined a simple autoencoder model, then loaded the MNIST dataset and initialized the model and optimizer. Next, we trained the model and output the loss value for each epoch. Finally, we reconstructed input images using the trained model. You can adjust the model structure and hyperparameters according to your needs and dataset to achieve better unsupervised learning results.

bannerAds