You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

linear.py 1.9 kB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. # MegEngine is Licensed under the Apache License, Version 2.0 (the "License")
  2. #
  3. # Copyright (c) 2014-2020 Megvii Inc. All rights reserved.
  4. #
  5. # Unless required by applicable law or agreed to in writing,
  6. # software distributed under the License is distributed on an
  7. # "AS IS" BASIS, WITHOUT ARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  8. import numpy as np
  9. from .. import functional as F
  10. from ..core import Parameter
  11. from . import init
  12. from .module import Module
  13. class Linear(Module):
  14. r"""Applies a linear transformation to the input. For instance, if input
  15. is x, then output y is:
  16. .. math::
  17. y = xW^T + b
  18. where :math:`y_i= \sum_j W_{ij} x_j + b_i`
  19. :param in_features: size of each input sample.
  20. :param out_features: size of each output sample.
  21. :param bias: If set to ``False``, the layer will not learn an additive bias.
  22. Default: ``True``
  23. """
  24. def __init__(
  25. self, in_features: int, out_features: int, bias: bool = True, **kwargs
  26. ):
  27. super().__init__(**kwargs)
  28. self.out_features = out_features
  29. self.in_features = in_features
  30. w_shape = (out_features, in_features)
  31. self.weight = Parameter(np.zeros(w_shape, dtype=np.float32))
  32. self.bias = None
  33. if bias:
  34. b_shape = (out_features,)
  35. self.bias = Parameter(np.zeros(b_shape, dtype=np.float32))
  36. self.reset_parameters()
  37. def _get_fanin(self):
  38. return self.in_features
  39. def reset_parameters(self) -> None:
  40. fanin = self._get_fanin()
  41. std = np.sqrt(1 / fanin)
  42. init.normal_(self.weight, 0.0, std)
  43. if self.bias is not None:
  44. init.zeros_(self.bias)
  45. def _calc_linear(self, x, weight, bias):
  46. return F.linear(x, weight, bias)
  47. def forward(self, x):
  48. return self._calc_linear(x, self.weight, self.bias)

MegEngine 安装包中集成了使用 GPU 运行代码所需的 CUDA 环境,不用区分 CPU 和 GPU 版。 如果想要运行 GPU 程序,请确保机器本身配有 GPU 硬件设备并安装好驱动。 如果你想体验在云端 GPU 算力平台进行深度学习开发的感觉,欢迎访问 MegStudio 平台