gradient.py 643 Bytes
Newer Older
Richard Vogl's avatar
Richard Vogl committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24

import theano

import lasagne
from lasagne.layers.base import Layer


__all__ = [
    "GradientClipLayer",
]

class GradientClipLayer(Layer):
    """
    Apply gradient clipping to output layer
    """
    def __init__(self, incoming, grad_clipping, nonlinearity=lasagne.nonlinearities.identity, **kwargs):
        super(GradientClipLayer, self).__init__(incoming, **kwargs)

        self.grad_clipping = grad_clipping
        self.nonlinearity = nonlinearity

    def get_output_for(self, input, **kwargs):
        clipped = theano.gradient.grad_clip(input, -self.grad_clipping, self.grad_clipping)
        return self.nonlinearity(clipped)