neural_filter_2CD.py 2.26 KB
Newer Older
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
"""
NeuralFilter2CD
***************

This module implements a trainable critically damped  all-pole second order filter with real poles using pyTorch


Copyright (c) 2018 Idiap Research Institute, http://www.idiap.ch/

Written by Francois Marelli <Francois.Marelli@idiap.ch>

This file is part of neural_filters.

neural_filters is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License version 3 as
published by the Free Software Foundation.

neural_filters is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with neural_filters. If not, see <http://www.gnu.org/licenses/>.

"""

Francois Marelli's avatar
Francois Marelli committed
28
from . import NeuralFilter
29 30 31 32

import torch
import numpy as np

33 34

class NeuralFilter2CD(torch.nn.Module):
35 36 37 38 39 40 41 42 43 44 45
    """
        A trainable second-order critically damped all-pole filter :math:`\\frac{1}{(1 - P z^{-1})^{2}}`

        * **hidden_size** (int) - the size of data vector
        """

    def __init__(self, hidden_size):
        super(NeuralFilter2CD, self).__init__()

        self.hidden_size = hidden_size

Francois Marelli's avatar
Francois Marelli committed
46
        self.cell = NeuralFilter(self.hidden_size)
47

Francois Marelli's avatar
Francois Marelli committed
48 49 50
    def reset_parameters(self, init=None):
        self.cell.reset_parameters(init)

51 52 53 54
    def __repr__(self):
        s = '{name}({hidden_size})'
        return s.format(name=self.__class__.__name__, **self.__dict__)

55
    def forward(self, input_var, hx=None):
56
        if hx is None:
57 58 59
            hx = torch.autograd.Variable(input_var.data.new(input_var.size(1),
                                                            self.hidden_size
                                                            ).zero_(), requires_grad=False)
60

61 62
        inter, inter_hidden = self.cell(input_var, hx)
        output, hidden = self.cell(inter)
63 64 65 66 67 68 69 70 71 72 73 74 75 76

        return output, hidden

    @property
    def denominator(self):
        first = self.cell.denominator
        denom = np.zeros((first.shape[0], 3))
        for i in range(self.hidden_size):
            denom[i] = np.polymul(first[i], first[i])
        return denom

    @property
    def gradients(self):
        return self.cell.gradients