Trainable Hamming Window

Hi,

I would like to train a network with the hamming window link parametrized with the coefficients alpha and beta.
However, I can’t do

def __init__(self):
    super().__init__()
    self.alpha = torch.nn.Parameter(1.0)
    self.beta = torch.nn.Parameter(1.0)

def forward(self, data):
    hw = torch.hamming_window(10, True, self.alpha, self.beta)
    return hw * data

with alpha, beta beign torch.nn.Parameter since torch.hamming_window expects float and not Parameters.
How would I do this?

Hi Lukas!

Yes, you’re right – you can’t use Parameters for alpha and beta.
Well, that’s annoying (and seemingly unnecessary).

As a work-around, you can scale your hw with Parameters after
creating it:

>>> import torch
>>> torch.__version__
'1.11.0'
>>> alpha = torch.nn.Parameter (torch.tensor ([1.0]))
>>> beta = torch.nn.Parameter (torch.tensor ([1.0]))
>>> hw_tmp = torch.hamming_window (10, True, 0.0, -1.0)
>>> hw = alpha - beta * hw_tmp
>>> hw
tensor([0.0000, 0.1910, 0.6910, 1.3090, 1.8090, 2.0000, 1.8090, 1.3090, 0.6910,
        0.1910], grad_fn=<SubBackward0>)

Best.

K. Frank

1 Like

Hi Frank,

Thank you for your reply! That indeed did the trick.
In case someone has a similar problem, here´s how I implemented the hamming window as a trainable layer for 3D data:

class HammingWindowParametrized(torch.nn.Module):
    def __init__(self):
        super().__init__()
        self.alpha = torch.nn.Parameter(torch.tensor(0.54))
        self.beta = torch.nn.Parameter(torch.tensor(0.46))
    
    def hamming_function(self, data):
        window_0 = self.alpha - self.beta * torch.cos(torch.pi * 2 * torch.linspace(0, data.shape[0], data.shape[0]) / data.shape[0])
        data = data * window_0.reshape((-1, 1, 1))
        window_1 = self.alpha - self.beta * torch.cos(torch.pi * 2 * torch.linspace(0, data.shape[1], data.shape[1]) / data.shape[1])
        data = data * window_1.reshape((1, -1, 1))
        window_2 = self.alpha - self.beta * torch.cos(torch.pi * 2 * torch.linspace(0, data.shape[2], data.shape[2]) / data.shape[2])
        data = data * window_2.reshape((1, 1, -1))
        return data
    
    def forward(self, data):
        shape = data.shape
        data = data.squeeze()
        data = self.hamming_function(data)
        data = data.reshape(shape)
        return data