中輸入learn_Scikit-learn新版本發布,一行代碼秒升級

5c58dc7906a6091d49564932a246054e.png

十三 發自 凹非寺
量子位 報道 | 公眾號 QbitAI

Scikit-learn,這個強大的Python包,一直深受機器學習玩家青睞。

而近日,scikit-learn 官方發布了 0.22 最終版本

285890bb73a3e5c333b2a0c8926eeb91.png

此次的更新修復了許多舊版本的bug,同時發布了一些新功能。

安裝最新版本 scikit-learn 也很簡單。

使用 pip :

pip install --upgrade scikit-learn

使用 conda :

conda install scikit-learn

接下來,就是此次更新的十大亮點

全新 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 pltX, 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()

b51883b2b7e2f63abb66a465eb2e199d.png

StackingClassifier和StackingRegressor

StackingClassifier 和 StackingRegressor 允許用戶擁有一個具有最終分類器/回歸器的估計器堆棧(estimator of stack)。

堆棧泛化(stacked generalization)是將各個估計器的輸出疊加起來,然后使用分類器來計算最終的預測。

基礎估計器擬合在完整的X( full X )上,而最終估計器則使用基于cross_val_predict的基礎估計器的交叉驗證預測進行訓練。

例如:

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_splitX, 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。

基于排列(permutation)的特征重要性

inspection.permutation_importance可以用來估計每個特征的重要性,對于任何擬合的估算器:

from sklearn.ensemble import RandomForestClassifier
from sklearn.inspection import permutation_importanceX, 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()

8964e3fcdda2089c8dbf0eec74f570a4.png

對梯度提升提供缺失值的本地支持

ensemble.HistGradientBoostingClassifier 和 ensemble.HistGradientBoostingRegressor 現在對缺失值(NaNs)具有本機支持。這意味著在訓練或預測時無需插補數據。

from sklearn.experimental import enable_hist_gradient_boosting  # noqa
from sklearn.ensemble import HistGradientBoostingClassifier
import numpy as npX = 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]。

預計算的稀疏近鄰圖

現在,大多數基于最近鄰圖的估算都接受預先計算的稀疏圖作為輸入,以將同一圖重用于多個估算量擬合。

要在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_pipelineX, 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)

基于Imputation的KNN

現在,scikit_learn 支持使用k近鄰來填充缺失值。

from sklearn.impute import KNNImputerX = [[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. ]]

樹剪枝

現在,在建立一個樹之后,可以剪枝大部分基于樹的估算器。

X, y = make_classification(random_state=0)rf = RandomForestClassifier(random_state=0, ccp_alpha=0).fit(X, y)
print("Average number of nodes without pruning {:.1f}".format(np.mean([e.tree_.node_count for e in rf.estimators_])))rf = RandomForestClassifier(random_state=0, ccp_alpha=0.05).fit(X, y)
print("Average number of nodes with pruning {:.1f}".format(np.mean([e.tree_.node_count for e in rf.estimators_])))

輸出
Average number of nodes without pruning 22.3
Average number of nodes with pruning 6.4

從OpenML檢索dataframe

datasets.fetch_openml現在可以返回pandas dataframe,從而正確處理具有異構數據的數據集:

from sklearn.datasets import fetch_openmltitanic = fetch_openml('titanic', version=1, as_frame=True)
print(titanic.data.head()[['pclass', 'embarked']])

輸出
pclass embarked
0 1.0 S
1 1.0 S
2 1.0 S
3 1.0 S
4 1.0 S

檢查一個估算器的scikit-learn兼容性

開發人員可以使用check_estimator檢查其scikit-learn兼容估算器的兼容性。

現在,scikit-learn 提供了pytest特定的裝飾器(decorator),該裝飾器允許pytest獨立運行所有檢查并報告失敗的檢查。

from sklearn.linear_model import LogisticRegression
from sklearn.tree import DecisionTreeRegressor
from sklearn.utils.estimator_checks import parametrize_with_checks@parametrize_with_checks([LogisticRegression, DecisionTreeRegressor])
def test_sklearn_compatible_estimator(estimator, check):check(estimator)

ROC AUC現在支持多類別分類

