Matplotlibで信頼楕円をプロットする

PythonPythonBeginner
今すぐ練習

This tutorial is from open-source community. Access the source code

💡 このチュートリアルは英語版からAIによって翻訳されています。原文を確認するには、 ここをクリックしてください

はじめに

この実験では、Python の Matplotlib を使用して2次元データセットの信頼楕円をプロットする方法を示します。信頼楕円は、データセットの共分散をグラフィカルに表したもので、推定された平均と標準偏差の不確定性を示します。楕円はピアソン相関係数を使用してプロットされます。

VMのヒント

VMの起動が完了したら、左上隅をクリックして Notebook タブに切り替え、Jupyter Notebook を開いて練習を行ってください。

場合によっては、Jupyter Notebook の読み込みが完了するまで数秒待つ必要があります。Jupyter Notebook の制限により、操作の検証を自動化することはできません。

学習中に問題が発生した場合は、いつでも Labby に質問してください。セッション終了後にフィードバックを提供していただければ、迅速に問題を解決します。

必要なライブラリをインポートする

最初のステップは、必要なライブラリをインポートすることです。この実験では numpymatplotlib.pyplot が必要です。

import matplotlib.pyplot as plt
import numpy as np

confidence_ellipse 関数を定義する

次に、データセットの x 座標と y 座標、楕円を描画する軸オブジェクト、および標準偏差の数を引数に取る confidence_ellipse 関数を定義します。この関数は、楕円を表す Matplotlib のパッチオブジェクトを返します。

def confidence_ellipse(x, y, ax, n_std=3.0, facecolor='none', **kwargs):
    """
    *x* と *y* の共分散信頼楕円のプロットを作成します。

    パラメータ
    ----------
    x, y : array-like, shape (n, )
        入力データ。

    ax : matplotlib.axes.Axes
        楕円を描画する軸オブジェクト。

    n_std : float
        楕円の半径を決定するための標準偏差の数。

    **kwargs
        `~matplotlib.patches.Ellipse` に転送されます。

    戻り値
    -------
    matplotlib.patches.Ellipse
    """
    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])
    ## この2次元データセットの固有値を取得するための特殊なケースを使用します。
    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)

    ## 分散の平方根から x の標準偏差を計算し、
    ## 与えられた標準偏差の数を掛けます。
    scale_x = np.sqrt(cov[0, 0]) * n_std
    mean_x = np.mean(x)

    ## y の標準偏差を計算します...
    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)

get_correlated_dataset 関数を定義する

また、指定された平均、次元、および相関を持つ2次元データセットを生成する関数が必要です。

def get_correlated_dataset(n, dependency, mu, scale):
    """
    指定された2次元の平均 (mu) と次元 (scale) を持つランダムな2次元データセットを作成します。
    相関はパラメータ 'dependency'(2x2行列)で制御できます。
    """
    latent = np.random.randn(n, 2)
    dependent = latent.dot(dependency)
    scaled = dependent * scale
    scaled_with_offset = scaled + mu
    ## 新しい相関データセットの x と y を返します
    return scaled_with_offset[:, 0], scaled_with_offset[:, 1]

正の相関、負の相関、および弱い相関のプロット

ここで、これらの関数を使用して、正の相関、負の相関、および弱い相関を持つデータセットの信頼楕円をプロットします。

np.random.seed(0)

PARAMETERS = {
    'Positive correlation': [[0.85, 0.35],
                             [0.15, -0.65]],
    'Negative correlation': [[0.9, -0.4],
                             [0.1, -0.6]],
    'Weak correlation': [[1, 0],
                         [0, 1]],
}

mu = 2, 4
scale = 3, 5

fig, axs = plt.subplots(1, 3, figsize=(9, 3))
for ax, (title, dependency) in zip(axs, PARAMETERS.items()):
    x, y = get_correlated_dataset(800, dependency, mu, scale)
    ax.scatter(x, y, s=0.5)

    ax.axvline(c='grey', lw=1)
    ax.axhline(c='grey', lw=1)

    confidence_ellipse(x, y, ax, edgecolor='red')

    ax.scatter(mu[0], mu[1], c='red', s=3)
    ax.set_title(title)

plt.show()

異なる標準偏差の数で信頼楕円をプロットする

また、異なる標準偏差の数で信頼楕円をプロットすることもできます。

fig, ax_nstd = plt.subplots(figsize=(6, 6))

dependency_nstd = [[0.8, 0.75],
                   [-0.2, 0.35]]
mu = 0, 0
scale = 8, 5

ax_nstd.axvline(c='grey', lw=1)
ax_nstd.axhline(c='grey', lw=1)

x, y = get_correlated_dataset(500, dependency_nstd, mu, scale)
ax_nstd.scatter(x, y, s=0.5)

confidence_ellipse(x, y, ax_nstd, n_std=1,
                   label=r'$1\sigma$', edgecolor='firebrick')
confidence_ellipse(x, y, ax_nstd, n_std=2,
                   label=r'$2\sigma$', edgecolor='fuchsia', linestyle='--')
confidence_ellipse(x, y, ax_nstd, n_std=3,
                   label=r'$3\sigma$', edgecolor='blue', linestyle=':')

ax_nstd.scatter(mu[0], mu[1], c='red', s=3)
ax_nstd.set_title('Different standard deviations')
ax_nstd.legend()
plt.show()

キーワード引数を使用する

最後に、キーワード引数を使用して楕円の外観をカスタマイズすることができます。

fig, ax_kwargs = plt.subplots(figsize=(6, 6))
dependency_kwargs = [[-0.8, 0.5],
                     [-0.2, 0.5]]
mu = 2, -3
scale = 6, 5

ax_kwargs.axvline(c='grey', lw=1)
ax_kwargs.axhline(c='grey', lw=1)

x, y = get_correlated_dataset(500, dependency_kwargs, mu, scale)
## 透明度(alphaの使用による)を示すために、zorder=0で楕円をプロットします。
confidence_ellipse(x, y, ax_kwargs,
                   alpha=0.5, facecolor='pink', edgecolor='purple', zorder=0)

ax_kwargs.scatter(x, y, s=0.5)
ax_kwargs.scatter(mu[0], mu[1], c='red', s=3)
ax_kwargs.set_title('Using keyword arguments')

fig.subplots_adjust(hspace=0.25)
plt.show()

まとめ

この実験では、PythonのMatplotlibを使用して2次元データセットの信頼楕円をプロットする方法を学びました。confidence_ellipseget_correlated_dataset 関数を定義し、これらを使用して、異なる相関と標準偏差の数を持つデータセットの楕円をプロットしました。また、キーワード引数を使用して楕円の外観をカスタマイズする方法も示しました。