【问题标题】:pytorch: How to implement one link per neuron?pytorch:如何实现每个神经元一个链接?
【发布时间】:2020-10-07 07:38:16
【问题描述】:
例如,我想要一个具有以下结构的标准前馈神经网络:
- n 个输入神经元
- 第二层有n个神经元
- 第三层2个神经元
- 第四层有n个神经元
在哪里
- 第一层的第 i 个神经元精确地连接到第二层的第 i 个神经元(不知道怎么做)
- 第二层和第三层是全连接的,第三层和第四层也是如此(我知道怎么做 - 使用 nn.Linear)
- 损失函数是前两层之间权重(向量)的 MSE + L1 范数(取决于我能否做到这一点的问题的解决方案)
动机:我想实现一个自动编码器并尝试实现一些稀疏性(这就是输入乘以单个权重(从第一层到第二层)的原因)。
【问题讨论】:
标签:
neural-network
pytorch
feed-forward
【解决方案1】:
可以实现自定义层,类似于nn.Linear:
import math
import torch
from torch import nn
class ElementWiseLinear(nn.Module):
__constants__ = ['n_features']
n_features: int
weight: torch.Tensor
def __init__(self, n_features: int, bias: bool = True) -> None:
super(ElementWiseLinear, self).__init__()
self.n_features = n_features
self.weight = nn.Parameter(torch.Tensor(1, n_features))
if bias:
self.bias = nn.Parameter(torch.Tensor(n_features))
else:
self.register_parameter('bias', None)
self.reset_parameters()
def reset_parameters(self) -> None:
nn.init.kaiming_uniform_(self.weight, a=math.sqrt(5))
if self.bias is not None:
fan_in, _ = nn.init._calculate_fan_in_and_fan_out(self.weight)
bound = 1 / math.sqrt(fan_in)
nn.init.uniform_(self.bias, -bound, bound)
def forward(self, input: torch.Tensor) -> torch.Tensor:
output = torch.mul(input, self.weight)
if self.bias is not None:
output += self.bias
return output
def extra_repr(self) -> str:
return 'in_features={}, out_features={}, bias={}'.format(
self.n_features, self.n_features, self.bias is not None
)
并像这样使用它:
x = torch.rand(3)
layer = ElementWiseLinear(3, bias=False)
output = layer(x)
当然,你让事情变得更简单:)