You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
I am trying to use aw loss in my cDCGAN. Unexpected issues occurred during code compilation. I don't quite understand. I hope to receive your help. Alternatively, upload an application instance of 'awloss'.
My code is as follows:
import torch
import torch.nn as nn
import torchvision.transforms as transforms
import torchvision.datasets as dset
from tqdm.autonotebook import tqdm
from torchvision.utils import save_image
from matplotlib import pyplot as plt
import numpy as np
from torch.autograd import Variable
from new_loss import aw_method
labels = labels.reshape(100, 1)
one_hot = nn.functional.one_hot(labels, num_classes=10) # i labels codificato in one_hot
fixed_label = one_hot.reshape(100, 10, 1, 1).float()
我在 onehot 中为数字 0 到 9 创建了自己的转换器:
onehot_before_cod = torch.LongTensor([i for i in range(10)]).cuda() # 0123456789
onehot = nn.functional.one_hot(onehot_before_cod, num_classes=10)
onehot = onehot.reshape(10, 10, 1, 1).float()
D_loss = []
G_loss = []
for epoch in tqdm(range(num_epochs)):
D_losses = []
G_losses = []
if epoch == 5 or epoch == 10:
G_opt.param_groups[0]['lr'] /= 2
D_opt.param_groups[0]['lr'] /= 2
# training
err_D, err_G = train_GAN(G, D, G_opt, D_opt, train_loader)
D_loss.append(err_D)
G_loss.append(err_G)
# test
if epoch % 1 == 0 or epoch + 1 == num_epochs:
with torch.no_grad():
out_imgs = G(fixed_noise.to(device), fixed_label.to(device))
save_image(out_imgs, f"{PATH}{epoch}.png",
nrow=10) # aggiungi percorso: "path/iterazione_classe.png" es "pippo/20000_3.png"
# salva i modelli
torch.save(D.state_dict(), f'{PATH}discriminator_cDCGAN_{epoch}.pth')
torch.save(G.state_dict(), f'{PATH}generator_cDCGAN_{epoch}.pth')
Unexpected issues occurred:
Traceback (most recent call last):
File "D:\python_parctice\pt\个人练习\数据预处理模板\不平衡图像数据的条件生成对抗网络生成\cDCGAN-main\cDCGAN MNIST.py", line 267, in
err_D, err_G = train_GAN(G, D, G_opt, D_opt, train_loader)
File "D:\python_parctice\pt\个人练习\数据预处理模板\不平衡图像数据的条件生成对抗网络生成\cDCGAN-main\cDCGAN MNIST.py", line 192, in train_GAN
aw_loss.backward(retain_graph=True)
File "D:\Anaconda\install\envs\pt\lib\site-packages\torch_tensor.py", line 487, in backward
torch.autograd.backward(
File "D:\Anaconda\install\envs\pt\lib\site-packages\torch\autograd_init_.py", line 200, in backward
Variable._execution_engine.run_backward( # Calls into the C++ engine to run the backward pass
RuntimeError: Trying to backward through the graph a second time (or directly access saved tensors after they have already been freed). Saved intermediate values of the graph are freed when you call .backward() or autograd.grad(). Specify retain_graph=True if you need to backward through the graph a second time or if you need to access saved tensors after calling backward.
The text was updated successfully, but these errors were encountered:
I am trying to use aw loss in my cDCGAN. Unexpected issues occurred during code compilation. I don't quite understand. I hope to receive your help. Alternatively, upload an application instance of 'awloss'.
My code is as follows:
import torch
import torch.nn as nn
import torchvision.transforms as transforms
import torchvision.datasets as dset
from tqdm.autonotebook import tqdm
from torchvision.utils import save_image
from matplotlib import pyplot as plt
import numpy as np
from torch.autograd import Variable
from new_loss import aw_method
num_epochs = 1000
betas = (0.5, 0.999)
lr = 0.0002 # 1e-5
batch_size = 64
device = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu')
z_dim = 100 # latent Space
c_dim = 1 # Image Channel
label_dim = 10 # label
image_size = 32
beta1 = 0.5
PATH = "./generate/"
generator_out_linear = 100 # l rumore che andrà al generatore sarà 100+generator_out_linear, deve essere >=10
MNIST dataset
transform = transforms.Compose([
transforms.Resize((image_size, image_size)),
transforms.ToTensor(),
# transforms.Normalize((0.5,),(0.5,)),
])
train_set = dset.MNIST(root='./mnist_data/',
train=True,
transform=transform,
download=True)
test_set = dset.MNIST(root='./mnist_data/',
train=False,
transform=transform,
download=False)
train_loader = torch.utils.data.DataLoader(
dataset=train_set,
batch_size=batch_size,
shuffle=True,
drop_last=True
)
test_loader = torch.utils.data.DataLoader(
dataset=test_set,
batch_size=batch_size,
shuffle=False,
drop_last=True
)
Generator model
class Generator(nn.Module):
def init(self, z_dim, label_dim):
super(Generator, self).init()
Discriminator model
class Discriminator(nn.Module):
def init(self, nc=1, label_dim=10):
super(Discriminator, self).init()
def weights_init(m):
# 用于初始化神经网络模型的权重和偏差
classname = m.class.name
if classname.find('Conv') != -1:
nn.init.normal_(m.weight.data, 0.0, 0.02) # 初始化卷积层,将权重参数的值从均值0.0、标准差0.02的正态分布中随机抽取
elif classname.find('BatchNorm') != -1:
nn.init.normal_(m.weight.data, 1.0, 0.02)
nn.init.constant_(m.bias.data, 0)
创建 aw_method 实例,可以根据需要自定义超参数
aw = aw_method(alpha1=0.5, alpha2=0.75, delta=0.05, epsilon=0.05, normalized_aw=True)
def train_GAN(G, D, G_opt, D_opt, dataset):
for i, (data, label) in tqdm(enumerate(dataset)):
'''
plt.figure(figsize=(8,8))
plt.axis("off")
plt.title("Training Images")
plt.imshow(np.transpose(vutils.make_grid(data, padding=2).cpu(),(1,2,0)))
plt.show()
'''
Models
D = Discriminator(c_dim, label_dim).to(device)
D.apply(weights_init)
G = Generator(z_dim, label_dim).to(device)
G.apply(weights_init)
D_opt = torch.optim.Adam(D.parameters(), lr=lr, betas=(beta1, 0.999)) # , betas=(beta1, 0.999))
G_opt = torch.optim.Adam(G.parameters(), lr=lr, betas=(beta1, 0.999)) # , betas=(beta1, 0.999))
Loss function
criterion = torch.nn.BCELoss()
创建一个固定噪声,用于测试
fixed_noise = torch.randn(100, 100)
fixed_noise = fixed_noise.reshape(100, 100, 1, 1)
创建一个固定标签,
labels = torch.LongTensor([i for i in range(10) for _ in range(
10)]).cuda()
labels = 00000000001111111111222222222233333333334444444444555555555566666666667777777777788888888889999999999
labels = labels.reshape(100, 1)
one_hot = nn.functional.one_hot(labels, num_classes=10) # i labels codificato in one_hot
fixed_label = one_hot.reshape(100, 10, 1, 1).float()
我在 onehot 中为数字 0 到 9 创建了自己的转换器:
onehot_before_cod = torch.LongTensor([i for i in range(10)]).cuda() # 0123456789
onehot = nn.functional.one_hot(onehot_before_cod, num_classes=10)
onehot = onehot.reshape(10, 10, 1, 1).float()
D_loss = []
G_loss = []
for epoch in tqdm(range(num_epochs)):
D_losses = []
G_losses = []
if epoch == 5 or epoch == 10:
G_opt.param_groups[0]['lr'] /= 2
D_opt.param_groups[0]['lr'] /= 2
Unexpected issues occurred:
Traceback (most recent call last):
File "D:\python_parctice\pt\个人练习\数据预处理模板\不平衡图像数据的条件生成对抗网络生成\cDCGAN-main\cDCGAN MNIST.py", line 267, in
err_D, err_G = train_GAN(G, D, G_opt, D_opt, train_loader)
File "D:\python_parctice\pt\个人练习\数据预处理模板\不平衡图像数据的条件生成对抗网络生成\cDCGAN-main\cDCGAN MNIST.py", line 192, in train_GAN
aw_loss.backward(retain_graph=True)
File "D:\Anaconda\install\envs\pt\lib\site-packages\torch_tensor.py", line 487, in backward
torch.autograd.backward(
File "D:\Anaconda\install\envs\pt\lib\site-packages\torch\autograd_init_.py", line 200, in backward
Variable._execution_engine.run_backward( # Calls into the C++ engine to run the backward pass
RuntimeError: Trying to backward through the graph a second time (or directly access saved tensors after they have already been freed). Saved intermediate values of the graph are freed when you call .backward() or autograd.grad(). Specify retain_graph=True if you need to backward through the graph a second time or if you need to access saved tensors after calling backward.
The text was updated successfully, but these errors were encountered: