Python 调试或跳过顺序pytorch模型的最佳方法
我曾经用Python 调试或跳过顺序pytorch模型的最佳方法,python,debugging,deep-learning,pycharm,pytorch,Python,Debugging,Deep Learning,Pycharm,Pytorch,我曾经用nn.Module编写PyTorch模型,其中包括\uuuu init\uuuuu和forward,这样我就可以跨过我的模型来检查变量维度如何沿网络变化。 然而,我已经意识到,您也可以使用nn.Sequential来实现它,它只需要\uuuu init\uuuu,您不需要编写如下所示的转发函数: 然而,问题是当我试图跨过这个网络时,再检查变量就不容易了。它只是跳到另一个地方然后再回来 有人知道在这种情况下该怎么做吗 附言:我正在使用PyCharm。您可以迭代如下模型的子项并打印大小以进
nn.Module
编写PyTorch模型,其中包括\uuuu init\uuuuu
和forward,这样我就可以跨过我的模型来检查变量维度如何沿网络变化。
然而,我已经意识到,您也可以使用nn.Sequential
来实现它,它只需要\uuuu init\uuuu
,您不需要编写如下所示的转发函数:
然而,问题是当我试图跨过这个网络时,再检查变量就不容易了。它只是跳到另一个地方然后再回来
有人知道在这种情况下该怎么做吗
附言:我正在使用PyCharm。您可以迭代如下模型的子项并打印大小以进行调试。这类似于向前写入,但您可以编写一个单独的函数,而不是创建
nn.Module
类
import torch
from torch import nn
model = nn.Sequential(
nn.Conv2d(1,20,5),
nn.ReLU(),
nn.Conv2d(20,64,5),
nn.ReLU()
)
def print_sizes(model, input_tensor):
output = input_tensor
for m in model.children():
output = m(output)
print(m, output.shape)
return output
input_tensor = torch.rand(100, 1, 28, 28)
print_sizes(model, input_tensor)
# output:
# Conv2d(1, 20, kernel_size=(5, 5), stride=(1, 1)) torch.Size([100, 20, 24, 24])
# ReLU() torch.Size([100, 20, 24, 24])
# Conv2d(20, 64, kernel_size=(5, 5), stride=(1, 1)) torch.Size([100, 64, 20, 20])
# ReLU() torch.Size([100, 64, 20, 20])
# you can also nest the Sequential models like this. In this case inner Sequential will be considered as module itself.
model1 = nn.Sequential(
nn.Conv2d(1,20,5),
nn.ReLU(),
nn.Sequential(
nn.Conv2d(20,64,5),
nn.ReLU()
)
)
print_sizes(model1, input_tensor)
# output:
# Conv2d(1, 20, kernel_size=(5, 5), stride=(1, 1)) torch.Size([100, 20, 24, 24])
# ReLU() torch.Size([100, 20, 24, 24])
# Sequential(
# (0): Conv2d(20, 64, kernel_size=(5, 5), stride=(1, 1))
# (1): ReLU()
# ) torch.Size([100, 64, 20, 20])