十三 发自 凹非寺
量子位 报道 | 公众号 QbitAI

Scikit-learn,这个强大的Python包,一直深受机器学习玩家青睐。

而近日,scikit-learn 官方发布了 0.22 最终版本

此次的更新修复了许多旧版本的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_splitfrom sklearn.svm import SVCfrom sklearn.metrics import plot_roc_curvefrom sklearn.ensemble import RandomForestClassifierfrom sklearn.datasets import make_classificationimport 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()

StackingClassifier和StackingRegressor

StackingClassifier 和 StackingRegressor 允许用户拥有一个具有最终分类器/回归器的估计器堆栈(estimator of stack)。

堆栈泛化(stacked generalization)是将各个估计器的输出叠加起来,然后使用分类器来计算最终的预测。

基础估计器拟合在完整的X( full X )上,而最终估计器则使用基于cross_val_predict的基础估计器的交叉验证预测进行训练。

例如:

from sklearn.datasets import load_irisfrom sklearn.svm import LinearSVCfrom sklearn.linear_model import LogisticRegressionfrom sklearn.preprocessing import StandardScalerfrom sklearn.pipeline import make_pipelinefrom sklearn.ensemble import StackingClassifierfrom 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 RandomForestClassifierfrom 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()

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

ensemble.HistGradientBoostingClassifier 和 ensemble.HistGradientBoostingRegressor 现在对缺失值(NaNs)具有本机支持。这意味着在训练或预测时无需插补数据。

from sklearn.experimental import enable_hist_gradient_boosting # noqafrom sklearn.ensemble import HistGradientBoostingClassifierimport 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 TemporaryDirectoryfrom sklearn.neighbors import KNeighborsTransformerfrom sklearn.manifold import Isomapfrom 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 LogisticRegressionfrom sklearn.tree import DecisionTreeRegressorfrom 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_classificationfrom sklearn.svm import SVCfrom 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 · 头条号签约

关注我们,第一时间获知前沿科技动态

golang 升级到新版本_Scikit-learn新版本发布,一行代码秒升级相关推荐

  1. Scikit-learn新版本发布,一行代码秒升级

    十三 发自 凹非寺  量子位 报道 | 公众号 QbitAI Scikit-learn,这个强大的Python包,一直深受机器学习玩家青睐. 而近日,scikit-learn 官方发布了 0.22 最 ...

  2. 中输入learn_Scikit-learn新版本发布,一行代码秒升级

    十三 发自 凹非寺 量子位 报道 | 公众号 QbitAI Scikit-learn,这个强大的Python包,一直深受机器学习玩家青睐. 而近日,scikit-learn 官方发布了 0.22 最终 ...

  3. Scikit-Learn 新版本发布!一行代码秒升级

    点击我爱计算机视觉标星,更快获取CVML新技术 十三 发自 凹非寺  量子位 报道 | 公众号 QbitAI Scikit-learn,这个强大的Python包,一直深受机器学习玩家青睐. 而近日,s ...

  4. Bitcoin ABC发布11月BCH升级要点,快看做了哪些改变?

    比特币现金在11月份即将到来的升级一直都是大家关注的重点.针对此次升级的方向,BCH社区也进行过多次的讨论.上个月,比特币现金的主要开发团队Bitcoin ABC针对2018年11月15日即将到来的升 ...

  5. 华为新系统鸿蒙升级时间,好消息确定!鸿蒙之后华为全新系统发布,只期待升级尝鲜...

    原标题:好消息确定!鸿蒙之后华为全新系统发布,只期待升级尝鲜 庆幸的是!教主现在已经是地地道道的小花粉了,为什么此处要称"小"呢?其实关键还是因为自己没钱只能买一些华为降价的产品, ...

  6. 谷歌手机升级android10,Android10.0都准备发布了,你的手机升级到Android9.0了

    原标题:Android10.0都准备发布了,你的手机升级到Android9.0了 谷歌的Android9.0于2018年8月6日发布,至今已过去半年多,但是国内安卓手机升级到Android9.0的机型 ...

  7. mysql 升级到集群_MySQL Yum存储库 安装、升级、集群

    添加MySQL Yum存储库 首先,将MySQL Yum存储库添加到系统的存储库列表中.按着这些次序: 选择并下载适用于您的平台的发行包. 使用以下命令安装下载的发行包,替换platform-and- ...

  8. [php] 如何正确发布 PHP 代码

    如何正确发布PHP代码 几乎每一个 PHP 程序员都发布过代码,可能是通过 FTP 或者 **rsync ** 同步的,也可能是通过 svn 或者 git 更新的.一个活跃的项目可能每天都要发布若干次 ...

  9. 甲骨文发布低代码平台,轻松扩展SaaS应用程序

    甲骨文全球大会,美国旧金山,2016年9月21日 -甲骨文今天发布了云可视化开发平台(Project Visual Code),为低代码开发提供全面基于云的应用平台.通过这一创新化的平台,客户可根据业 ...

最新文章

  1. 1.6 Java数组也是一种数据类型
  2. 2009计算机网络考研大题,2009年计算机考研统考真题网络部分分析
  3. sqlserver date类型和字符串比较_VB编程基本数据类型完整剖析
  4. 5c用计算机怎么打,再一次谈谈%5c暴库的利用 -电脑资料
  5. Python---列表与元组
  6. File类与FileInfo类
  7. SQL系列(二)—— 查询(select)
  8. Python 定时任务的几种实现方式
  9. 根据后缀名/扩展名获取content-type/Mime类型
  10. G-sensor概述及常用概念整理【转】
  11. 原始分布式架构服务探索的得与失
  12. 【速成MSP430f149】电赛期间学习MSP430f149笔记
  13. Premiere Pro cc 2019 全面使用教程(非常简单)
  14. VUE vue Expected Object, Function, got String with value “xxx;
  15. greys在线问题诊断工具
  16. 人证核验终端设备技术
  17. 诗琳通:中泰友谊使者,曾在汶川地震时曾为汶川灾区捐款1100万
  18. 服务器配置和部署(待完善)
  19. 海量数据处理之 Bit-map 详细讲解
  20. Oracle 11g安装报错You do not have sufficient permissions to access the inventory

热门文章

  1. python官方的扩展索引_Python列表操作与深浅拷贝(6)——列表索引、查询、修改、扩展...
  2. atoi函数_每日一道 LeetCode (50):字符串转换整数 (atoi)
  3. c语言variant是什么变量,介绍一些常用数据类型的使用。先定义一些常见类型变量借以.doc...
  4. 【机器学习-数据科学】第二节:ipython开发环境搭建以及pandas快速入门
  5. python怎么给画布填上颜色_python numpy matplotlib画小方块填充背景色和添加不同色彩的文字...
  6. Python中查找包含它的列表元素的索引,index报错!!!
  7. python历史以及基础知识
  8. 【美团语音交互部】 NLP/知识图谱/语音识别等算法职位开放招聘!
  9. 追剧计划第三弹!UC Berkeley出品,全栈深度学习!
  10. 神经网络激活函数=生物转换器?