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 2.2 kB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  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 ..functional import linear
  10. from ..tensor 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. Examples:
  24. .. testcode::
  25. import numpy as np
  26. import megengine as mge
  27. import megengine.module as M
  28. m = M.Linear(in_features=3, out_features=1)
  29. inp = mge.tensor(np.arange(0, 6).astype("float32").reshape(2, 3))
  30. oup = m(inp)
  31. print(oup.shape)
  32. Outputs:
  33. .. testoutput::
  34. (2, 1)
  35. """
  36. def __init__(
  37. self, in_features: int, out_features: int, bias: bool = True, **kwargs
  38. ):
  39. super().__init__(**kwargs)
  40. self.out_features = out_features
  41. self.in_features = in_features
  42. w_shape = (out_features, in_features)
  43. self.weight = Parameter(np.zeros(w_shape, dtype=np.float32))
  44. self.bias = None
  45. if bias:
  46. b_shape = (out_features,)
  47. self.bias = Parameter(np.zeros(b_shape, dtype=np.float32))
  48. self.reset_parameters()
  49. def _get_fanin(self):
  50. return self.in_features
  51. def reset_parameters(self) -> None:
  52. fanin = self._get_fanin()
  53. std = np.sqrt(1 / fanin)
  54. init.normal_(self.weight, 0.0, std)
  55. if self.bias is not None:
  56. init.zeros_(self.bias)
  57. def _calc_linear(self, x, weight, bias):
  58. return linear(x, weight, bias)
  59. def forward(self, x):
  60. return self._calc_linear(x, self.weight, self.bias)

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