【问题标题】:How to construct CNN with 400 nodes hidden layer using PyTorch?如何使用 PyTorch 构建具有 400 个节点隐藏层的 CNN?
【发布时间】:2021-08-17 03:59:21
【问题描述】:

我想使用 PyTorch 创建具有 400 个节点的卷积层,如下所示,条件为具有 400 个隐藏神经元/输出为 10 的全连接线性层,将图像展平为输入向量,并使用 ReLU 函数。

当我打印出x.shape 时,它会返回torch.Size([1024, 300])torch.Size([1024, 10]),而我的第一层是torch.Size([100, 3, 32, 32])。我很困惑如何构建这个简单的 CNN 以及我缺少什么。

class MyNet(nn.Module):
 def __init__(self):
  super(MyNet, self).__init__()
  self.relu = nn.ReLU()
  self.fc1 = torch.nn.Linear(400, 10)

  def forward(self, x):
   x = x.view(-1, 400)
   print(x.shape)
   x = self.relu(self.fc1(x))
   print(x.shape)

   return x



【问题讨论】:

    标签: python deep-learning neural-network pytorch conv-neural-network


    【解决方案1】:

    我想你希望中间线性层有 400 个单元,首先是 1 个 conv 层,最后是一个有 10 个单元的线性层用于分类。

    您需要这样的网络:

    import torch
    import torch.nn as nn
    import torch.nn.functional as F
    
    
    class Net(nn.Module):
        def __init__(self, n_channel = 3, final_conv_feature_size = (8,8), conv_filters = 32):
            super(Net, self).__init__()
            self.conv1 = nn.Conv2d(n_channel, conv_filters, 3, 1) # first layer with 32 filters
            self.adapt = nn.AdaptiveMaxPool2d(final_conv_feature_size)
            self.fc1 = nn.Linear(conv_filters * final_conv_feature_size[0] * final_conv_feature_size[1] , 400)
            self.fc2 = nn.Linear(400, 10)
    
        def forward(self, x):
            x = self.conv1(x)
            x = F.relu(x)
            x = self.adapt(x)
            x = torch.flatten(x, 1)
            x = self.fc1(x)
            x = F.relu(x)
            x = self.fc2(x)
            output = F.log_softmax(x, dim=1)
            return output
    
    model = Net()
    print(model)
    
    Net(
      (conv1): Conv2d(3, 32, kernel_size=(3, 3), stride=(1, 1))
      (adapt): AdaptiveMaxPool2d(output_size=(8, 8))
      (fc1): Linear(in_features=2048, out_features=400, bias=True)
      (fc2): Linear(in_features=400, out_features=10, bias=True)
    )
    

    【讨论】:

      猜你喜欢
      • 2020-05-11
      • 1970-01-01
      • 1970-01-01
      • 2019-02-28
      • 1970-01-01
      • 2020-02-02
      • 2019-03-30
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多