运行卷积神经网络报错
1、RuntimeError:Given groups=1, expected weight to be at least 1 at dimension 0, but got weight of size [0, 2, 3, 3] instead
错误代码:
in_num, out_num = 256, 128
for i in range(8):
enc_model += [
nn.Conv2d(in_channels=in_num, out_channels=out_num, kernel_size=3, stride=1, padding=1),
nn.ReLU(inplace=True),
]
in_num = out_num
out_num >>= 2
错误原因:out_num >>= 2
导致batch size变为了0,因此出现了上述的错误,而本来想要经过for循环将batch size变为1,所以改为out_num >>= 1
即可。
2、RuntimeError: Attempting to deserialize object on a CUDA device but torch.cuda.is_available() is False. If you are running on a CPU-only machine, please use torch.load with map_location=torch.device(‘cpu’) to map your storages to the CPU.
错误原因:使用 PyTorch 的 torch.load() 函数加载模型,但这个模型是在 GPU 上训练的,而当前运行环境是CPU。
解决方法:在加载模型时明确指定映射位置,即在 torch.load() 函数中使用 map_location 参数,将模型映射到 CPU 上。
device = torch.device('cpu')
model = torch.load('path', map_location=device)
3、RuntimeError: Can’t call numpy() on Tensor that requires grad. Use tensor.detach().numpy() instead.
错误原因:试图直接将需要梯度的Tensor转换为numpy数组,在PyTorch中,需要梯度的Tensor是存储在GPU上的,因此不能直接转换为numpy数组
解决办法:先调用.detach()方法将Tensor从计算图中分离出来,然后调用.numpy()将其转换为numpy数组
tensor.detach().numpy()