微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

RuntimeError: Given groups=1, weight of size [32, 1, 5, 5], 预期输入 [256, 3, 256, 256] 有 1 个通道,但得到 3 个通道

如何解决RuntimeError: Given groups=1, weight of size [32, 1, 5, 5], 预期输入 [256, 3, 256, 256] 有 1 个通道,但得到 3 个通道

我正在尝试运行以下代码但出现错误

import torch.nn as nn
import torch.nn.functional as F


class EmbeddingNet(nn.Module):
    def __init__(self):
        super(EmbeddingNet,self).__init__()
        self.convnet = nn.Sequential(nn.Conv2d(1,32,5),nn.PReLU(),nn.MaxPool2d(2,stride=2),nn.Conv2d(32,64,stride=2))

        self.fc = nn.Sequential(nn.Linear(64 * 4 * 4,256),nn.Linear(256,2)
                                )

    def forward(self,x):
        output = self.convnet(x)
        output = output.view(output.size()[0],-1)
        output = self.fc(output)
        return output

    def get_embedding(self,x):
        return self.forward(x)


class EmbeddingNetL2(EmbeddingNet):
    def __init__(self):
        super(EmbeddingNetL2,self).__init__()

    def forward(self,x):
        output = super(EmbeddingNetL2,self).forward(x)
        output /= output.pow(2).sum(1,keepdim=True).sqrt()
        return output
   
    def get_embedding(self,x):
        return self.forward(x)'''enter code here

enter image description here

解决方法

错误很简单。它说你给了 3 个通道的图像而不是 1 个通道。

一个变化将在这个块

class EmbeddingNet(nn.Module):
  def __init__(self):
    super(EmbeddingNet,self).__init__()
    self.convnet = nn.Sequential(nn.Conv2d(3,32,5),#instead of 1 i have made it 3
                                 nn.PReLU(),nn.MaxPool2d(2,stride=2),nn.Conv2d(32,64,nn.PReLU(),stride=2))

    self.fc = nn.Sequential(nn.Linear(64 * 4 * 4,256),nn.Linear(256,2)
                            )

编辑下一个错误:
改成这个

self.fc = nn.Sequential(nn.Linear(64 * 61 * 61,#here is the change
                    nn.PReLU(),2)
                    )

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。