使用pytorchviz进行模型可视化出现 'NoneType' object has no attribute 'grad_fn'
问题
最近学习pytorch, 原来用kreas重现的模型改为用pytorch实现训练,因为这样给模型的操作更加细致, 对模型的掌控更好。
当我写好一个模型 出现了这个问题
使用pytorchviz进行模型可视化出现r如下错误
raceback (most recent call last):
File "/home/jiwu/Documents/AttRCNN-CNNs/pyt_train.py", line 174, in <module>
g = make_dot(y)
File "/home/jiwu/.virtualenvs/jiwu/lib/python3.6/site-packages/torchviz/dot.py", line 37, in make_dot
output_nodes = (var.grad_fn,) if not isinstance(var, tuple) else tuple(v.grad_fn for v in var)
AttributeError: 'NoneType' object has no attribute 'grad_fn'
找了很久没发现原因在哪里, 翻pytorchviz的issue, 一直google没找到原因,最后才发现是只是在foward 函数 我没有return x。 所以出现了这个问题。
def forward(self, x):
print (x.shape)
x1 = self.conv1(x)
x2 = self.conv2(x)
print (x2.shape)
x3 = self.conv3(x)
x4 = self.conv4(x)
print (x1.shape, x2.shape, x3.shape, x4.shape)
x = torch.cat((x1, x2, x3, x4), dim = 1)
print (x.shape)
x = x.view(x.size(0), -1)
print(x.shape)
x = self.line1(x)
x = self.line2(x)
x = self.line3(x)
return x