TECHFIELD NOTE
PCAで次元削減した散布図に、分類ごとの信頼楕円を描く
matplotlib/seabornの散布図に、クラスごとの共分散楕円を重ねる方法のメモ。
4分で読める
2023年1月にQiitaへ投稿した記事を、文体を整えて移行したものです。
PCAやNMDSで次元を削減した分類データを散布図にするとき、クラスごとの分布の広がりを楕円で示したい場面があります。実装例を見つけにくかったので、当時の自分用のメモを整理して残しておきます。
楕円を描く関数
matplotlibの公式サンプルにある confidence_ellipse を利用します。入力の2系列から共分散を求め、標準偏差の何倍の範囲を囲むかを n_std で指定します。
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.patches import Ellipse
import matplotlib.transforms as transforms
# https://github.com/matplotlib/matplotlib/blob/main/examples/statistics/confidence_ellipse.py
def confidence_ellipse(x, y, ax, n_std=3.0, facecolor='none', **kwargs):
"""
Create a plot of the covariance confidence ellipse of *x* and *y*.
"""
if x.size != y.size:
raise ValueError("x and y must be the same size")
cov = np.cov(x, y)
pearson = cov[0, 1] / np.sqrt(cov[0, 0] * cov[1, 1])
ell_radius_x = np.sqrt(1 + pearson)
ell_radius_y = np.sqrt(1 - pearson)
ellipse = Ellipse(
(0, 0),
width=ell_radius_x * 2,
height=ell_radius_y * 2,
facecolor=facecolor,
**kwargs,
)
scale_x = np.sqrt(cov[0, 0]) * n_std
mean_x = np.mean(x)
scale_y = np.sqrt(cov[1, 1]) * n_std
mean_y = np.mean(y)
transf = (
transforms.Affine2D()
.rotate_deg(45)
.scale(scale_x, scale_y)
.translate(mean_x, mean_y)
)
ellipse.set_transform(transf + ax.transData)
return ax.add_patch(ellipse)
irisデータでの使用例
irisデータを標準化してPCAで2次元に落とし、seabornで散布図を描いたあと、品種ごとに楕円を重ねます。
from sklearn.datasets import load_iris
import seaborn as sns
import pandas as pd
from sklearn.decomposition import PCA
# データの読み込みと標準化
iris = load_iris()
df = pd.DataFrame(iris.data, columns=iris.feature_names)
df = df.apply(lambda x: (x - x.mean()) / x.std(), axis=0)
# PCAで2次元へ
n_components = 2
pca = PCA(n_components=n_components)
pca.fit(df)
feature = pca.transform(df)
feature_df = pd.DataFrame(
feature, columns=[f"PC{i + 1}" for i in range(n_components)]
)
# 目的変数の追加
feature_df["label"] = iris.target
feature_df["label"] = feature_df["label"].map(
{i: name for i, name in enumerate(iris.target_names)}
)
colors = {"setosa": "blue", "virginica": "orange", "versicolor": "green"}
fig, ax = plt.subplots()
sns.scatterplot(
data=feature_df, x="PC1", y="PC2", hue="label", palette=colors, ax=ax
)
# クラスごとの楕円を追加
for name, color in colors.items():
sub = feature_df[feature_df["label"] == name]
confidence_ellipse(sub["PC1"].values, sub["PC2"].values, ax, edgecolor=color)
plt.show()
これで、クラスごとの分布の傾きと広がりが一目で比較できる図になります。