Sure, here's an implementation of Kernel PCA from scratch in Python:
import numpy as np
class KernelPCA:
def __init__(self, n_components=None, kernel='rbf', gamma=None):
self.n_components = n_components
self.kernel = kernel
if self.kernel == 'rbf':
self.gamma = gamma if gamma is not None else 1/self.n_features
def fit_transform(self, X):
self.X = X
self.n_samples, self.n_features = X.shape
# Compute the Kernel matrix
K = self._compute_kernel_matrix(X)
# Center the data in feature space
K_centered = K - 1/self.n_samples * np.dot(K, np.ones((self.n_samples, self.n_samples))) - \
1/self.n_samples * np.dot(np.ones((self.n_samples, self.n_samples)), K) + \
1/self.n_samples**2 * np.dot(np.ones((self.n_samples, self.n_samples)), np.dot(K, np.ones((self.n_samples, self.n_samples))))
# Compute the eigenvalues and eigenvectors of the centered Kernel matrix
eigenvalues, eigenvectors = np.linalg.eigh(K_centered)
# Sort the eigenvalues in decreasing order and get the corresponding eigenvectors
idxs = np.argsort(eigenvalues)[::-1]
eigenvalues = eigenvalues[idxs]
eigenvectors = eigenvectors[:, idxs]
# Normalize the eigenvectors by the square root of their respective eigenvalues
components = []
for i in range(self.n_components):
components.append(eigenvectors[:,i] / np.sqrt(np.abs(eigenvalues[i])))
# Return the projected data in feature space
return np.column_stack(components)
def _compute_kernel_matrix(self, X):
if self.kernel == 'rbf':
return self._rbf_kernel(X, X, gamma=self.gamma)
def _rbf_kernel(self, X1, X2, gamma):
dist_matrix = np.square(np.linalg.norm(X1[:,np.newaxis] - X2, axis=2))
return np.exp(-gamma * dist_matrix)
The KernelPCA class takes two arguments - n_components (number of principal components) and kernel (type of kernel to be used). For the rbf kernel, we also have the option to set the gamma parameter.
We have implemented only the radial basis function (RBF) kernel. We can add other kernels like linear, polynomial, sigmoid, etc. in the _compute_kernel_matrix method.
First, we compute the Kernel matrix using the _compute_kernel_matrix method. We then center the data in feature space using the formula for centering a Kernel matrix.
Next, we compute the eigenvalues and eigenvectors of the centered Kernel matrix. We sort the eigenvalues in decreasing order and get the corresponding eigenvectors. We then normalize the eigenvectors by the square root of their respective eigenvalues to get the principal components.
Finally, we return the projected data in feature space.
To test this implementation, we can use a 2-dimensional dataset and apply Kernel PCA to it with 1 principal component. Here's an example:
import matplotlib.pyplot as plt
from sklearn.datasets import make_circles
X, _ = make_circles(n_samples=1000, noise=0.1, factor=0.5, random_state=42)
kpca = KernelPCA(n_components=1, kernel='rbf', gamma=10)
X_transformed = kpca.fit_transform(X)
plt.scatter(X[:,0], X[:,1])
plt.scatter(X_transformed, np.zeros(X_transformed.shape), c='r')
plt.show()
This will generate a random dataset of 1000 samples in the shape of circles with some noise, and apply Kernel PCA with the RBF kernel and gamma=10 to get 1 principal component. We then plot the original data points as well as the transformed data points on the x-axis only.