pytorch错误提示TypeError: conv2d() received an invalid combination of arguments

问题遇到的现象和发生背景
问题相关代码,请勿粘贴截图
运行结果及报错内容
我的解答思路和尝试过的方法
我想要达到的结果

提示错误
Traceback (most recent call last):
File "G:/PYxiangmu/les_1/les4.py", line 97, in
output = mymodel(data)
File "D:\pyanzhuang38\lib\site-packages\torch\nn\modules\module.py", line 1102, in _call_impl
return forward_call(*input, **kwargs)
File "G:/PYxiangmu/les_1/les4.py", line 57, in forward
x = self.conv1(x)
File "D:\pyanzhuang38\lib\site-packages\torch\nn\modules\module.py", line 1102, in _call_impl
return forward_call(*input, **kwargs)
File "D:\pyanzhuang38\lib\site-packages\torch\nn\modules\container.py", line 141, in forward
input = module(input)
File "D:\pyanzhuang38\lib\site-packages\torch\nn\modules\module.py", line 1102, in _call_impl
return forward_call(*input, **kwargs)
File "D:\pyanzhuang38\lib\site-packages\torch\nn\modules\conv.py", line 446, in forward
return self._conv_forward(input, self.weight, self.bias)
File "D:\pyanzhuang38\lib\site-packages\torch\nn\modules\conv.py", line 442, in _conv_forward
return F.conv2d(input, weight, bias, self.stride,
TypeError: conv2d() received an invalid combination of arguments - got (int, 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: (!int!, !Parameter!, !Parameter!, !tuple!, !tuple!, !tuple!, 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: (!int!, !Parameter!, !Parameter!, !tuple!, !tuple!, !tuple!, int)


import torch
import torch.nn as nn
from torchvision import datasets, transforms
from torchvision.datasets import MNIST
import torch.optim as optim
import numpy as np
import torch.nn.functional as F
import matplotlib.pyplot as plt
from torch.utils.data import DataLoader

# -- 定义超参数
input_size = 28  # -- 图片尺寸28*28
num_class = 10  # -- 最后分类情况 10分类0-9
num_epochs = 3  # -- 循环3个周期
batch_size = 64  # -- batch大小64

# -- 训练集
train_dataset = MNIST(root="./data/", train=True, transform=transforms.ToTensor(), download=True)
# -- 测试集
test_dataset = MNIST(root="./data/", train=False, transform=transforms.ToTensor())

# -- 构建batch数据
train_loader = DataLoader(dataset=train_dataset,
                          batch_size=batch_size,
                          shuffle=True)
test_loader = DataLoader(dataset=test_dataset,
                         batch_size=batch_size,
                         shuffle=True)


# -- 定义模型
class CNN_Model(nn.Module):
    def __init__(self):
        super(CNN_Model, self).__init__()
        # -- 第一个卷积单元  卷积 relu 池化        输入图为28*28*1 输出结果为 16 *14 *14
        self.conv1 = nn.Sequential(
            nn.Conv2d(in_channels=1,  # -- 输入的灰度图  1通道 所以是1
                      out_channels=16,  # -- 想得到多少个特征图  输出的特征图16个
                      kernel_size=5,  # -- 卷积核的大小 5*5 提取成1个点
                      stride=1,  # -- 步长为1
                      padding=2  # -- 填充0
                      ),
            nn.ReLU(),  # -- relu层
            nn.MaxPool2d(kernel_size=2)  # -- 池化操作 输出结果为 16 *14 *14
        )
        # -- 第二个卷积单元 输入为16*14*14  输出10分类
        self.conv2 = nn.Sequential(
            nn.Conv2d(16, 32, 5, 1, 2),  # -- 输入为16*14*14
            nn.ReLU(),
            nn.MaxPool2d(2)  # -- 输出为32*7*7
        )
        self.out = nn.Linear(32 * 7 * 7, 10)  # -- 全连接层 输出10分类

    # -- 前向传播
    def forward(self, x):
        x = self.conv1(x)
        x = self.conv2(x)
        x = x.view(x.size(0), -1)  # -- flatten操作  拉成一维数组形式  才能进行全连接输出
        output = self.out(x)
        return output


# -- 定义一个评估函数
def pinggu(predictions, labels):
    pred = torch.max(predictions.data, 1)[1]
    right = pred.eq(labels.data.view_as(pred)).sum()
    return right, len(labels)


# -- 训练网络模型
# -- 实例化
mymodel = CNN_Model()
# -- 损失函数
loss_fn = nn.CrossEntropyLoss()
# -- 优化器    # 普通的随机梯度下降
optimizer = optim.Adam(mymodel.parameters(), lr=0.001)

# -- 开始训练
for epoch in range(num_epochs):
    # -- 当前epoch结果保存起来
    train_right = []
    for batch_idx, (data, target) in enumerate(train_loader):
        mymodel.train()
        output = mymodel(data)
        loss = loss_fn(output, target)
        optimizer.zero_grad()
        loss.backward()
        optimizer.step()
        right = pinggu(output, target)
        train_right.append(right)

        if batch_idx % 100 == 0:
            mymodel.eval()
            val_right = []
            for (data, target) in enumerate(test_loader):
                output = mymodel(data)
                right = pinggu(output, target)
                val_right.append(right)

            # -- 准确率计算
            train_r = (sum([tup[0] for tup in train_right]), sum([tup[1] for tup in train_right]))
            val_r = (sum([tup[0] for tup in val_right]), sum([tup[1] for tup in val_right]))

            print('当前epoch:{} [{}/{} ({:.0f}%)]\t 损失:{:.6f}\t 训练集准确率: {:.2f}%\t 测试集准确率:{:.2f}%'.format(
                epoch, batch_idx * batch_size, len(train_loader.dataset),
                       100. * batch_idx / len(train_loader),
                       loss.data,
                       100. * train_r[0].numpy() / train_r[1],
                       100. * val_r[0].numpy() / val_r[1]
            ))

你好,解决了吗,我也遇到这个问题

你好,请问解决了吗,我也遇到了类似的问题!

Conv2d 2维卷积的第三个参数kernel_size 是元组类型 (x,y)这种, 你这参数5.,是啥意思?一维卷积? 看你的代码,改成kernel_size = (5,5)吧