报错信息如下:
RuntimeError Traceback (most recent call last)
~\AppData\Local\Temp/ipykernel_19156/279535578.py in <module>
59
60 #2、用噪声生成一张假图片
---> 61 noise.data.resize_(data.size()[0], input_dim, 1, 1).normal_(0, 1) #噪声是一个input_dim维度的向量
62 #喂给生成器生成图像
63 fake_pic=netG(noise).detach() #这里的detach是为了让生成器不参与梯度更新
RuntimeError: set_sizes_contiguous is not allowed on a Tensor created from .data or .detach().
If your intent is to change the metadata of a Tensor (such as sizes / strides / storage / storage_offset)
without autograd tracking the change, remove the .data / .detach() call and wrap the change in a `with torch.no_grad():` block.
For example, change:
x.data.set_(y)
to:
with torch.no_grad():
x.set_(y)
按照错误提示改了去掉.data之后运行仍然报错,报错信息如下:
RuntimeError Traceback (most recent call last)
~\AppData\Local\Temp/ipykernel_19156/1757806420.py in <module>
59
60 #2、用噪声生成一张假图片
---> 61 noise.resize_(data.size()[0], input_dim, 1, 1).normal_(0, 1) #噪声是一个input_dim维度的向量
62 #喂给生成器生成图像
63 fake_pic=netG(noise).detach() #这里的detach是为了让生成器不参与梯度更新
RuntimeError: cannot resize variables that require grad
然后我在网上查了很多资料都没能解决问题,最后是通过去掉前面的noise的参数require_grad选项或者使其为false
# 模型的输入输出
# 生成一个随机噪声输入给生成器
noise=torch.tensor((batch_size, input_dim, 1, 1), dtype = torch.float, requires_grad = True)
修改之后如下:
# 模型的输入输出
# 生成一个随机噪声输入给生成器
noise=torch.tensor((batch_size, input_dim, 1, 1), dtype = torch.float)
#固定噪声是用于评估生成器结果的,它在训练过程中始终不变
fixed_noise=torch.FloatTensor(batch_size, input_dim, 1, 1).normal_(0,1).requires_grad_(True)
即可解决问题。