基于pytorch读取1*121维csv文件用dcgan生成一维数据代码
时间: 2023-09-22 14:15:32 浏览: 111
以下是一个使用PyTorch实现DCGAN生成一维数据的示例代码,假设csv文件中只有一列数据,共121行:
```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
# 定义数据集类
class MyDataset(Dataset):
def __init__(self, csv_file):
self.data = pd.read_csv(csv_file, header=None).values
self.transform = transforms.Compose([
transforms.ToTensor(),
transforms.Normalize((127.5,), (127.5,))
])
def __len__(self):
return len(self.data)
def __getitem__(self, idx):
return self.transform(self.data[idx])
# 定义生成器模型
class Generator(nn.Module):
def __init__(self, input_size, output_size):
super(Generator, self).__init__()
self.fc1 = nn.Linear(input_size, 64)
self.bn1 = nn.BatchNorm1d(64)
self.fc2 = nn.Linear(64, 128)
self.bn2 = nn.BatchNorm1d(128)
self.fc3 = nn.Linear(128, output_size)
self.tanh = nn.Tanh()
def forward(self, x):
x = self.fc1(x)
x = self.bn1(x)
x = nn.functional.leaky_relu(x, 0.2)
x = self.fc2(x)
x = self.bn2(x)
x = nn.functional.leaky_relu(x, 0.2)
x = self.fc3(x)
x = self.tanh(x)
return x
# 定义判别器模型
class Discriminator(nn.Module):
def __init__(self, input_size):
super(Discriminator, self).__init__()
self.fc1 = nn.Linear(input_size, 128)
self.fc2 = nn.Linear(128, 64)
self.fc3 = nn.Linear(64, 1)
def forward(self, x):
x = nn.functional.leaky_relu(self.fc1(x), 0.2)
x = nn.functional.dropout(x, 0.3)
x = nn.functional.leaky_relu(self.fc2(x), 0.2)
x = nn.functional.dropout(x, 0.3)
x = self.fc3(x)
return x
# 定义训练函数
def train(model_G, model_D, train_loader, epochs, lr):
criterion = nn.BCEWithLogitsLoss()
optimizer_G = optim.Adam(model_G.parameters(), lr=lr)
optimizer_D = optim.Adam(model_D.parameters(), lr=lr)
fixed_noise = torch.randn(1, 100)
for epoch in range(epochs):
for i, data in enumerate(train_loader, 0):
real_data = data.to(device)
fake_noise = torch.randn(real_data.size(0), 100).to(device)
fake_data = model_G(fake_noise)
# 训练判别器
optimizer_D.zero_grad()
real_labels = torch.ones(real_data.size(0), 1).to(device)
fake_labels = torch.zeros(real_data.size(0), 1).to(device)
real_output = model_D(real_data)
fake_output = model_D(fake_data.detach())
loss_D = criterion(real_output, real_labels) + criterion(fake_output, fake_labels)
loss_D.backward()
optimizer_D.step()
# 训练生成器
optimizer_G.zero_grad()
fake_labels = torch.ones(real_data.size(0), 1).to(device)
fake_output = model_D(fake_data)
loss_G = criterion(fake_output, fake_labels)
loss_G.backward()
optimizer_G.step()
# 每个epoch生成一组样本数据
if epoch % 100 == 0:
print("Epoch:", epoch)
with torch.no_grad():
fake_data = model_G(fixed_noise).cpu().numpy()
fake_data = (fake_data * 127.5 + 127.5).reshape(121)
print("Generated data:", fake_data)
# 定义训练参数
batch_size = 1
input_size = 100
output_size = 121
epochs = 1000
lr = 0.0002
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
print("Device:", device)
# 加载数据集
dataset = MyDataset("data.csv")
train_loader = DataLoader(dataset, batch_size=batch_size, shuffle=True)
# 初始化模型并开始训练
model_G = Generator(input_size, output_size).to(device)
model_D = Discriminator(output_size).to(device)
train(model_G, model_D, train_loader, epochs, lr)
```
需要注意的是,PyTorch的神经网络模型和训练过程与TensorFlow有所不同,但逻辑类似。此外,对于PyTorch的GPU加速,需要将模型和数据都放到GPU上进行计算,可以通过 `to(device)` 方法实现。
阅读全文