-
Notifications
You must be signed in to change notification settings - Fork 1.4k
/
__init__.py
64 lines (53 loc) · 2.35 KB
/
__init__.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
import numpy
import chainer
# import classes and functions
from chainer.initializers.constant import Constant
from chainer.initializers.constant import Identity # NOQA
from chainer.initializers.constant import NaN # NOQA
from chainer.initializers.constant import One # NOQA
from chainer.initializers.constant import Zero # NOQA
from chainer.initializers.normal import GlorotNormal # NOQA
from chainer.initializers.normal import HeNormal # NOQA
from chainer.initializers.normal import LeCunNormal
from chainer.initializers.normal import Normal # NOQA
from chainer.initializers.orthogonal import Orthogonal # NOQA
from chainer.initializers.uniform import GlorotUniform # NOQA
from chainer.initializers.uniform import HeUniform # NOQA
from chainer.initializers.uniform import LeCunUniform # NOQA
from chainer.initializers.uniform import Uniform # NOQA
def generate_array(initializer, shape, xp, dtype=None):
"""Return initialized array.
The algorithms used to make the new values depend on the
concrete derived classes. If the initializer has the ``dtype`` attribute,
it is used to construct the array. Otherwise, ``chainer.config.dtype`` is
used instead. See :ref:`configuration` for the dtype config.
Args:
initializer: A callable object that takes :ref:`ndarray` and edits its
value.
shape (tuple): Shape of a return array.
xp (module): :mod:`cupy` or :mod:`numpy`.
dtype: Dtype specifier. If omitted, ``initializer.dtype`` is used.
Returns:
:ref:`ndarray`: An initialized array.
"""
dtype_attr = getattr(initializer, 'dtype', None)
if dtype is not None and dtype_attr is not None \
and numpy.dtype(dtype) != numpy.dtype(dtype_attr):
raise ValueError(
'dtype mismatch: {} != {}'.format(dtype, dtype_attr))
if dtype is None:
dtype = dtype_attr
dtype = chainer.get_dtype(dtype)
array = xp.empty(shape, dtype=dtype)
initializer(array)
return array
def _get_initializer(initializer):
if initializer is None:
return LeCunNormal()
if numpy.isscalar(initializer):
return Constant(initializer)
if isinstance(initializer, numpy.ndarray):
return Constant(initializer)
if not callable(initializer):
raise TypeError('invalid type of initializer: %s' % type(initializer))
return initializer