旨在学习非线性方程的简单神经网络无法收敛

问题描述 投票:0回答:1

我有一堆使用求和、乘法和 min(x,0) 或 max(x,0) 得出结果的方程(一个输出,18 个输入)。

我正在尝试让 pytorch 中的神经网络模型学习这些,以便快速生成结果。

我在 Excel 中生成了 30k 个随机 X-Y 对(仅使用 RND()*100-50 作为 X 并计算 Y)。 我用 pandas 上传了这些对,并用 ReLu 编写了一个神经网络(我希望它能够处理非线性)。这是网:

class MyModel(nn.Module):
    def __init__(self, input_size, hidden_size, output_size):
        super().__init__()
        self.flatten = nn.Flatten()  # Flatten input data
        self.hidden_layer = nn.Sequential(
            nn.Linear(input_size, hidden_size),
            nn.Linear(input_size, hidden_size),
            nn.ReLU(),
            nn.BatchNorm1d(hidden_size),
            nn.Linear(input_size, hidden_size),
            nn.Linear(input_size, hidden_size),

            nn.ReLU()
        )
        self.output_layer = nn.Linear(hidden_size, output_size)

    def forward(self, x):
        x = self.flatten(x)
        x = self.hidden_layer(x)
        x = self.hidden_layer(x)
        x = self.hidden_layer(x)
        output = self.output_layer(x)
        return output

输入和隐藏层的大小为 18,输出的大小为 1。

无法收敛,留下相当大的误差。我认为对于神经网络来说,学习这组方程是一项简单的任务,没有噪音或任何东西。我该怎么做才能使这项工作成功?

pytorch neural-network nonlinear-functions
1个回答
0
投票

您的

nn.Sequential
设置没有意义。
nn.Sequential
按列出的顺序运行模型模块。你的:

        self.hidden_layer = nn.Sequential(
            nn.Linear(input_size, hidden_size),
            nn.Linear(input_size, hidden_size),
            nn.ReLU(),
            nn.BatchNorm1d(hidden_size),
            nn.Linear(input_size, hidden_size),
            nn.Linear(input_size, hidden_size),

            nn.ReLU()
        )

具有背靠背的线性层,这是多余的,因为两个线性层的组合仍然是线性层。你们的尺寸不一致。第一层将大小为

input_size
的输入映射到
hidden_size
,但第二层期望输入大小为
input_size
。目前这对您有用,因为您使用相同的大小进行输入和隐藏,但如果情况并非如此,这将引发错误。

你想要这样的东西:

self.hidden_layer = nn.Sequential(
    nn.Linear(input_size, hidden_size),
    nn.ReLU(),
    nn.BatchNorm1d(hidden_size),
    nn.Linear(hidden_size, hidden_size),
    nn.ReLU(),
    nn.BatchNorm1d(hidden_size)
)

该示例有两个线性/relu/batchnorm 块。如果您愿意,可以添加更多。

你的

forward
方法也很奇怪

首先,确保

nn.Flatten
正在执行您期望的操作。检查输入/输出形状以确定。

其次,将同一块图层涂抹三次。如果您想要更多层,您应该将它们添加到

nn.Sequential
块,而不是通过相同层传递不同的激活 3 次。

© www.soinside.com 2019 - 2024. All rights reserved.