1. 程式人生 >實用技巧 >其它 >[機器學習] Yellowbrick使用筆記4-目標視覺化檔案

[機器學習] Yellowbrick使用筆記4-目標視覺化檔案


dates:  2020-07-25 10:31:35 +0800
tags:
  - 機器學習
  - Python
  - 資料分析與視覺化

目標視覺化工具專門用於直觀地描述用於監督建模的因變數,通常稱為y目標。
程式碼下載
當前實現了以下視覺化:

  • 平衡箱視覺化Balanced Binning:生成帶有垂直線的直方圖,垂直線顯示推薦值點,以將資料裝箱到均勻分佈的箱中。
  • 類平衡Class Balance:視覺化來檢查目標,以顯示每個類對最終估計器的支援。
  • 特徵相關Feature Correlation:繪製特徵和因變數之間的相關性。

標頭檔案呼叫如下:

# Target Visualizers Imports
from yellowbrick.target import BalancedBinningReference
from yellowbrick.target import ClassBalance
from yellowbrick.target import FeatureCorrelatio

本文如果資料集下載不下來,檢視下面地址,然後放入yellowbrick安裝目錄\datasets\fixtures資料夾:

{
  "bikeshare": {
    "url": "https://s3.amazonaws.com/ddl-data-lake/yellowbrick/v1.0/bikeshare.zip",
    "signature": "4ed07a929ccbe0171309129e6adda1c4390190385dd6001ba9eecc795a21eef2"
  },
  "hobbies": {
    "url": "https://s3.amazonaws.com/ddl-data-lake/yellowbrick/v1.0/hobbies.zip",
    "signature": "6114e32f46baddf049a18fb05bad3efa98f4e6a0fe87066c94071541cb1e906f"
  },
  "concrete": {
    "url": "https://s3.amazonaws.com/ddl-data-lake/yellowbrick/v1.0/concrete.zip",
    "signature": "5807af2f04e14e407f61e66a4f3daf910361a99bb5052809096b47d3cccdfc0a"
  },
  "credit": {
    "url": "https://s3.amazonaws.com/ddl-data-lake/yellowbrick/v1.0/credit.zip",
    "signature": "2c6f5821c4039d70e901cc079d1404f6f49c3d6815871231c40348a69ae26573"
  },
  "energy": {
    "url": "https://s3.amazonaws.com/ddl-data-lake/yellowbrick/v1.0/energy.zip",
    "signature": "174eca3cd81e888fc416c006de77dbe5f89d643b20319902a0362e2f1972a34e"
  },
  "game": {
    "url": "https://s3.amazonaws.com/ddl-data-lake/yellowbrick/v1.0/game.zip",
    "signature": "ce799d1c55fcf1985a02def4d85672ac86c022f8f7afefbe42b20364fba47d7a"
  },
  "mushroom": {
    "url": "https://s3.amazonaws.com/ddl-data-lake/yellowbrick/v1.0/mushroom.zip",
    "signature": "f79fdbc33b012dabd06a8f3cb3007d244b6aab22d41358b9aeda74417c91f300"
  },
  "occupancy": {
    "url": "https://s3.amazonaws.com/ddl-data-lake/yellowbrick/v1.0/occupancy.zip",
    "signature": "0b390387584586a05f45c7da610fdaaf8922c5954834f323ae349137394e6253"
  },
  "spam": {
    "url": "https://s3.amazonaws.com/ddl-data-lake/yellowbrick/v1.0/spam.zip",
    "signature": "000309ac2b61090a3001de3e262a5f5319708bb42791c62d15a08a2f9f7cb30a"
  },
  "walking": {
    "url": "https://s3.amazonaws.com/ddl-data-lake/yellowbrick/v1.0/walking.zip",
    "signature": "7a36615978bc3bb74a2e9d5de216815621bd37f6a42c65d3fc28b242b4d6e040"
  },
  "nfl": {
    "url": "https://s3.amazonaws.com/ddl-data-lake/yellowbrick/v1.0/nfl.zip",
    "signature": "4989c66818ea18217ee0fe3a59932b963bd65869928c14075a5c50366cb81e1f"
  }
}

1 平衡箱視覺化Balanced Binning

通常,現實世界中的機器學習問題會受到維數詛咒的影響;訓練例項比預期的要少,而且預測訊號分佈在許多不同的特徵上。有時,當目標變數連續賦值時,根本沒有足夠的例項來預測這些值達到迴歸的精度。在這種情況下,我們有時可以將問題轉化為連續的分類問題。

為了幫助使用者選擇最佳的倉位數量,BalancedBiningReference visualizer將目標變數y作為輸入,並生成一個直方圖,其中豎線表示建議的值點,以確保資料均勻地分佈到每個倉位中。

