|
| 1 | +"""Initializer of parameters.""" |
| 2 | +import numpy as np |
| 3 | + |
| 4 | +class Initializer(object): |
| 5 | + """The base class of an initializer.""" |
| 6 | + def __init__(self, **kwargs): |
| 7 | + self._kwargs = kwargs |
| 8 | + |
| 9 | + def __call__(self, desc, arr): |
| 10 | + """Initialize an array |
| 11 | +
|
| 12 | + Parameters |
| 13 | + ---------- |
| 14 | + desc : str |
| 15 | + Initialization pattern descriptor. |
| 16 | +
|
| 17 | + arr : NDArray |
| 18 | + The array to be initialized. |
| 19 | + """ |
| 20 | + if desc.endswith('weight'): |
| 21 | + self._init_weight(desc, arr) |
| 22 | + elif desc.endswith('bias'): |
| 23 | + self._init_bias(desc, arr) |
| 24 | + elif desc.endswith('gamma'): |
| 25 | + self._init_gamma(desc, arr) |
| 26 | + elif desc.endswith('beta'): |
| 27 | + self._init_beta(desc, arr) |
| 28 | + elif desc.endswith('mean'): |
| 29 | + self._init_mean(desc, arr) |
| 30 | + elif desc.endswith('var'): |
| 31 | + self._init_var(desc, arr) |
| 32 | + else: |
| 33 | + self._init_default(desc, arr) |
| 34 | + |
| 35 | + def _init_bias(self, _, arr): |
| 36 | + arr[:] = 0.0 |
| 37 | + |
| 38 | + def _init_gamma(self, _, arr): |
| 39 | + arr[:] = 1.0 |
| 40 | + |
| 41 | + def _init_beta(self, _, arr): |
| 42 | + arr[:] = 0.0 |
| 43 | + |
| 44 | + def _init_mean(self, _, arr): |
| 45 | + arr[:] = 0.0 |
| 46 | + |
| 47 | + def _init_var(self, _, arr): |
| 48 | + arr[:] = 1.0 |
| 49 | + |
| 50 | + def _init_weight(self, name, arr): |
| 51 | + """Abstract method to Initialize weight.""" |
| 52 | + raise NotImplementedError("Must override it") |
| 53 | + |
| 54 | + def _init_default(self, name, _): |
| 55 | + raise ValueError( |
| 56 | + 'Unknown initialization pattern for %s. ' \ |
| 57 | + 'Default initialization is now limited to '\ |
| 58 | + '"weight", "bias", "gamma" (1.0), and "beta" (0.0).' \ |
| 59 | + 'Please use mx.sym.Variable(init=mx.init.*) to set initialization pattern' % name) |
| 60 | + |
| 61 | + |
| 62 | +class Xavier(Initializer): |
| 63 | + """ "Xavier" initialization for weights |
| 64 | +
|
| 65 | + Parameters |
| 66 | + ---------- |
| 67 | + rnd_type: str, optional |
| 68 | + Random generator type, can be ``'gaussian'`` or ``'uniform'``. |
| 69 | +
|
| 70 | + factor_type: str, optional |
| 71 | + Can be ``'avg'``, ``'in'``, or ``'out'``. |
| 72 | +
|
| 73 | + magnitude: float, optional |
| 74 | + Scale of random number. |
| 75 | + """ |
| 76 | + def __init__(self, rnd_type="uniform", factor_type="avg", magnitude=3): |
| 77 | + super(Xavier, self).__init__(rnd_type=rnd_type, |
| 78 | + factor_type=factor_type, |
| 79 | + magnitude=magnitude) |
| 80 | + self.rnd_type = rnd_type |
| 81 | + self.factor_type = factor_type |
| 82 | + self.magnitude = float(magnitude) |
| 83 | + |
| 84 | + |
| 85 | + def _init_weight(self, name, arr): |
| 86 | + shape = arr.shape |
| 87 | + hw_scale = 1. |
| 88 | + if len(shape) < 2: |
| 89 | + raise ValueError('Xavier initializer cannot be applied to vector {0}. It requires at' |
| 90 | + ' least 2D.'.format(name)) |
| 91 | + if len(shape) > 2: |
| 92 | + hw_scale = np.prod(shape[2:]) |
| 93 | + fan_in, fan_out = shape[1] * hw_scale, shape[0] * hw_scale |
| 94 | + factor = 1. |
| 95 | + if self.factor_type == "avg": |
| 96 | + factor = (fan_in + fan_out) / 2.0 |
| 97 | + elif self.factor_type == "in": |
| 98 | + factor = fan_in |
| 99 | + elif self.factor_type == "out": |
| 100 | + factor = fan_out |
| 101 | + else: |
| 102 | + raise ValueError("Incorrect factor type") |
| 103 | + # Hack for mobilenet, because there is less connectivity |
| 104 | + if "depthwise" in name: |
| 105 | + factor = 3 * 3 |
| 106 | + scale = np.sqrt(self.magnitude / factor) |
| 107 | + if self.rnd_type == "uniform": |
| 108 | + arr[:] = np.random.uniform(-scale, scale, size=arr.shape) |
| 109 | + else: |
| 110 | + raise ValueError("Unknown random type") |
0 commit comments