天天看點

科研作圖-heatmap(二)

1.簡介

上次我們簡單說了seaborn.heatmap函數,這一次我們将介紹在機器學習中的顯示不同特征之間相關性的熱力圖和Pyheatmap.heatmap用法。在機器學習中我們在篩選有用特征的時候,常常計算一下不同特征的相關性,便于我們去掉相關性強的特征,我們此次用的資料集為sklearn中的breast_cancer資料集。

2.特征之間相關性的熱力圖

(1)首先我們導入資料和作圖的包

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt # 導入作圖包
import seaborn as sns    # 導入作圖包
from sklearn.datasets import load_breast_cancer # 從sklearn導入資料
           

(2)檢視資料

cancer = load_breast_cancer() 
print(cancer.data)  #輸出資料的内容
print(cancer.target) #輸出資料的标簽
           

(3)檢視資料的列名

col_names = list(cancer.feature_names)  #檢視資料的列名
print(col_names)
col_names.append('target')
df = pd.DataFrame(np.c_[cancer.data, cancer.target], columns=col_names) #合并資料和标簽并存儲成DataFrame在df中
df.head() #展示資料的前五條
           
科研作圖-heatmap(二)

(4)檢視資料的基本統計學資訊

科研作圖-heatmap(二)

(5)檢視資料每列資訊

科研作圖-heatmap(二)

(6)生成不同特征之間的相關熱力圖,可以根據顔色篩選出相關性小的特征組合

plt.figure(figsize=(20,10)) 
sns.heatmap(df.corr(), annot=True) #根據特征相關性繪制熱力圖
plt.show()
           
科研作圖-heatmap(二)

其中看一下df.corr()方法:

DataFrame.corr(method='pearson', min_periods=1)

參數說明:
method:可選值為{‘pearson’, ‘kendall’, ‘spearman’}

df.corr()  # 預設是pearson相關系數
df.corr('kendall') # Kendall Tau相關系數
df.corr('spearman') # spearman秩相關
           

關于相關系數的數學計算公式這裡就不展開寫了,以後會慢慢補上。

3. Pyheatmap.heatmap

官方給了兩種說明,一是點選圖(使用滑鼠點點點,然後生成相應的點選圖),二是熱力圖,根據給定x,y資料生成熱力圖,生成效果如下:

(點選圖)

科研作圖-heatmap(二)

(熱力圖)

科研作圖-heatmap(二)

使用方法如下:

(1)安裝-這裡通過Pip

pip install pyheatmap
           

(2) 官方代碼例子

import urllib
from pyheatmap.heatmap import HeatMap

def main():

    # download test data
    url = "https://raw.github.com/oldj/pyheatmap/master/examples/test_data.txt"
    sdata = urllib.urlopen(url).read().split("\n")
    data = []
    for ln in sdata:
        a = ln.split(",")
        if len(a) != 2:
            continue
        a = [int(i) for i in a]
        data.append(a)

    # start painting
    hm = HeatMap(data)
    hm.clickmap(save_as="hit.png")
    hm.heatmap(save_as="heat.png")

if __name__ == "__main__":
    main()
           

(3)其他例子

from pyheatmap.heatmap import HeatMap
import numpy as np
x = [10,20,30,50,40,30,70,80,50,30,45,50]
y = [30,40,50,30,40,80,50,34,45,95,26,33]
data = []
for i in range(0,11):
    tmp = [int(x[i]), int(y[i]),1]
    data.append(tmp)
heat = HeatMap(data)
heat.clickmap(save_as="1.png") #點選圖
heat.heatmap(save_as="2.png") #熱圖
           

4.總結

這次我們介紹了在機器學習中的顯示不同特征之間相關性的熱力圖和Pyheatmap.heatmap用法,下次我将介紹場景熱力圖的使用。

5.參考

https://blog.csdn.net/walking_visitor/article/details/85128461

https://blog.csdn.net/sunmingyang1987/article/details/105459104

https://www.kaggle.com/prashant111/lightgbm-classifier-in-python

https://github.com/oldj/pyheatmap

https://blog.csdn.net/weixin_43289135/article/details/104651047