25.2 KernelPCA
In [1]:
from sklearn.datasets import make_circles
X, y = make_circles(n_samples=200, random_state=1, noise=0.2, factor=0.1)In [2]:
import pandas as pd
df = pd.DataFrame(X)
df.columns=['a','b']
df["y"]=y
print(df)a b y 0 -0.923942 -0.549919 0 1 -0.711498 0.935600 0 2 -0.522033 0.938976 0 3 -0.030860 -0.143288 1 4 -0.101950 0.040080 1 .. ... ... .. 195 0.044067 -0.176675 1 196 0.077252 0.335312 1 197 -0.508993 -0.829551 0 198 0.202898 -0.016087 1 199 -0.769211 0.480595 0 [200 rows x 3 columns]
In [5]:
import seaborn as sns
import matplotlib.pyplot as plt
plt.figure(figsize=(6, 3))
sns.scatterplot(data=df,x='a',y='b', hue="y")<Axes: xlabel='a', ylabel='b'>
In [6]:
from sklearn.decomposition import PCA
pca = PCA(n_components=2)
X_pca = pca.fit_transform(X)In [7]:
df = pd.DataFrame(X_pca)
df.columns=["pc1","pc2"]
df['y']=y
print(df.head(5))pc1 pc2 y 0 -0.936050 -0.560885 0 1 -0.731019 0.925676 0 2 -0.541573 0.929997 0 3 -0.045007 -0.149804 1 4 -0.117011 0.033207 1
In [9]:
plt.figure(figsize=(6, 3))
sns.scatterplot(data=df,x='pc1',y='pc2',hue="y")<Axes: xlabel='pc1', ylabel='pc2'>
In [10]:
from sklearn.decomposition import KernelPCA
kpca = KernelPCA(kernel="rbf", fit_inverse_transform=True, gamma=10, n_components=2)
X_kpca = kpca.fit_transform(X)
df = pd.DataFrame(X_kpca)
df.columns=["kpc1","kpc2"]
df['y']=y
print(df.head(5))kpc1 kpc2 y 0 -0.336612 -0.026161 0 1 -0.312302 -0.011878 0 2 -0.348684 -0.013925 0 3 0.567221 -0.194443 1 4 0.614309 -0.230115 1
In [11]:
plt.figure(figsize=(6, 3))
sns.scatterplot(data=df,x='kpc1',y='kpc2', hue="y")<Axes: xlabel='kpc1', ylabel='kpc2'>