視覺化器 BalancedBinningReference
快速使用方法 balanced_binning_reference()
模型 分類
工作流程 特徵分析,目標分析,模型選擇
# 多行輸出
from IPython.core.interactiveshell import InteractiveShell
InteractiveShell.ast_node_interactivity = "all"

1.1 基本使用

BalancedBinningReference實際就是應用numpy中的histogram進行資料視覺化,histogram()會對區間中陣列所對應的權值進行求和,bins決定分箱個數。關於numpy中的histogram函式具體見:
numpy之histogram


from yellowbrick.datasets import load_concrete
from yellowbrick.target import BalancedBinningReference
import numpy as np
# Load the concrete dataset
X, y = load_concrete()

# Instantiate the visualizer
# 視覺化器,求各個區間的平均值
visualizer = BalancedBinningReference(bins=5)

# Fit the data to the visualizer
# 擬合數據
a=visualizer.fit(y)
# 顯示資料     
visualizer.show();       
<Figure size 800x550 with 1 Axes>

1.2 快速方法

上面的相同功能可以通過關聯的快速方法來實現balanced_binning_reference。此方法將BalancedBinningReference使用關聯的引數構建物件,將其擬合,然後(可選)立即顯示它。

from yellowbrick.datasets import load_concrete
from yellowbrick.target import balanced_binning_reference

# Load the dataset
X, y = load_concrete()

# Use the quick method and immediately show the figure
balanced_binning_reference(y);

2 類平衡Class Balance

分類模型面臨的最大挑戰之一是訓練資料中類的不平衡。嚴重的類不平衡可能被相對較好的F1和準確度分數掩蓋-分類器只是猜測大多數類,而不對代表性不足的類進行任何評估。

有幾種處理類不平衡的技術,例如分層抽樣,對多數類進行下采樣,加權等。但是,在採取這些措施之前,瞭解訓練資料中的類平衡是什麼很重要。ClassBalance visualizer通過為每個類建立支援的條形圖來支援這一點,即資料集中類表示的頻率。

視覺化器 ClassBalance
快速使用方法 class_balance()
模型 分類
工作流程 特徵分析,目標分析,模型選擇

2.1 基本使用

結果圖使我們能夠診斷餘額問題的嚴重性。 在此圖中,我們可以看到“ win”類主導了其他兩個類。 一種可能的解決方案是建立一個二進位制分類器:“ win”與“ not win”,並將“ loss”和“ draw”類組合為一個類。ClassBalance函式的功能就是計算各個類下樣本數。

from yellowbrick.datasets import load_game
from yellowbrick.target import ClassBalance

# Load the classification dataset
# 載入分類資料庫
X, y = load_game()
# Instantiate the visualizer
# ClassBalance函式的功能就是計算各個類下樣本數。
visualizer = ClassBalance(labels=["draw", "loss", "win"])

visualizer.fit(y)        # Fit the data to the visualizer
visualizer.show();        # Finalize and render the figure

如果在評估期間必須保持類別不平衡(例如,被分類的事件實際上如頻率所暗示的那樣罕見),則應使用分層抽樣來建立訓練和測試集。
這確保了測試資料與訓練資料具有大致相同的類比例。雖然SCRICIT-LEARN預設在Train_Test_Split和其他cv方法中執行此操作,但是比較兩個Split中每個類的支援情況可能是有用的。

ClassBalance視覺化工具具有“比較”模式,在該模式下,可以將訓練和測試資料傳遞給FIT(),從而建立並排條形圖而不是單個條形圖,如下所示:

from sklearn.model_selection import TimeSeriesSplit

from yellowbrick.datasets import load_occupancy
from yellowbrick.target import ClassBalance

# Load the classification dataset
X, y = load_occupancy()

# Create the training and test data
# 時間分割序列資料
tscv = TimeSeriesSplit()
for train_index, test_index in tscv.split(X):
    X_train, X_test = X.iloc[train_index], X.iloc[test_index]
    y_train, y_test = y.iloc[train_index], y.iloc[test_index]

# Instantiate the visualizer
visualizer = ClassBalance(labels=["unoccupied", "occupied"])

visualizer.fit(y_train, y_test)        # Fit the data to the visualizer
visualizer.show();
/opt/conda/envs/python35-paddle120-env/lib/python3.7/site-packages/sklearn/model_selection/_split.py:752: FutureWarning: You should specify a value for 'n_splits' instead of relying on the default value. The default value will change from 3 to 5 in version 0.22.
  warnings.warn(NSPLIT_WARNING, FutureWarning)

這種視覺化使我們可以快速檢查,以確保每個類在兩個拆分中的比例大致相似。這種視覺化應該是第一步,尤其是當評估指標在不同的分割中高度可變時。