roc_auc_score 函數也可用于多類別分類。

目前支持兩種平均策略:

one-vs-one算法計算兩兩配對的ROC AUC分數的平均值;
one-vs-rest算法計算每個類別相對于所有其他類別的ROC AUC分數的平均值。

在這兩種情況下,模型都是根據樣本屬于特定類別的概率估計來計算多類別ROC AUC分數。

from sklearn.datasets import make_classification
from sklearn.svm import SVC
from sklearn.metrics import roc_auc_scoreX, 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

傳送門

Twitter:https://twitter.com/scikit_learn/status/1201847227561529346

博客:https://scikit-learn.org/stable/auto_examples/release_highlights/plot_release_highlights_0_22_0.html#new-plotting-api

使用指南:https://scikit-learn.org/stable/modules/model_evaluation.html#roc-metrics

— 完 —

量子位 · QbitAI

?'?' ? 追蹤AI技術和產品新動態

戳右上角「+關注」獲取最新資訊↗↗

如果喜歡,請分享or點贊吧~比心?

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/279297.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/279297.shtml
英文地址,請注明出處:http://en.pswp.cn/news/279297.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

禁用刪除鍵退回歷史記錄_如何在Windows 8中刪除或禁用搜索超級按鈕歷史記錄

禁用刪除鍵退回歷史記錄When you use the Search Charm in Windows 8 it remembers everything you search for, which is very useful, but if you share your PC with someone you may want to delete your history or even disable it. Here’s how to do it. 在Windows 8中…

Java8基礎之super關鍵字

相信學過Java語言的小伙伴都熟悉super這個關鍵字,接下來,我們來研究他的一些基礎用法吧。 定義名字為Father的類 package superkeyworld;public class Father {public String name;public int age;public Father() {}public Father(String name, int age…

canpro腳本_AE/PR腳本-創建編輯導入導出專業字幕腳本 Subtitle Pro 2.8.0 + 使用教程...

Subtitle Pro是一個專業的插件,可讓您直接在After Effects和Premiere Pro中為視頻創建字幕。可將字幕快速的導入或導出。您可以導入.srt文件或任何字幕格式,也可以編寫文本。一鍵翻譯單詞,一鍵同步時間。不僅是簡單的字幕文字,還可…

【概率論】1-2:計數方法(Counting Methods)

title: 【概率論】1-2:計數方法(Counting Methods) categories: MathematicProbability keywords:Counting Methods技術方法Combinatorial Methods組合方法Multiplication乘法法則Permutations排列Stirling’s Formula斯特林公式 toc: true date: 2018-01-25 10:35:46Abstract:…

Python字符編碼詳解

Python字符編碼詳解 http://www.cnblogs.com/huxi/archive/2010/12/05/1897271.html本文簡單介紹了各種常用的字符編碼的特點,并介紹了在python2.x中如何與編碼問題作戰 :) 請注意本文關于Python的內容僅適用于2.x,3.x中str和…

使用sql服務器發送賀卡_創建和發送免費電子賀卡的最佳網站

使用sql服務器發送賀卡With the holiday season upon us, it’s time to pull out the holiday card list and get writing. However, how would you like to save some money this year and also help save the environment? 隨著假期的到來,是時候抽出節日賀卡清…

職稱申報評審管理系統_《四川省職稱評審管理暫行辦法》出臺

我省將探索實行職稱評審電子證書,電子證書與紙質證書具有同等效力。12月29日,記者從省人社廳了解到,我省近日出臺《四川省職稱評審管理暫行辦法》,從職稱評審總體要求、評審主體、申報程序、組織實施、優化服務、強化監管等方面提…

WordCount--統計輸入文件的字符數、行數、單詞數(java)--初級功能

碼云地址: https://gitee.com/YuRenDaZ/WordCount 個人PSP表格: PSP2.1 PSP階段 預估耗時 (分鐘) 實際耗時 (分鐘) Planning 計劃 180 120 Estimate 估計這個任務需要多少時間 180 120 D…

網頁的驗證碼

1.首先可以寫一個產生隨機驗證碼的aspx文件,如下產生四位數字: private void Page_Load(object sender, System.EventArgs e) { this.CreateCheckCodeImage(GenerateCheckCode()); } private string GenerateCheckCode() { …

榮耀9igoogle模式_iGoogle個性化主頁的6種替代方法

榮耀9igoogle模式iGoogle has less than a year to go before it’s shut down for good on November 1, 2013. While Google seems to think that iGoogle isn’t necessary anymore, there are other services waiting to take its place. iGoogle距離其2013年11月1日永久關閉…

華為堡壘機_安恒信息成為“華為云優秀嚴選合作伙伴”,攜手保障“云上”資產安全訪問...

加快5G持續創新能力,為云計算行業注入新動能。近日,以“智者?同行?共贏”為主題的2020華為云ISV(嚴選)合作伙伴大會在杭州隆重舉行。上百位華為云合作伙伴、行業大咖等專業人士齊聚一堂,探討云計算產業熱門話題。作為華為云重要的生態合作伙…

zip4j實現多線程壓縮

使用的jar包:zip4j_1.3.2.jar 基本功能: 針對ZIP壓縮文件創建、添加、分卷、更新和移除文件 (讀寫有密碼保護的Zip文件) (支持AES 128/256算法加密) (支持標準Zip算法加密) (支持zip64格式) (支持Store(僅打包,默認不壓縮,…

非三星手機無法登錄三星賬號_如何解決所有三星手機的煩惱

非三星手機無法登錄三星賬號Samsung is the biggest manufacturer of Android phones in the world, but that doesn’t mean these handsets are perfect out of the box. In fact, most of these phones have several annoyances initially—here’s how to fix many of thes…

設置單元格填充方式_單元格的選擇及設置單元格格式

數據輸入完畢,接下來可以設置字體、對齊方式、添加邊框和底紋等方式設置單元格格式,從而美化工作表。要對單元格進行設置,首先要選中單元格。選擇單元格選擇單元格是指在工作表中確定活動單元格以便在單元格中進行輸入、修改、設置和刪除等操…

Recover Binary Search Tree

Two elements of a binary search tree (BST) are swapped by mistake. Recover the tree without changing its structure. Note: A solution using O(n) space is pretty straight forward. Could you devise a constant space solution? 要求找到BST中放錯位置的兩個節點. …

springboot三種過濾功能的使用與比較

若要實現對請求的過濾,有三種方式可供選擇:filter、interceptort和aop。本文主要討論三種攔截器的使用場景與使用方式。 下文中的舉例功能是計算每個請求的從開始到結束的時間,例子來源是慕課網。 一、filter 特點:可以獲取原始的…

后綴的形容詞_構詞法(18)構成形容詞的常見后綴 3

即時練習一、按要求改寫下列單詞。1. Japan →___________ adj. 日本(人)的2. Canton →_________ adj. 廣東(人)的3. Vietnam →__________ adj. 越南(人)的4. Europe →__________ adj. 歐洲(人)的5. India → ________ adj. 印度(人)的6. Africa →_______ adj. 非洲(人)的7…

CentOS 桌面啟動無登錄界面

最近VMWare下搞了2個CentOS 32bit虛擬機, 裝了些軟件之后,都遇到開機無法顯示登錄界面, 僅能看見桌面背景圖的情況。 以下是我搜索很久匯總的方法。 嘗試按 ctrl alt F3(快捷鍵可能有所不同), 由桌面模式進入命令行模式。 直接 startx 報錯&#xf…

批量刪除推文_如何搜索(和刪除)您的舊推文

批量刪除推文“The internet never forgets” is an aphorism that isn’t entirely true, but it’s worth thinking about whenever you post to social media. If you think your Twitter profile needs a bit of a scrub, here’s how to search and delete those old twee…

[USACO13JAN] Cow Lineup (單調隊列,尺取法)

題目鏈接 Solution 尺取法板子,算是復習一波. 題中說最多刪除 \(k\) 種,那么其實就是找一個顏色種類最多為 \(k1\) 的區間; 統計一下其中最多的顏色出現次數. 然后直接尺取法,然后每次對于 \(col[r]\) 進行統計,時間復雜度 \(O(n)\) . Code #include<bits/stdc.h> using …