中输入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.mzph.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 …