2.2 快速使用

from yellowbrick.datasets import load_game
from yellowbrick.target import class_balance

# Load the dataset
X, y = load_game()

# Use the quick method and immediately show the figure
class_balance(y);

3 特徵相關Feature Correlation

該視覺化工具計算皮爾遜相關係數和特徵與因變數之間的互資訊。
這種視覺化可以用於特徵選擇,以識別與因變數具有高相關性或大互資訊的特徵。

預設計算是Pearson相關性,這是使用scipy.stats.Pearsonr執行的。

視覺化器 FeatureCorrelation
快速使用方法 feature_correlation()
模型 迴歸/分類/聚類
工作流程 特徵分析/模型選擇

3.1 Person分析

FeatureCorrelation通過method設定來確定分析方法,預設是person分析,除此之外還有mutual_info-regression,通過sklearn.feature_selection中的mutual_info-regression計算,還有mutual_info-classification,通過sklearn.feature_selection中的mutual_info_classif計算。

from sklearn import datasets
from yellowbrick.target import FeatureCorrelation

# Load the regression dataset
data = datasets.load_diabetes()
X, y = data['data'], data['target']

# Create a list of the feature names
features = np.array(data['feature_names'])

# Instantiate the visualizer
# 計算x中的每個特徵與y的相關性
visualizer = FeatureCorrelation(labels=features)

# Fit the data to the visualizer
visualizer.fit(X, y)        
visualizer.show();

3.2 Mutual Information Regression分析

互資訊詳細見:https://www.cntofu.com/book/48/shu-xue-ji-chu/xin-xi-lun/hu-xin-xi.md

互資訊與相關性的區別見:https://blog.csdn.net/gdanskamir/article/details/54913233

但是迴歸中,連續資料需要轉換為離散資料。特徵和因變數之間的相互資訊是使用sklearn.feature_selection.mutual_info_classifwhen method='mutual_info-classification'和mutual_info_regressionwhen 計算的method='mutual_info-regression'。在計算互資訊時,指定離散特徵非常重要,因為連續變數和離散變數的計算是不同的。sklearn中參考文件見http://scikit-learn.org/stable/modules/generated/sklearn.feature_selection.mutual_info_classif.html

from sklearn import datasets
from yellowbrick.target import FeatureCorrelation
import numpy as np

# Load the regression dataset
data = datasets.load_diabetes()
X, y = data['data'], data['target']

# Create a list of the feature names
features = np.array(data['feature_names'])

# Create a list of the discrete features
# 建立離散變數列表
discrete = [False for _ in range(len(features))]
# discrete為age需要變為離散變數
discrete[1] = True

# Instantiate the visualizer
visualizer = FeatureCorrelation(method='mutual_info-regression', labels=features)

visualizer.fit(X, y, discrete_features=discrete, random_state=0)
visualizer.show();

3.3 Mutual Information Classification分析

通過與pandas DataFrame配合,可以從列名稱中自動獲取功能標籤。該視覺化器還允許根據計算出互資訊(或Pearson相關係數)對條形圖進行排序,並通過指定特徵名稱或特徵索引來選擇要繪製的特徵。

import pandas as pd

from sklearn import datasets
from yellowbrick.target import FeatureCorrelation

# Load the regression dataset
# 匯入分類資料
data = datasets.load_wine()
X, y = data['data'], data['target']
X_pd = pd.DataFrame(X, columns=data['feature_names'])

# Create a list of the features to plot
features = ['alcohol', 'ash', 'hue', 'proline', 'total_phenols']

# Instaniate the visualizer
# sort設定是否排序
visualizer = FeatureCorrelation(
    method='mutual_info-classification', feature_names=features, sort=True
)

visualizer.fit(X_pd, y)        # Fit the data to the visualizer
visualizer.show();

3.4 快速使用

上面的相同功能可以通過關聯的快速方法來實現feature_correlation。此方法將FeatureCorrelation使用關聯的引數構建物件,將其擬合,然後(可選)立即顯示它

import numpy as np
from sklearn import datasets
import matplotlib.pyplot as plt
from yellowbrick.target.feature_correlation import feature_correlation

#Load the diabetes dataset
data = datasets.load_iris()
X, y = data['data'], data['target']

features = np.array(data['feature_names'])
visualizer = feature_correlation(X, y, labels=features)
plt.tight_layout();
<Figure size 432x288 with 0 Axes>

4 參考

https://www.scikit-yb.org/en/latest/api/target/binning.html

https://www.scikit-yb.org/en/latest/api/target/class_balance.html

https://blog.csdn.net/gdanskamir/article/details/54913233

https://www.scikit-yb.org/en/latest/api/target/feature_correlation.html#yellowbrick.target.feature_correlation.FeatureCorrelation