前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >牛逼了!Scikit-learn 0.22新版本发布,新功能更加方便

牛逼了!Scikit-learn 0.22新版本发布,新功能更加方便

作者头像
Python数据科学
发布2019-12-18 09:58:59
1.3K0
发布2019-12-18 09:58:59
举报

作者:xiaoyu,数据爱好者 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
本文参与 腾讯云自媒体分享计划,分享自微信公众号。
原始发表:2019-12-06,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 Python数据科学 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • ▍预计算的稀疏近邻图
  • ▍安装
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档