使用torch.utils.tensorboard添加图形时如何解决RuntimeError

问题描述 投票:0回答:1

我正在尝试使用张量板来可视化我的pytorch模型并遇到问题。输入张量的形状为(-1、1、20、15),输出张量的形状为(-1、6)。我的模型结合了5个卷积网络的列表。

包装:

  • python:3.7.6
  • 火炬:1.4.0
  • 张量板:2.1.0

pytorch模型如下:

import torch
from torch import nn
from torch.nn import functional as F
class MyModel(nn.Module):
    """example"""

    def __init__(self, nchunks=[2, 5, 3, 2, 3], resp_size=6):
        super().__init__()
        self.nchunks = nchunks
        self.conv = [nn.Conv2d(1, 2, (2, x)) for x in nchunks]
        self.pool = nn.Sequential(
            nn.AdaptiveMaxPool1d(output_size=10), nn.Flatten(start_dim=1)
        )
        self.bn = nn.BatchNorm1d(100)
        self.fc1 = nn.Linear(100, 100)
        self.fc2 = nn.Linear(100, 100)
        self.fc3 = nn.Linear(100, resp_size)

    def forward(self, x):
        xi = torch.split(x, self.nchunks, dim=3)
        xi = [f(subx.float()).view(-1, 2, 19) for f, subx in zip(self.conv, xi)]
        xi = [self.pool(subx) for subx in xi]
        xi = torch.cat(xi, dim=1)
        xi = self.bn(xi)
        xi = F.relu(self.fc1(xi))
        xi = F.relu(self.fc2(xi))
        xi = self.fc3(xi)
        return xi

这是张量板摘要编写器的代码:

from torch.utils.tensorboard import SummaryWriter
x = torch.rand((5,1,20,15))
model = MyModel()
writer = SummaryWriter('logs')
writer.add_graph(model, x)

返回错误:

RuntimeError: Cannot insert a Tensor that requires grad as a constant. Consider making it a parameter or input, or detaching the gradient
Tensor:
(1,1,.,.) =
 -0.2108 -0.4986
 -0.4009 -0.1910

(2,1,.,.) =
  0.2383 -0.4147
  0.2642  0.0456
[ torch.FloatTensor{2,1,2,2} ]

我猜该模型存在一些问题,但是我不确定会发生什么。

此相似的github issue与我的问题无关,因为我没有使用多GPU。

pytorch tensorboard
1个回答
0
投票

我通过替换解决了问题

[nn.Conv2d(1, 2, (2, x)) for x in nchunks]

nn.ModuleList([[nn.Conv2d(1, 2, (2, x)) for x in nchunks])
© www.soinside.com 2019 - 2024. All rights reserved.