Skip to content

Instantly share code, notes, and snippets.

@andersx
Last active October 18, 2018 09:19
Show Gist options
  • Save andersx/731d87b143c1ffa5958066c92d74b350 to your computer and use it in GitHub Desktop.
Save andersx/731d87b143c1ffa5958066c92d74b350 to your computer and use it in GitHub Desktop.
Kernel PCA for QML kernels (ndarray)
import numpy as np
import scipy
def kpca(K, n=2, centering=True):
assert K.shape[0] == K.shape[1], "Square matrix required for Kernel PCA."
assert np.allclose(K, K.T, atol=1e-8), "Symmetric matrix required for Kernel PCA."
# First center kernel.
K_centered = None
if (centering):
z = K.shape[0]
G = np.ones((z,z))
G /= z
K_centered = K - np.dot(G, K) - np.dot(K, G) + np.dot(np.dot(G, K), G)
else:
K_centered = K
(w, X) = scipy.linalg.eig(K_centered)
pca = np.transpose(X[:,:n])
print(pca)
return pca
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment