【问题标题】:How to solve the RuntimeError when using torch.utils.tensorboard to add a graph使用torch.utils.tensorboard添加图表时出现RuntimeError如何解决
【发布时间】:2020-05-21 18:28:08
【问题描述】:

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

包:

  • 蟒蛇:3.7.6
  • pytorch: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】:

    我通过替换解决了问题

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

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

    【讨论】:

      猜你喜欢
      • 2020-02-07
      • 2022-07-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-25
      • 1970-01-01
      • 2018-09-23
      • 2019-12-03
      相关资源
      最近更新 更多