做者:xiaoyuhtml
微信公衆號:Python數據科學算法
玩過建模的朋友都知道,在創建模型以前有很長的一段特徵工程工做要作,而在特徵工程的過程當中,探索性數據分析又是必不可少的一部分,由於若是咱們要對各個特徵進行細緻的分析,那麼必然會進行一些可視化以輔助咱們來作選擇和判斷。api
可視化的工具備不少,可是可以針對特徵探索性分析而進行專門可視化的很少,今天給你們介紹一款功能十分強大的工具:yellowbrick
,但願經過這個工具的輔助能夠節省更多探索的時間,快速掌握特徵信息。數組
RadViz雷達圖是一種多變量數據可視化算法,它圍繞圓周均勻地分佈每一個特徵,而且標準化了每一個特徵值。通常數據科學家使用此方法來檢測類之間的關聯。例如,是否有機會從特徵集中學習一些東西或是否有太多的噪音?微信
# Load the classification data set data = load_data("occupancy") # Specify the features of interest and the classes of the target features = ["temperature", "relative humidity", "light", "C02", "humidity"] classes = ["unoccupied", "occupied"] # Extract the instances and target X = data[features] y = data.occupancy # Import the visualizer from yellowbrick.features import RadViz # Instantiate the visualizer visualizer = RadViz(classes=classes, features=features) visualizer.fit(X, y) # Fit the data to the visualizer visualizer.transform(X) # Transform the data visualizer.poof() # Draw/show/poof the data
從上面雷達圖能夠看出5個維度中,溫度對於目標類的影響是比較大的。dom
特徵的一維排序利用排名算法,僅考慮單個特徵,默認狀況下使用Shapiro-Wilk算法來評估與特徵相關的實例分佈的正態性,而後繪製一個條形圖,顯示每一個特徵的相對等級。工具
from yellowbrick.features import Rank1D # Instantiate the 1D visualizer with the Sharpiro ranking algorithm visualizer = Rank1D(features=features, algorithm='shapiro') visualizer.fit(X, y) # Fit the data to the visualizer visualizer.transform(X) # Transform the data visualizer.poof() # Draw/show/poof the data
PCA分解可視化利用主成分分析將高維數據分解爲二維或三維,以即可以在散點圖中繪製每一個實例。PCA的使用意味着能夠沿主要變化軸分析投影數據集,而且能夠解釋該數據集以肯定是否能夠利用球面距離度量。性能
PCA投影能夠加強到雙點,其點是投影實例,其矢量表示高維空間中數據的結構。經過使用proj_features = True標誌,數據集中每一個要素的向量將在散點圖上以該要素的最大方差方向繪製。這些結構可用於分析特徵對分解的重要性或查找相關方差的特徵以供進一步分析。學習
# Load the classification data set data = load_data('concrete') # Specify the features of interest and the target target = "strength" features = [ 'cement', 'slag', 'ash', 'water', 'splast', 'coarse', 'fine', 'age' ] # Extract the instance data and the target X = data[features] y = data[target] visualizer = PCADecomposition(scale=True, proj_features=True) visualizer.fit_transform(X, y) visualizer.poof()
特徵工程過程涉及選擇生成有效模型所需的最小特徵,由於模型包含的特徵越多,它就越複雜(數據越稀疏),所以模型對方差的偏差越敏感。消除特徵的經常使用方法是描述它們對模型的相對重要性,而後消除弱特徵或特徵組合並從新評估以肯定模型在交叉驗證期間是否更好。測試
在scikit-learn中,Decision Tree模型和樹的集合(如Random Forest,Gradient Boosting和AdaBoost)在擬合時提供feature_importances_屬性。Yellowbrick FeatureImportances可視化工具利用此屬性對相對重要性進行排名和繪製。
import matplotlib.pyplot as plt from sklearn.ensemble import GradientBoostingClassifier from yellowbrick.features.importances import FeatureImportances # Create a new matplotlib figure fig = plt.figure() ax = fig.add_subplot() viz = FeatureImportances(GradientBoostingClassifier(), ax=ax) viz.fit(X, y) viz.poof()
遞歸特徵消除(RFE)是一種特徵選擇方法,它訓練模型並刪除最弱的特徵(或多個特徵),直到達到指定數量的特徵。特徵按模型的coef_或feature_importances_屬性排序,並經過遞歸消除每一個循環的少許特徵,RFE嘗試消除模型中可能存在的依賴性和共線性。
RFE須要保留指定數量的特徵,但事先一般不知道有多少特徵有效。爲了找到最佳數量的特徵,交叉驗證與RFE一塊兒用於對不一樣的特徵子集進行評分,並選擇最佳評分特徵集合。RFECV可視化繪製模型中的特徵數量以及它們的交叉驗證測試分數和可變性,並可視化所選數量的特徵。
from sklearn.svm import SVC from sklearn.datasets import make_classification from yellowbrick.features import RFECV # Create a dataset with only 3 informative features X, y = make_classification( n_samples=1000, n_features=25, n_informative=3, n_redundant=2, n_repeated=0, n_classes=8, n_clusters_per_class=1, random_state=0 ) # Create RFECV visualizer with linear SVM classifier viz = RFECV(SVC(kernel='linear', C=1)) viz.fit(X, y) viz.poof()
該圖顯示了理想的RFECV曲線,當捕獲三個信息特徵時,曲線跳躍到極好的準確度,而後隨着非信息特徵被添加到模型中,精度逐漸下降。陰影區域表示交叉驗證的可變性,一個標準誤差高於和低於曲線繪製的平均精度得分。
下面是一個真實數據集,咱們能夠看到RFECV對信用違約二元分類器的影響。
from sklearn.ensemble import RandomForestClassifier from sklearn.model_selection import StratifiedKFold df = load_data('credit') target = 'default' features = [col for col in data.columns if col != target] X = data[features] y = data[target] cv = StratifiedKFold(5) oz = RFECV(RandomForestClassifier(), cv=cv, scoring='f1_weighted') oz.fit(X, y) oz.poof()
在這個例子中,咱們能夠看到選擇了19個特徵,儘管在大約5個特徵以後模型的f1分數彷佛沒有太大改善。選擇要消除的特徵在肯定每一個遞歸的結果中起着重要做用;修改步驟參數以在每一個步驟中消除多個特徵可能有助於儘早消除最差特徵,加強其他特徵(而且還可用於加速具備大量特徵的數據集的特徵消除)。
在迴歸模型的上下文中,殘差是目標變量(y)的觀測值與預測值(ŷ)之間的差別,例如,預測的錯誤。殘差圖顯示垂直軸上的殘差與水平軸上的因變量之間的差別,容許檢測目標中可能容易出錯或多或少的偏差的區域。
from sklearn.linear_model import Ridge from yellowbrick.regressor import ResidualsPlot # Instantiate the linear model and visualizer ridge = Ridge() visualizer = ResidualsPlot(ridge) visualizer.fit(X_train, y_train) # Fit the training data to the model visualizer.score(X_test, y_test) # Evaluate the model on the test data visualizer.poof() # Draw/show/poof the data
正則化旨在懲罰模型複雜性,所以α越高,模型越複雜,因爲方差(過分擬合)而減小偏差。另外一方面,過高的Alpha會因誤差(欠調)而增長偏差。所以,重要的是選擇最佳α,以便在兩個方向上最小化偏差。 AlphaSelection Visualizer演示了不一樣的α值如何影響線性模型正則化過程當中的模型選擇。通常而言,α增長了正則化的影響,例如,若是alpha爲零,則沒有正則化,α越高,正則化參數對最終模型的影響越大。
import numpy as np from sklearn.linear_model import LassoCV from yellowbrick.regressor import AlphaSelection # Create a list of alphas to cross-validate against alphas = np.logspace(-10, 1, 400) # Instantiate the linear model and visualizer model = LassoCV(alphas=alphas) visualizer = AlphaSelection(model) visualizer.fit(X, y) g = visualizer.poof()
類預測偏差圖提供了一種快速瞭解分類器在預測正確類別方面有多好的方法。
from sklearn.ensemble import RandomForestClassifier from yellowbrick.classifier import ClassPredictionError # Instantiate the classification model and visualizer visualizer = ClassPredictionError( RandomForestClassifier(), classes=classes ) # Fit the training data to the visualizer visualizer.fit(X_train, y_train) # Evaluate the model on the test data visualizer.score(X_test, y_test) # Draw visualization g = visualizer.poof()
固然也同時有分類評估指標的可視化,包括混淆矩陣、AUC/ROC、召回率/精準率等等。
關於二元分類器的辨別閾值的精度,召回,f1分數和queue rate的可視化。辨別閾值是在陰性類別上選擇正類別的機率或分數。一般,將其設置爲50%,但能夠調整閾值以增長或下降對誤報或其餘應用因素的敏感度。
from sklearn.linear_model import LogisticRegression from yellowbrick.classifier import DiscriminationThreshold # Instantiate the classification model and visualizer logistic = LogisticRegression() visualizer = DiscriminationThreshold(logistic) visualizer.fit(X, y) # Fit the training data to the visualizer visualizer.poof() # Draw/show/poof the data
KElbowVisualizer實現了「肘部」法則,經過使模型具備K的一系列值來幫助數據科學家選擇最佳簇數。若是折線圖相似於手臂,那麼「肘」(拐點)就是曲線)是一個很好的跡象,代表基礎模型最適合那一點。
在下面的示例中,KElbowVisualizer在具備8個隨機點集的樣本二維數據集上適合KMeans模型,以得到4到11的K值範圍。當模型適合8個聚類時,咱們能夠在圖中看到「肘部」,在這種狀況下,咱們知道它是最佳數字。
from sklearn.datasets import make_blobs # Create synthetic dataset with 8 random clusters X, y = make_blobs(centers=8, n_features=12, shuffle=True, random_state=42) from sklearn.cluster import KMeans from yellowbrick.cluster import KElbowVisualizer # Instantiate the clustering model and visualizer model = KMeans() visualizer = KElbowVisualizer(model, k=(4,12)) visualizer.fit(X) # Fit the data to the visualizer visualizer.poof() # Draw/show/poof the data
集羣間距離地圖以2維方式顯示集羣中心的嵌入,並保留與其餘中心的距離。例如。中心越靠近可視化,它們就越接近原始特徵空間。根據評分指標調整集羣的大小。默認狀況下,它們按內部數據的多少,例如屬於每一箇中心的實例數。這給出了集羣的相對重要性。但請注意,因爲兩個聚類在2D空間中重疊,所以並不意味着它們在原始特徵空間中重疊。
from sklearn.datasets import make_blobs # Make 12 blobs dataset X, y = make_blobs(centers=12, n_samples=1000, n_features=16, shuffle=True) from sklearn.cluster import KMeans from yellowbrick.cluster import InterclusterDistance # Instantiate the clustering model and visualizer visualizer = InterclusterDistance(KMeans(9)) visualizer.fit(X) # Fit the training data to the visualizer visualizer.poof() # Draw/show/poof the data
學習曲線基於不一樣數量的訓練樣本,檢驗模型訓練分數與交叉驗證測試分數的關係。這種可視化一般用來表達兩件事:
下面是利用yellowbrick生成的學習曲線可視化圖。該學習曲線對於分類、迴歸和聚類均可以適用。
模型驗證用於肯定模型對其已通過訓練的數據的有效性以及它對新輸入的泛化程度。爲了測量模型的性能,咱們首先將數據集拆分爲訓練和測試,將模型擬合到訓練數據上並在保留的測試數據上進行評分。
爲了最大化分數,必須選擇模型的超參數,以便最好地容許模型在指定的特徵空間中操做。大多數模型都有多個超參數,選擇這些參數組合的最佳方法是使用網格搜索。然而,繪製單個超參數對訓練和測試數據的影響有時是有用的,以肯定模型是否對某些超參數值不適合或過分擬合。
import numpy as np from sklearn.tree import DecisionTreeRegressor from yellowbrick.model_selection import ValidationCurve # Load a regression dataset data = load_data('energy') # Specify features of interest and the target targets = ["heating load", "cooling load"] features = [col for col in data.columns if col not in targets] # Extract the instances and target X = data[features] y = data[targets[0]] viz = ValidationCurve( DecisionTreeRegressor(), param_name="max_depth", param_range=np.arange(1, 11), cv=10, scoring="r2" ) # Fit and poof the visualizer viz.fit(X, y) viz.poof()
我的認爲yellowbrick這個工具很是好,一是由於解決了特徵工程和建模過程當中的可視化問題,極大地簡化了操做;二是經過各類可視化也能夠補充本身對建模的一些盲區。
本篇僅展現了建模中部分可視化功能,詳細的完整功能請參考:
https://www.scikit-yb.org/en/...
若是以爲有幫助,還請給點個贊!
歡迎關注個人我的公衆號:Python數據科學