python - CNN 时如何检查图像大小?
问题描述
我正在尝试使用 PyTorch 对 CNN 中的猫和狗进行分类。虽然我做了一些图层和处理图像,但我发现最终处理的特征图大小与计算的大小不匹配。因此,我尝试在 CNN 过程中使用打印形状逐步检查特征图大小,但它不起作用。我听说 tensorflow 可以逐步检查张量大小,但我该怎么做呢?
我想要的是:
def __init__(self):
super(CNN, self).__init__()
conv1 = nn.Conv2d(1, 16, 3, 1, 1)
conv1_1 = nn.Conv2d(16, 16, 3, 1, 1)
pool1 = nn.MaxPool2d(2)
conv2 = nn.Conv2d(16, 32, 3, 1, 1)
conv2_1 = nn.Conv2d(32, 32, 3, 1, 1)
pool2 = nn.MaxPool2d(2)
conv3 = nn.Conv2d(32, 64, 3, 1, 1)
conv3_1 = nn.Conv2d(64, 64, 3, 1, 1)
conv3_2 = nn.Conv2d(64, 64, 3, 1, 1)
pool3 = nn.MaxPool2d(2)
self.conv_module = nn.Sequential(
conv1,
nn.ReLU(),
conv1_1,
nn.ReLU(),
pool1,
# check first result size
conv2,
nn.ReLU(),
conv2_1,
nn.ReLU(),
pool2,
# check second result size
conv3,
nn.ReLU(),
conv3_1,
nn.ReLU(),
conv3_2,
nn.ReLU(),
pool3,
# check third result size
pool4,
# check fourth result size
pool5
# check fifth result size
)
如果有任何其他方法可以在每一步检查特征大小,请提供一些建议。提前致谢。
解决方案
为此,您不应该使用nn.Sequential
. 只需初始化您的图层__init__()
并在 forward 函数中调用它们。在 forward 函数中,您可以打印出形状。例如像这样:
class CNN(nn.Module):
def __init__(self):
super(CNN, self).__init__()
self.conv1 = nn.Conv2d(...)
self.maxpool1 = nn.MaxPool2d()
self.conv2 = nn.Conv2d(...)
self.maxpool2 = nn.MaxPool2d()
def forward(self, x):
x = self.conv1(x)
x = F.relu(x)
x = self.maxpool1(x)
print(x.size())
x = self.conv2(x)
x = F.relu(x)
x = self.maxpool2(x)
print(x.size())
希望这就是你要找的!
推荐阅读
- javascript - JavaScript - 带有十进制值的正则表达式
- c - 如何通过放入 scanf 的数字数量来定义数组的限制?
- python - 使用 pd.isin() 检查一列中的值是否在另一列的列表中
- charts - 如何在 Apex 图表中同时使用渐变和单色?
- python - 如何向现有字典添加新键并将前一个键作为值附加到在 for 循环中创建的新键:python
- regex - 如何在 google 表格中解析此 URL 以仅显示价格?
- flutter - 像在android启动器中一样在flutter中创建一个文件夹
- swiftui - 如何在 SwiftUI 中隐藏从子视图中的 tabItem 导航的 TabView?
- sql - 在 bigquery 中将罗马数字转换为阿拉伯数字的最佳方法是什么?
- machine-learning - 为什么网络架构的差异会导致名称分类的巨大差异