【问题标题】:How can I convert the dimension in the model form 2D to 1D?如何将模型形式 2D 中的尺寸转换为 1D?
【发布时间】:2021-05-17 23:18:31
【问题描述】:

我是使用 pytorch 的初学者。我想将 2d 二进制数组 (17 * 20 ) 分类为 8 个类,我使用交叉熵作为损失函数。我有 512 批大小。输入是 512 批大小(17 * 20),最终输出 512 批大小为 8。我应用了以下模型,我希望最终输出仅为长度为 8 的列表。如 [512,8]但我得到了那个暗淡的 [512,680,8] (我在代码之后打印了我从模型中获取的尺寸)。如何从该网络中获得 [512,8] 作为最终输出。

 def __init__(self, M=1):
        super(PPS, self).__init__()
        #input layer
        self.layer1 = nn.Sequential(
             nn.Conv2d(17, 680,  kernel_size=1, stride=1, padding=0),
             nn.ReLU())
        self.drop1 = nn.Sequential(nn.Dropout())
        self.batch1 = nn.BatchNorm2d(680)
        self.lstm1=nn.Sequential(nn.LSTM(
        input_size=20,
        hidden_size=16,
        num_layers=1,
        bidirectional=True,
        batch_first= True))
        self.gru = nn.Sequential(nn.GRU(
            input_size=16*2,
            hidden_size=16,
            num_layers=2,
            bidirectional=True,
            batch_first=True))
        self.fc1 = nn.Linear(16*2,8)

    def forward(self, x):
     
        out = self.layer1(x)
        out = self.drop1(out)
        out = self.batch1(out)
        out = out.squeeze()
        out,_ = self.lstm1(out)
        out,_ = self.gru(out)
        out = self.fc1(out)
        return out
cov2d torch.Size([512, 680, 20, 1])
drop torch.Size([512, 680, 20, 1])
batch torch.Size([512, 680, 20])
lstm1 torch.Size([512, 680, 32])
lstm2 torch.Size([512, 680, 32])
linear1 torch.Size([512, 680, 8])

【问题讨论】:

    标签: computer-vision pytorch conv-neural-network flatten cross-entropy


    【解决方案1】:

    如果您希望输出为(512, 8),那么您必须将最后一个线性层更改为如下内容:

    def __init__(self, M=1):
        ...
        self.gru = nn.Sequential(nn.GRU(
                input_size=16*2,
                hidden_size=16,
                num_layers=2,
                bidirectional=True,
                batch_first=True))
        self.fc1 = nn.Linear(680 * 16*2, 8)
    
        def forward (self, x):
            ...
            out, _ = self.gru(out)
            out = self.fc1(out.reshape(-1, 680 * 16*2))
            return out
    

    目标是将特征数量从680 * 16 * 2 减少到8。您可以(并且可能应该)添加更多最终线性层来为您减少这种情况。

    【讨论】:

    • 谢谢,我试过那个解决方案,但它给了我一个错误 out = self.fc1(out.view(-1, 680 * 16*2)) RuntimeError: view size is not compatible with输入张量的大小和步幅(至少一个维度跨越两个连续的子空间)。改用 .reshape(...)
    • 您可以按照提示的错误消息执行.reshape()。我已经编辑了我的答案,请检查。
    猜你喜欢
    • 2016-01-23
    • 1970-01-01
    • 1970-01-01
    • 2011-06-30
    • 2017-07-29
    • 1970-01-01
    • 2020-10-25
    • 2022-01-17
    • 2019-02-03
    相关资源
    最近更新 更多