如何在Pytorch的`nn.Sequential`中展平输入

如何在nn.Sequential中展平输入

Model = nn.Sequential(x.view(x.shape[0],-1),                     nn.Linear(784,256),                     nn.ReLU(),                     nn.Linear(256,128),                     nn.ReLU(),                     nn.Linear(128,64),                     nn.ReLU(),                     nn.Linear(64,10),                     nn.LogSoftmax(dim=1))

回答:

你可以创建一个新的模块/类如下,并在Sequential中像使用其他模块一样使用它(调用Flatten())。

class Flatten(torch.nn.Module):    def forward(self, x):        batch_size = x.shape[0]        return x.view(batch_size, -1)

参考:https://discuss.pytorch.org/t/flatten-layer-of-pytorch-build-by-sequential-container/5983

编辑:Flatten现在是torch的一部分。参见https://pytorch.org/docs/stable/nn.html?highlight=flatten#torch.nn.Flatten

Related Posts

L1-L2正则化的不同系数

我想对网络的权重同时应用L1和L2正则化。然而,我找不…

使用scikit-learn的无监督方法将列表分类成不同组别,有没有办法?

我有一系列实例,每个实例都有一份列表,代表它所遵循的不…

f1_score metric in lightgbm

我想使用自定义指标f1_score来训练一个lgb模型…

通过相关系数矩阵进行特征选择

我在测试不同的算法时,如逻辑回归、高斯朴素贝叶斯、随机…

可以将机器学习库用于流式输入和输出吗?

已关闭。此问题需要更加聚焦。目前不接受回答。 想要改进…

在TensorFlow中,queue.dequeue_up_to()方法的用途是什么?

我对这个方法感到非常困惑,特别是当我发现这个令人费解的…

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注