基于pytorch的DCGAN生成11*11的黑白图像代码
时间: 2023-11-27 14:03:06 浏览: 72
基于pytorch的GAN.py代码
下面是一个基于PyTorch实现的DCGAN生成11*11的黑白图像的代码示例:
```python
import torch
import torch.nn as nn
import torch.optim as optim
import numpy as np
import matplotlib.pyplot as plt
from torchvision import datasets, transforms
# 定义生成器模型
class Generator(nn.Module):
def __init__(self, image_size=11, latent_dim=100, hidden_dim=64):
super(Generator, self).__init__()
self.image_size = image_size
self.latent_dim = latent_dim
self.hidden_dim = hidden_dim
self.main = nn.Sequential(
nn.ConvTranspose2d(self.latent_dim, self.hidden_dim * 4, 4, 1, 0, bias=False),
nn.BatchNorm2d(self.hidden_dim * 4),
nn.ReLU(True),
nn.ConvTranspose2d(self.hidden_dim * 4, self.hidden_dim * 2, 4, 2, 1, bias=False),
nn.BatchNorm2d(self.hidden_dim * 2),
nn.ReLU(True),
nn.ConvTranspose2d(self.hidden_dim * 2, self.hidden_dim, 4, 2, 1, bias=False),
nn.BatchNorm2d(self.hidden_dim),
nn.ReLU(True),
nn.ConvTranspose2d(self.hidden_dim, 1, 4, 2, 1, bias=False),
nn.Tanh()
)
def forward(self, input):
return self.main(input.view(-1, self.latent_dim, 1, 1))
# 定义判别器模型
class Discriminator(nn.Module):
def __init__(self, image_size=11, hidden_dim=64):
super(Discriminator, self).__init__()
self.image_size = image_size
self.hidden_dim = hidden_dim
self.main = nn.Sequential(
nn.Conv2d(1, self.hidden_dim, 4, 2, 1, bias=False),
nn.LeakyReLU(0.2, inplace=True),
nn.Conv2d(self.hidden_dim, self.hidden_dim * 2, 4, 2, 1, bias=False),
nn.BatchNorm2d(self.hidden_dim * 2),
nn.LeakyReLU(0.2, inplace=True),
nn.Conv2d(self.hidden_dim * 2, self.hidden_dim * 4, 4, 2, 1, bias=False),
nn.BatchNorm2d(self.hidden_dim * 4),
nn.LeakyReLU(0.2, inplace=True),
nn.Conv2d(self.hidden_dim * 4, 1, 4, 1, 0, bias=False),
nn.Sigmoid()
)
def forward(self, input):
return self.main(input).view(-1, 1)
# 定义训练函数
def train(generator, discriminator, dataloader, num_epochs=20, batch_size=64, lr=0.0002, beta1=0.5):
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
generator.to(device)
discriminator.to(device)
# 定义损失函数和优化器
criterion = nn.BCELoss()
optimizerG = optim.Adam(generator.parameters(), lr=lr, betas=(beta1, 0.999))
optimizerD = optim.Adam(discriminator.parameters(), lr=lr, betas=(beta1, 0.999))
# 定义噪声向量
fixed_noise = torch.randn(64, 100, 1, 1, device=device)
# 开始训练
for epoch in range(num_epochs):
for i, data in enumerate(dataloader, 0):
# 更新判别器模型
discriminator.zero_grad()
real_cpu = data[0].to(device)
b_size = real_cpu.size(0)
label = torch.full((b_size,), 1, device=device)
output = discriminator(real_cpu)
errD_real = criterion(output, label)
noise = torch.randn(b_size, 100, 1, 1, device=device)
fake = generator(noise)
label.fill_(0)
output = discriminator(fake.detach())
errD_fake = criterion(output, label)
errD = errD_real + errD_fake
errD.backward()
optimizerD.step()
# 更新生成器模型
generator.zero_grad()
label.fill_(1)
output = discriminator(fake)
errG = criterion(output, label)
errG.backward()
optimizerG.step()
# 打印损失函数和生成的图像
if i % 100 == 0:
print('[%d/%d][%d/%d]\tLoss_D: %.4f\tLoss_G: %.4f'
% (epoch, num_epochs, i, len(dataloader),
errD.item(), errG.item()))
with torch.no_grad():
fake = generator(fixed_noise).detach().cpu()
plt.imshow(fake[0][0], cmap='gray')
plt.show()
```
使用MNIST数据集训练这个模型:
```python
dataset = datasets.MNIST(root='./data', train=True, transform=transforms.Compose([
transforms.Resize(11),
transforms.ToTensor(),
transforms.Normalize((0.5,), (0.5,))
]), download=True)
dataloader = torch.utils.data.DataLoader(dataset, batch_size=64, shuffle=True, num_workers=2)
generator = Generator()
discriminator = Discriminator()
train(generator, discriminator, dataloader)
```
这个模型的训练过程可能需要几个小时或者更长时间,具体取决于你的计算机性能和数据集大小。
阅读全文