conv2d 函数的参数问题

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

我有CNN的代码:

import numpy as np
import torch
import torch.nn as nn

class CNN(nn.Module):
 def __init__(self):
  super(CNN, self).__init__()
    self.n = 10
    kernel_size = 3
    padding = (kernel_size - 1) / 2
    self.conv1 = nn.Conv2d(in_channels=3,out_channels=self.n,kernel_size=kernel_size,stride = (2,2),padding=padding),

    self.conv2 = nn.Conv2d(in_channels=self.n,out_channels=2*self.n,kernel_size=kernel_size,stride = (2,2),padding=padding),
        
    self.conv3 = nn.Conv2d(in_channels=2*self.n,out_channels=4*self.n,kernel_size=kernel_size,stride = (2,2),padding=padding),
    
    self.conv4 = nn.Conv2d(in_channels=4*self.n,out_channels=8*self.n,kernel_size=kernel_size,stride = (2,2),padding=padding),
    
    self.fc1 = nn.Linear(8 * self.n * 7 * 4, 100)
    self.fc2 = nn.Linear(100, 2) 

 def forward(self,inp):
   out = nn.functional.relu(self.conv1(inp))
   out = nn.functional.relu(self.conv2(out))
   out = nn.functional.relu(self.conv3(out))
   out = nn.functional.relu(self.conv4(out))

   out = out. View(-1, 8 * self.n * 7 * 4)
   out = nn.functional.relu(self.fc1(out)) 
   out = self.fc2(out)
    
   return out

我收到错误:

TypeError: conv2d() received an invalid combination of arguments - got (Tensor, Parameter, Parameter, tuple, tuple, tuple, int), but expected one of:
 * (Tensor input, Tensor weight, Tensor bias, tuple of ints stride, tuple of ints padding, tuple of ints dilation, int groups)
      didn't match because some of the arguments have invalid types: (Tensor, !Parameter!, !Parameter!, !tuple of (int, int)!, !tuple of (float, float)!, !tuple of (int, int)!, int)
 * (Tensor input, Tensor weight, Tensor bias, tuple of ints stride, str padding, tuple of ints dilation, int groups)
      didn't match because some of the arguments have invalid types: (Tensor, !Parameter!, !Parameter!, !tuple of (int, int)!, !tuple of (float, float)!, !tuple of (int, int)!, int)

如何解决?

machine-learning pytorch conv-neural-network
1个回答
0
投票

请注意,图层定义末尾有逗号。这些必须删除(这已经向您指出了here)。

这个错误的原因是

padding
应该是一个整数:

padding = (kernel_size - 1) // 2

在这种情况下,您的模型将按预期工作:

>>> CNN()(torch.rand(1,3,100,50)).shape
torch.Size([1, 2])
© www.soinside.com 2019 - 2024. All rights reserved.