Created
November 27, 2015 19:45
-
-
Save Strateus/b701131daa80f44d8960 to your computer and use it in GitHub Desktop.
L2 Normalize layer for Chainer
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class L2Normalize(Function): | |
def forward(self, inputs): | |
xp = cuda.get_array_module(*inputs) | |
x, = inputs | |
if type(x) is cuda.ndarray: | |
Xnp = cuda.cupy.asnumpy(x) | |
self._norm = xp.asarray(xp.expand_dims(np.linalg.norm(Xnp, ord=2, axis=1), axis=1), dtype=xp.float32) | |
else: | |
self._norm = xp.expand_dims(np.linalg.norm(x, ord=2, axis=1), axis=1) | |
z = xp.divide(x, self._norm) | |
return z, | |
def backward(self, inputs, grad_outputs): | |
#xp = cuda.get_array_module(*inputs) | |
x, = inputs | |
gz, = grad_outputs | |
gx = None # how to compute gradient here? | |
return gx, | |
def l2_normalize(X): | |
return L2Normalize()(X) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment