Created
February 6, 2018 19:39
-
-
Save vvanirudh/2683295a198a688ef3c49650cada0114 to your computer and use it in GitHub Desktop.
Random fourier features using both sines and cosines embedding for Gaussian kernel
This file contains hidden or 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
from sklearn.base import BaseEstimator | |
from sklearn.exceptions import NotFittedError | |
import numpy as np | |
class IRFF(BaseEstimator): | |
''' | |
Random fourier features using the improved embedding | |
https://www.cs.cmu.edu/~schneide/DougalRandomFeatures_UAI2015.pdf | |
''' | |
def __init__(self, gamma=1., n_components=100): | |
self.gamma = gamma | |
self.n_components = n_components | |
self.fitted = False | |
def fit(self, X, y=None): | |
inp = np.array(X) | |
d = inp.shape[1] | |
D = int(self.n_components/2) | |
self.w = np.sqrt(2*self.gamma)*np.random.normal(size=(D, d)) | |
self.fitted = True | |
return self | |
def transform(self, X): | |
inp = np.array(X) | |
if not self.fitted: | |
raise NotFittedError('Fourier feature should be fitted before transforming') | |
dotproduct = inp.dot(self.w.T) | |
Z = np.sqrt(2 / self.n_components) * np.concatenate([np.cos(dotproduct), np.sin(dotproduct)], axis=1) | |
return Z | |
def fit_transform(self, X): | |
self.fit(X) | |
return self.transform(X) | |
def compute_kernel(self, X): | |
if not self.fitted: | |
raise NotFittedError('Fourier feature should be fitted before computing kernel') | |
Z = self.transform(X) | |
return Z.dot(Z.T) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment