作者:xiaoyu,數據愛好者
Python數據科學出品
Scikit-learn此次發佈的版本爲0.22。我瀏覽了一下,此次版本除了修復之前出現的一些bug,還更新了很多新功能,不得不說更加好用了。下面我把我瞭解到主要的幾個最新功能和大家分享一下。
▍sklearn.ensemble 集成模型
1. 模型融合
舊版本的ensemble集成學習模塊裏只有提升樹、隨機森林等高級模型,新版本增加了融合模型,有 StackingClassifier 和 StackingRegressor ,對應分類和迴歸。原來模型融合的做法是自己手擼一個,現在可以做到直接使用方法,更加方便,尤其對於參加kaggle競賽,模型融合也是上分利器。
下面是更新後的一個使用例子。
from sklearn.datasets import load_iris
from sklearn.svm import LinearSVC
from sklearn.linear_model import LogisticRegression
from sklearn.preprocessing import StandardScaler
from sklearn.pipeline import make_pipeline
from sklearn.ensemble import StackingClassifier
from sklearn.model_selection import train_test_split
X, y = load_iris(return_X_y=True)
estimators = [
('rf', RandomForestClassifier(n_estimators=10, random_state=42)),
('svr', make_pipeline(StandardScaler(),
LinearSVC(random_state=42)))
]
clf = StackingClassifier(
estimators=estimators, final_estimator=LogisticRegression()
)
X_train, X_test, y_train, y_test = train_test_split(
X, y, stratify=y, random_state=42
)
clf.fit(X_train, y_train).score(X_test, y_test)
0.9473684210526315
2. 對梯度提升提供缺失值的本地支持
ensemble.HistGradientBoostingClassifier 和 ensemble.HistGradientBoostingRegressor 現在對缺失值(NaNs)具有本機支持,因此在訓練或預測時就不需填補缺失數據了,完全可以直接運行。
from sklearn.experimental import enable_hist_gradient_boosting # noqa
from sklearn.ensemble import HistGradientBoostingClassifier
import numpy as np
X = np.array([0, 1, 2, np.nan]).reshape(-1, 1)
y = [0, 0, 1, 1]
gbdt = HistGradientBoostingClassifier(min_samples_leaf=1).fit(X, y)
print(gbdt.predict(X))
[0 0 1 1]
▍sklearn.impute 模塊
新版本的 sklearn.impute 模塊中增加了 impute.KNNImputer ,所以當我們需要填補缺失值時,可以考慮直接使用KNN的這個算法填補。
import numpy as np
from sklearn.impute import KNNImputer
X = [[1, 2, np.nan], [3, 4, 3], [np.nan, 6, 5], [8, 8, 7]]
imputer = KNNImputer(n_neighbors=2)
print(imputer.fit_transform(X))
[[1. 2. 4. ]
[3. 4. 3. ]
[5.5 6. 5. ]
[8. 8. 7. ]]
▍sklearn.inspection 模塊
新增加了 inspection.permutation_importance, 可以用來估計每個特徵的重要性。
from sklearn.ensemble import RandomForestClassifier
from sklearn.inspection import permutation_importance
X, y = make_classification(random_state=0, n_features=5, n_informative=3)
rf = RandomForestClassifier(random_state=0).fit(X, y)
result = permutation_importance(rf, X, y, n_repeats=10, random_state=0,
n_jobs=-1)
fig, ax = plt.subplots()
sorted_idx = result.importances_mean.argsort()
ax.boxplot(result.importances[sorted_idx].T,
vert=False, labels=range(X.shape[1]))
ax.set_title("Permutation Importance of each feature")
ax.set_ylabel("Features")
fig.tight_layout()
plt.show()
▍sklearn.metrics 模塊
新版本增加了一個非常好的功能 metrics.plot_roc_curve,解決了roc_curve 繪製的問題。原來需要自己根據auc/roc原理自己擼,雖然網上已有了相應成熟的現成代碼,但此後可以直接放心大膽的用了。
同時,這個 roc_auc_score 函數也可用於多類分類。目前支持兩種平均策略:1-VS-1 算法計算成對的ROC AUC分數的平均值,1-VS-REST 算法計算每一類相對於所有其他類的平均分數。在這兩種情況下,多類ROC AUC分數是根據該模型從樣本屬於特定類別的概率估計來計算的。OVO和OVR算法支持均勻加權(average='macro')和按流行率(average='weighted')。
from sklearn.datasets import make_classification
from sklearn.svm import SVC
from sklearn.metrics import roc_auc_score
X, y = make_classification(n_classes=4, n_informative=16)
clf = SVC(decision_function_shape='ovo', probability=True).fit(X, y)
print(roc_auc_score(y, clf.predict_proba(X), multi_class='ovo'))
0.9957333333333332
腳本的總運行時間:(0分7.364秒)
估計內存使用量:8 MB
▍全新 plotting API
對於創建可視化任務,scikit-learn 推出了一個全新 plotting API。這個新API可以快速調整圖形的視覺效果,不再需要進行重新計算。也可以在同一個圖形中添加不同的圖表。例如:
from sklearn.model_selection import train_test_split
from sklearn.svm import SVC
from sklearn.metrics import plot_roc_curve
from sklearn.ensemble import RandomForestClassifier
from sklearn.datasets import make_classification
import matplotlib.pyplot as plt
X, y = make_classification(random_state=0)
X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=42)
svc = SVC(random_state=42)
svc.fit(X_train, y_train)
rfc = RandomForestClassifier(random_state=42)
rfc.fit(X_train, y_train)
svc_disp = plot_roc_curve(svc, X_test, y_test)
rfc_disp = plot_roc_curve(rfc, X_test, y_test, ax=svc_disp.ax_)
rfc_disp.figure_.suptitle("ROC curve comparison")
plt.show()
▍預計算的稀疏近鄰圖
大多數基於最近鄰圖的估算都接受預先計算的稀疏圖作爲輸入,以將同一圖重用於多個估算量擬合。
要在pipeline中使用這個特性,可以使用 memory 參數,以及neighbors.KNeighborsTransformer 和 neighbors.RadiusNeighborsTransformer 中的一個。
預計算還可以由自定義的估算器來執行。
from tempfile import TemporaryDirectory
from sklearn.neighbors import KNeighborsTransformer
from sklearn.manifold import Isomap
from sklearn.pipeline import make_pipeline
X, y = make_classification(random_state=0)
with TemporaryDirectory(prefix="sklearn_cache_") as tmpdir:
estimator = make_pipeline(
KNeighborsTransformer(n_neighbors=10, mode='distance'),
Isomap(n_neighbors=10, metric='precomputed'),
memory=tmpdir)
estimator.fit(X)
# We can decrease the number of neighbors and the graph will not be
# recomputed.
estimator.set_params(isomap__n_neighbors=5)
estimator.fit(X)
以上就是本次我瞭解到的主要更新內容,更多詳細信息請參考。
鏈接:https://scikit-learn.org/dev/whats_new/v0.22.html
▍安裝
升級很簡單,一行指令即可完成。
pip install --upgrade scikit-learn
或者用conda
conda install scikit-learn
推薦閱讀
1、牛逼!這個Python庫竟然可以偷懶,和import說再見!
3、Windows上評分最高的截圖工具,幫你搞定論文和設計難題
5、神作《統計學習要素》的中文翻譯、代碼實現及其習題解答,附下載