Flatten layer of PyTorch build by sequential container(通过顺序容器扁平化 PyTorch 构建层)
问题描述
我正在尝试通过 PyTorch 的顺序容器构建一个 cnn,我的问题是我不知道如何展平图层.
I am trying to build a cnn by sequential container of PyTorch, my problem is I cannot figure out how to flatten the layer.
main = nn.Sequential()
self._conv_block(main, 'conv_0', 3, 6, 5)
main.add_module('max_pool_0_2_2', nn.MaxPool2d(2,2))
self._conv_block(main, 'conv_1', 6, 16, 3)
main.add_module('max_pool_1_2_2', nn.MaxPool2d(2,2))
main.add_module('flatten', make_it_flatten)
我应该在make_it_flatten"中放什么?我试图压平主要但它不起作用,主要不存在调用视图的东西
What should I put in the "make_it_flatten"? I tried to flatten the main but it do not work, main do not exist something call view
main = main.view(-1, 16*3*3)
推荐答案
这可能不是您想要的,但您可以简单地创建自己的 nn.Module 来扁平化任何输入,然后您可以将其添加到 nn.Sequential() 对象:
This might not be exactly what you are looking for, but you can simply create your own nn.Module that flattens any input, which you can then add to the nn.Sequential() object:
class Flatten(nn.Module):
def forward(self, x):
return x.view(x.size()[0], -1)
x.size()[0] 将选择批量暗淡,而 -1 将计算所有剩余的暗淡以适应元素的数量,从而展平任何张量/变量.
The x.size()[0] will select the batch dim, and -1 will compute all remaining dims to fit the number of elements, thereby flattening any tensor/Variable.
并在 nn.Sequential 中使用它:
main = nn.Sequential()
self._conv_block(main, 'conv_0', 3, 6, 5)
main.add_module('max_pool_0_2_2', nn.MaxPool2d(2,2))
self._conv_block(main, 'conv_1', 6, 16, 3)
main.add_module('max_pool_1_2_2', nn.MaxPool2d(2,2))
main.add_module('flatten', Flatten())
这篇关于通过顺序容器扁平化 PyTorch 构建层的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:通过顺序容器扁平化 PyTorch 构建层
基础教程推荐
- PANDA VALUE_COUNTS包含GROUP BY之前的所有值 2022-01-01
- 使用大型矩阵时禁止 Pycharm 输出中的自动换行符 2022-01-01
- 包装空间模型 2022-01-01
- PermissionError: pip 从 8.1.1 升级到 8.1.2 2022-01-01
- 修改列表中的数据帧不起作用 2022-01-01
- 无法导入 Pytorch [WinError 126] 找不到指定的模块 2022-01-01
- Plotly:如何设置绘图图形的样式,使其不显示缺失日期的间隙? 2022-01-01
- 在同一图形上绘制Bokeh的烛台和音量条 2022-01-01
- 求两个直方图的卷积 2022-01-01
- 在Python中从Azure BLOB存储中读取文件 2022-01-01
