Notice
Recent Posts
Recent Comments
Link
«   2024/07   »
1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30 31
Archives
Today
Total
관리 메뉴

Passion, Grace & Fire.

pyplot : heatmap 본문

pyplot

pyplot : heatmap

vincenthanna 2020. 8. 26. 13:37

heatmap은 색상표에 기반하여 데이터를 시각화하는 그래픽 표현이다.

머신러닝 분야에서는 여러개의 feature에 대해 feature 간 연관성(상관관계)를 시각화하려고 할 때 많이 사용된다. 상관관계가 높은 feature들은 줄일 수 있기 때문에 성능개선에 도움이 된다.


feature마다의 상관관계(correlation)를 heatmap으로 표현하는 예제 코드이다.

먼저 데이터를 준비한다.

import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns

data = {'A' : [1, 0, 3, 2, 4, 5, 8],
        'B' : [1, 0, 3, 2, 4, 5, 8],
        'C' : [7, 6, 3, 4, 5, 2, 1],
        'D' : [3, 2, 4, 7, 6, 3, 0],
        'E' : [6, 7, 8, 9, 10, 11, 12],
        'F' : [2, 0, 3, 4, 6, 5, 8],
       }

df = pd.DataFrame(data, columns=sorted(data.keys()))
df = df.corr()

'''
result:
          A         B         C         D         E         F
A  1.000000  1.000000 -0.860309 -0.369609  0.917663  0.936586
B  1.000000  1.000000 -0.860309 -0.369609  0.917663  0.936586
C -0.860309 -0.860309  1.000000  0.292925 -0.857143 -0.729015
D -0.369609 -0.369609  0.292925  1.000000 -0.162736 -0.079724
E  0.917663  0.917663 -0.857143 -0.162736  1.000000  0.903978
F  0.936586  0.936586 -0.729015 -0.079724  0.903978  1.000000
'''

 

Seaborn 라이브러리 사용

colormap = plt.cm.magma
plt.figure(figsize=(20, 16))
plt.title('correlation of features', size=32)
sns.set(font_scale=2.4)
sns.heatmap(df, linewidths=0.1, vmax=1.0, square=True,
            cmap=colormap, linecolor='white', annot=True)

 

pyplot 라이브러리 사용

fig, ax = plt.subplots(figsize=(24, 20))
im = ax.matshow(df, cmap='viridis')
ax.grid(False)
ax.set_title("Correlation of Features")

ax.set_xticks(np.arange(df.shape[1]), minor=False)
ax.set_yticks(np.arange(df.shape[1]), minor=False)
ax.set_xticklabels(df.columns.values)
ax.set_yticklabels(df.columns.values)

# 항목마다 값을 출력하는 코드
for (i, j), z in np.ndenumerate(df.corr()):
    ax.text(j, i, '{:0.1f}'.format(z), ha='center', va='center',
           bbox=dict(boxstyle='round', facecolor='white', edgecolor='0.3'))

# colorbar 추가
fig.colorbar(im)

Comments