将 nn.Linear 转换为 nn.Conv1d

发布于 2025-01-15 10:12:12 字数 446 浏览 0 评论 0原文

我想要输出模型的格式不支持 nn.Linear,因此我想更改它以执行完全相同的操作,但使用 nn.Conv1d。

我的输入是形状 (N, A, B),我想要一个线性层将其转换为形状 (N, A, C) 的输出。以前,我使用层 nn.Linear(B, C) 来执行此操作。我可以通过执行以下操作来生成具有正确尺寸的工作代码

t1 = t1.transpose(1,2)
conv = nn.Conv1d(
            in_channels=B,
            out_channels=C,
            kernel_size=1
        )
t2 = conv(t1)
t2 = t2.transpose(1,2)

:这在功能上等同于执行 t2 = nn.Linear(B,C)(t1)? 如果是这样,是否有更好/更简洁的方法?

The format I want to output my model to doesn't support nn.Linear, so I'd like to change it to do the exact same thing but with nn.Conv1d.

My input is of shape (N, A, B) and I'd like to have a linear layer that transforms that into an output of shape (N, A, C). Previously, I was doing this with the layer nn.Linear(B, C). I'm able to produce working code that has the correct dimensions by doing

t1 = t1.transpose(1,2)
conv = nn.Conv1d(
            in_channels=B,
            out_channels=C,
            kernel_size=1
        )
t2 = conv(t1)
t2 = t2.transpose(1,2)

Is this functionally equivalent to doing t2 = nn.Linear(B,C)(t1)?
If so, is there a better/less verbose way of doing it?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

若有似无的小暗淡 2025-01-22 10:12:12

是的,这本质上是在做同样的事情。
您可以通过执行以下操作来添加尾随虚拟维度,而不是转置。

t1 = t1.unsqueeze(-1)
...
t2 = t2.squeeze(-1)

这具有不必重新排序数据的优点,但效果可能可以忽略不计。

Yes this is essentially doing the same thing.
Instead of transposing you could just add a trailing dummy dimension by doing

t1 = t1.unsqueeze(-1)
...
t2 = t2.squeeze(-1)

This has the advantage that the data doesn't have to be reordered, but the effect is probably negligible.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文