Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Create FisherVector class #26

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 27 additions & 0 deletions fisher_vector.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
import torch
import numpy as np

from math import pi
from torch import nn

class FisherVectorLayer(nn.Module):
def __init__(self, gmm):
super(FisherVectorLayer, self).__init__()
self.gmm = gmm

def forward(self, x: torch.Tensor):
B, N, D = x.shape
Q = torch.zeros(B, N, self.gmm.n_components)

for vid in range(B):
Q[vid] = self.gmm.predict_proba(x[vid])
Q_sum = torch.sum(Q, 1).unsqueeze(2) / N # B, K, 1
Q_x = torch.einsum('knb,bnd->bkd', Q.T, x) / N # B, K, D
Q_x_2 = torch.einsum('knb,bnd->bkd', Q.T, x ** 2) / N # B, K, D

d_pi = Q_sum - self.gmm.pi #find weights # B, K
d_mu = Q_x - Q_sum * self.gmm.mu #B, K, D
d_sigma = (- Q_x_2 - Q_sum * self.gmm.mu ** 2 + Q_sum * self.gmm.var + 2 * Q_x * self.gmm.mu) #B, K, D

# Merge derivatives into a vector.
return torch.hstack((d_pi.reshape(B, -1), d_mu.reshape(B, -1), d_sigma.reshape(B, -1)))