gpt4 book ai didi

python - PyTorch 逐元素过滤层

转载 作者:太空宇宙 更新时间:2023-11-04 00:12:37 24 4
gpt4 key购买 nike

你好,我想添加逐元素乘法层来将输入复制到多 channel ,如下图所示。 (因此,输入大小 M x N 和乘法滤波器大小 M x N 相同),如图所示

我想给过滤器添加自定义的初始化值,也想让它们在训练时获得梯度。但是,我在 PyTorch 中找不到按元素过滤层。我能做到吗?或者这在 PyTorch 中是不可能的?

最佳答案

在 pytorch 中,您始终可以通过使它们成为 nn.Module 的子类来实现您自己的层。您还可以使用 nn.Parameter 在层中设置可训练参数。 .
这种层的可能实现可能看起来像

import torch
from torch import nn

class TrainableEltwiseLayer(nn.Module)
def __init__(self, n, h, w):
super(TrainableEltwiseLayer, self).__init__()
self.weights = nn.Parameter(torch.Tensor(1, n, h, w)) # define the trainable parameter

def forward(self, x):
# assuming x is of size b-n-h-w
return x * self.weights # element-wise multiplication

您仍然需要担心初始化权重。查看nn.init关于初始化权重的方法。通常,在训练之前和加载任何存储的模型之前初始化所有网络的权重(因此部分训练的模型可以覆盖随机初始化)。有点像

model = mymodel(*args, **kwargs)  # instantiate a model
for m in model.modules():
if isinstance(m, nn.Conv2d):
nn.init.normal_(m.weights.data) # init for conv layers
if isinstance(m, TrainableEltwiseLayer):
nn.init.constant_(m.weights.data, 1) # init your weights here...

关于python - PyTorch 逐元素过滤层,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51980654/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com