python - 如何在 PyTorch 中的许多 conv 层之后指定 flatten 层输入大小?
问题描述
这是我的问题,我在 CIFAR10 数据集上做了一个小测试,如何在 PyTorch 中指定扁平层输入大小?如下所示,输入大小为 16*5*5,但是我不知道如何计算,我想通过一些函数获取输入大小。有人可以在这个 Net 类中编写一个简单的函数并解决这个问题?
class Net(nn.Module):
def __init__(self):
super(Net, self).__init__()
self.conv1 = nn.Conv2d(3,6,5)
self.conv2 = nn.Conv2d(6,16,5)
# HERE , the input size is 16*5*5, but I don't know how to get it.
self.fc1 = nn.Linear(16*5*5, 120)
self.fc2 = nn.Linear(120,84)
self.fc3 = nn.Linear(84,10)
def forward(self, x):
x = F.max_pool2d(F.relu(self.conv1(x)),(2,2))
x = F.max_pool2d(F.relu(self.conv2(x)),2)
x = x.view(x.size()[0],-1)
x = F.relu(self.fc1(x))
x = F.relu(self.fc2(x))
x = self.fc3(x)
return x
解决方案
Pytorch 默认没有 Flatten Layer。您可以创建一个如下所示的类。干杯
class Flatten(nn.Module):
def forward(self, input):
return input.view(input.size(0), -1)
class Net(nn.Module):
def __init__(self):
super(Net, self).__init__()
self.flatten = Flatten() ## describing the layer
self.conv1 = nn.Conv2d(3,6,5)
self.conv2 = nn.Conv2d(6,16,5)
# HERE , the input size is 16*5*5, but I don't know how to get it.
self.fc1 = nn.Linear(16*5*5, 120)
self.fc2 = nn.Linear(120,84)
self.fc3 = nn.Linear(84,10)
def forward(self, x):
x = F.max_pool2d(F.relu(self.conv1(x)),(2,2))
x = F.max_pool2d(F.relu(self.conv2(x)),2)
#x = x.view(x.size()[0],-1)
x = self.flatten(x) ### using of flatten layer
x = F.relu(self.fc1(x))
x = F.relu(self.fc2(x))
x = self.fc3(x)
return x
推荐阅读
- python - How to remove space in a value
- linux - 如何找到可执行文件所在的目录,显示出来,不重复?Linux
- c++ - 为什么记忆的解决方案比正常的递归解决方案慢?
- javascript - 通过 SSH 使用 exec 的异步等待功能
- python - 如何使用 BLEU 将假设与参考相匹配?
- react-native - React Native Flatlist 仅更新最后一项
- reporting-services - SSRS manager VS Report builder中的共享数据源
- linq - 如何使两个联合的 LINQ 语句异步?
- regex - 正则表达式匹配并分组到第一个句点和最后一个斜杠
- python - 从网站/selenium /python 中获取列表