https://pytorch.org/docs/stable/generated/torch.nn.Linear.html?highlight=linear#torch.nn.Linear

功能

对输入nn.Linear - 图1进行线性变换nn.Linear - 图2

源码

  1. [torch/nn/modules/linear.py]
  2. class Linear(Module):
  3. r"""Applies a linear transformation to the incoming data: :math:`y = xA^T + b`
  4. Args:
  5. in_features: size of each input sample
  6. out_features: size of each output sample
  7. bias: If set to False, the layer will not learn an additive bias.
  8. Default: True
  9. Examples::
  10. >>> m = nn.Linear(20, 30)
  11. >>> input = torch.randn(128, 20)
  12. >>> output = m(input)
  13. >>> print(output.size())
  14. torch.Size([128, 30])
  15. """
  16. # https://discuss.pytorch.org/t/why-do-we-use-constants-or-final/70331
  17. __constants__ = ['in_features', 'out_features']
  18. in_features: int
  19. out_features: int
  20. weight: Tensor
  21. def __init__(self, in_features: int, out_features: int, bias: bool = True) -> None:
  22. super(Linear, self).__init__()
  23. self.in_features = in_features
  24. self.out_features = out_features
  25. self.weight = Parameter(torch.Tensor(out_features, in_features))
  26. if bias:
  27. self.bias = Parameter(torch.Tensor(out_features))
  28. else:
  29. self.register_parameter('bias', None)
  30. self.reset_parameters()
  31. def reset_parameters(self) -> None:
  32. # 初始化 Delving Deep into Rectifiers: Surpassing Human-Level Performance on ImageNet Classification
  33. init.kaiming_uniform_(self.weight, a=math.sqrt(5))
  34. if self.bias is not None:
  35. fan_in, _ = init._calculate_fan_in_and_fan_out(self.weight)
  36. bound = 1 / math.sqrt(fan_in)
  37. init.uniform_(self.bias, -bound, bound)
  38. def forward(self, input: Tensor) -> Tensor:
  39. return F.linear(input, self.weight, self.bias)
  40. def extra_repr(self) -> str:
  41. return 'in_features={}, out_features={}, bias={}'.format(
  42. self.in_features, self.out_features, self.bias is not None
  43. )