python - PyTorch 逐元素过滤层

标签 python neural-network pytorch conv-neural-network

你好,我想添加逐元素乘法层来将输入复制到多 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/

相关文章:

python - 在 Jetson Nano Ubuntu 18 上安装 PyTorch

python - 在序列化器中添加一个额外的字段,但它不在模型中

java - 从哪里开始使用神经网络进行手写识别?

matlab - 如何在Matlab中加速代码?

image-processing - pytorch 仿射网格 : what is the theta input?

python - 列/行切片 torch 稀疏张量

python - 带有 HiddenInput 的 Django 的 ModelForm 返回无效

Python,条件问题

python - 为 csv 中的列创建不同的元组值并计算第三列的平均值

python - 具有加州住房数据的神经网络