0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

最も相関の強い特徴量のペアを取り出す

Last updated at Posted at 2025-12-01

相関行列から最も相関の強い(=絶対値が1に近い)特徴量のペアを取り出すコードです。

import pandas as pd
import numpy as np

df = pd.DataFrame({
    'A': [10, 22, 36, 43, 55],
    'B': [24, 43, 86, 68, 10],
    'C': [52, 43, 33, 24, 16],
    'D': [18, 22, 41, 52, 61]
})

# 相関行列の作成
df_corr = df.corr()

# 下三角のみを取り出す(対角線も除外)
mask = np.triu(np.ones(df_corr.shape), k=0).astype(bool)
df_corr_masked = df_corr.mask(mask)

# 絶対値が最大の組み合わせを取得
features_max_corr_abs = df_corr_masked.abs().stack().idxmax()


print(f"相関係数 : {df_corr_masked.loc[features_max_corr_abs]:.3f}")
print(f"特徴量 : {features_max_corr_abs[0]}{features_max_corr_abs[1]}")
実行結果
相関係数 : -0.997
特徴量 : C と A

相関行列 df_corr

A B C D
A 1.000000 0.039565 -0.996503 0.982765
B 0.039565 1.000000 -0.019308 0.037627
C -0.996503 -0.019308 1.000000 -0.987924
D 0.982765 0.037627 -0.987924 1.000000

対角成分が 1.0 の対称行列になるので、対角成分と左下(右上)を取り除く必要がある。

相関行列の下三角 df_corr_masked

相関行列をマスクするために、bool値の上三角行列を作成する。
np.triu(np.ones(df_corr.shape), k=0).astype(bool)

array([[ True,  True,  True,  True],
       [False,  True,  True,  True],
       [False, False,  True,  True],
       [False, False, False,  True]])

相関行列にマスクする。
df_corr.mask(mask)

A B C D
A NaN NaN NaN NaN
B 0.039565 NaN NaN NaN
C -0.996503 -0.019308 NaN NaN
D 0.982765 0.037627 -0.987924 NaN

相関係数の絶対値が最大となる特徴量 features_max_corr_abs

絶対値に変換してからインデックスを階層化して1次元化する。
df_corr_masked.abs().stack()

B  A    0.039565
C  A    0.996503
   B    0.019308
D  A    0.982765
   B    0.037627
   C    0.987924
dtype: float64

最大となる階層インデックスを取得する。
df_corr_masked_abs.stack().idxmax()

('C', 'A')
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?