基于pytorch的读取csv数据1*121维用dcgan扩充完整代码
时间: 2023-12-22 17:06:21 浏览: 189
DCGAN pytorch实现,基于MNIST数据集
以下是基于PyTorch的读取CSV数据并使用DCGAN扩充的完整代码:
```python
import torch
import torch.nn as nn
import torch.optim as optim
import numpy as np
import pandas as pd
from torch.utils.data import Dataset, DataLoader
from torchvision import transforms, utils
# 定义CSV数据集类
class CSVDataset(Dataset):
def __init__(self, csv_file):
self.data = pd.read_csv(csv_file, header=None)
self.transform = transforms.Compose([
transforms.ToTensor(),
transforms.Normalize((0.5,), (0.5,))
])
def __len__(self):
return len(self.data)
def __getitem__(self, idx):
sample = np.array(self.data.iloc[idx, :], dtype=np.float32)
sample = self.transform(sample)
return sample
# 定义DCGAN生成器
class Generator(nn.Module):
def __init__(self):
super(Generator, self).__init__()
self.fc1 = nn.Linear(100, 256)
self.fc2 = nn.Linear(256, 512)
self.fc3 = nn.Linear(512, 1024)
self.fc4 = nn.Linear(1024, 1*121)
self.relu = nn.ReLU()
self.tanh = nn.Tanh()
def forward(self, x):
x = self.relu(self.fc1(x))
x = self.relu(self.fc2(x))
x = self.relu(self.fc3(x))
x = self.tanh(self.fc4(x))
x = x.view(x.size(0), 1, 11, 11)
return x
# 定义DCGAN判别器
class Discriminator(nn.Module):
def __init__(self):
super(Discriminator, self).__init__()
self.conv1 = nn.Conv2d(1, 64, 4, 2, 1)
self.conv2 = nn.Conv2d(64, 128, 4, 2, 1)
self.fc1 = nn.Linear(128*5*5, 1024)
self.fc2 = nn.Linear(1024, 1)
self.leaky_relu = nn.LeakyReLU(0.2, inplace=True)
self.sigmoid = nn.Sigmoid()
def forward(self, x):
x = self.leaky_relu(self.conv1(x))
x = self.leaky_relu(self.conv2(x))
x = x.view(x.size(0), -1)
x = self.leaky_relu(self.fc1(x))
x = self.sigmoid(self.fc2(x))
return x
# 定义训练函数
def train(netG, netD, dataloader, optimizerG, optimizerD, criterion):
real_label = 1
fake_label = 0
for epoch in range(num_epochs):
for i, data in enumerate(dataloader, 0):
netD.zero_grad()
real_data = data.to(device)
batch_size = real_data.size(0)
label = torch.full((batch_size,), real_label, device=device)
output = netD(real_data)
errD_real = criterion(output, label)
errD_real.backward()
D_x = output.mean().item()
noise = torch.randn(batch_size, 100, device=device)
fake_data = netG(noise)
label.fill_(fake_label)
output = netD(fake_data.detach())
errD_fake = criterion(output, label)
errD_fake.backward()
D_G_z1 = output.mean().item()
errD = errD_real + errD_fake
optimizerD.step()
netG.zero_grad()
label.fill_(real_label)
output = netD(fake_data)
errG = criterion(output, label)
errG.backward()
D_G_z2 = output.mean().item()
optimizerG.step()
if i % 50 == 0:
print('[%d/%d][%d/%d]\tLoss_D: %.4f\tLoss_G: %.4f\tD(x): %.4f\tD(G(z)): %.4f / %.4f'
% (epoch, num_epochs, i, len(dataloader), errD.item(), errG.item(), D_x, D_G_z1, D_G_z2))
# 参数设置
csv_file = 'data.csv'
batch_size = 64
num_epochs = 50
lr = 0.0002
beta1 = 0.5
ngpu = 1
# 数据加载与预处理
dataset = CSVDataset(csv_file)
dataloader = DataLoader(dataset, batch_size=batch_size, shuffle=True, num_workers=2)
# 设备设置
device = torch.device("cuda:0" if (torch.cuda.is_available() and ngpu > 0) else "cpu")
# DCGAN网络初始化
netG = Generator().to(device)
netD = Discriminator().to(device)
# 损失函数与优化器
criterion = nn.BCELoss()
optimizerG = optim.Adam(netG.parameters(), lr=lr, betas=(beta1, 0.999))
optimizerD = optim.Adam(netD.parameters(), lr=lr, betas=(beta1, 0.999))
# 训练DCGAN
train(netG, netD, dataloader, optimizerG, optimizerD, criterion)
```
在这个例子中,我们定义了一个CSVDataset类来从CSV文件中读取数据。我们还定义了一个Generator和Discriminator类作为DCGAN的生成器和判别器。最后,我们使用train函数来训练DCGAN并生成新的数据。
阅读全文