注意
Go to the end to download the full example code or to run this example in your browser via JupyterLite or Binder.
scikit-learn 0.24 版本亮点#
我们很高兴地宣布发布 scikit-learn 0.24 版本!此版本中添加了许多错误修复和改进,以及一些新的关键功能。下面我们将详细介绍此版本的一些主要功能。 有关所有更改的详尽列表,请参阅发布说明。
要安装最新版本(使用 pip)
pip install --upgrade scikit-learn
或使用 conda
conda install -c conda-forge scikit-learn
用于超参数调优的连续减半(Successive Halving)估计器#
连续减半(Successive Halving)是一种最先进的方法,现在可用于探索参数空间并找出它们的最佳组合。HalvingGridSearchCV 和 HalvingRandomSearchCV 可以作为 GridSearchCV 和 RandomizedSearchCV 的直接替代品使用。连续减半是一个迭代选择过程,如下图所示。第一次迭代使用少量资源运行,其中资源通常对应于训练样本的数量,但也可是任意整数参数,例如随机森林中的 n_estimators。只有一部分参数候选者被选中用于下一次迭代,下一次迭代将分配增加的资源量运行。只有一部分候选者会持续到迭代过程结束,得分最高的参数候选者就是最后一次迭代中得分最高的那个。
在用户指南中了解更多信息(注:连续减半估计器仍然是实验性功能)。
import numpy as np
from scipy.stats import randint
from sklearn.datasets import make_classification
from sklearn.ensemble import RandomForestClassifier
from sklearn.experimental import enable_halving_search_cv # noqa: F401
from sklearn.model_selection import HalvingRandomSearchCV
rng = np.random.RandomState(0)
X, y = make_classification(n_samples=700, random_state=rng)
clf = RandomForestClassifier(n_estimators=10, random_state=rng)
param_dist = {
"max_depth": [3, None],
"max_features": randint(1, 11),
"min_samples_split": randint(2, 11),
"bootstrap": [True, False],
"criterion": ["gini", "entropy"],
}
rsh = HalvingRandomSearchCV(
estimator=clf, param_distributions=param_dist, factor=2, random_state=rng
)
rsh.fit(X, y)
rsh.best_params_
{'bootstrap': True, 'criterion': 'gini', 'max_depth': None, 'max_features': 10, 'min_samples_split': 10}
HistGradientBoosting 估计器对分类特征的原生支持#
HistGradientBoostingClassifier 和 HistGradientBoostingRegressor 现在原生支持分类特征:它们可以考虑对非有序的分类数据进行分割。在用户指南中了解更多信息。
该图显示,对分类特征的新原生支持所导致的拟合时间与将类别视为有序量(即简单的序数编码)的模型相当。原生支持也比独热编码和序数编码更具表达性。然而,要使用新的 categorical_features 参数,仍然需要在管道中对数据进行预处理,如本示例所示。
HistGradientBoosting 估计器的性能改进#
ensemble.HistGradientBoostingRegressor 和 ensemble.HistGradientBoostingClassifier 在调用 fit 期间的内存占用已得到显着改善。此外,直方图初始化现在是并行进行的,这会带来轻微的速度改进。在基准页面上查看更多信息。
新的自训练元估计器#
现在可以使用基于 Yarowski 算法的新自训练实现,它适用于任何实现了 predict_proba 的分类器。子分类器将表现为半监督分类器,允许它从未标记的数据中学习。在用户指南中了解更多信息。
import numpy as np
from sklearn import datasets
from sklearn.semi_supervised import SelfTrainingClassifier
from sklearn.svm import SVC
rng = np.random.RandomState(42)
iris = datasets.load_iris()
random_unlabeled_points = rng.rand(iris.target.shape[0]) < 0.3
iris.target[random_unlabeled_points] = -1
svc = SVC(probability=True, gamma="auto")
self_training_model = SelfTrainingClassifier(svc)
self_training_model.fit(iris.data, iris.target)
新的 SequentialFeatureSelector 转换器#
一种新的用于选择特征的迭代转换器现已可用:SequentialFeatureSelector。顺序特征选择可以一次添加一个特征(前向选择)或从可用特征列表中删除特征(后向选择),具体取决于交叉验证分数的最大化。请参阅用户指南。
from sklearn.datasets import load_iris
from sklearn.feature_selection import SequentialFeatureSelector
from sklearn.neighbors import KNeighborsClassifier
X, y = load_iris(return_X_y=True, as_frame=True)
feature_names = X.columns
knn = KNeighborsClassifier(n_neighbors=3)
sfs = SequentialFeatureSelector(knn, n_features_to_select=2)
sfs.fit(X, y)
print(
"Features selected by forward sequential selection: "
f"{feature_names[sfs.get_support()].tolist()}"
)
Features selected by forward sequential selection: ['sepal length (cm)', 'petal width (cm)']
新的 PolynomialCountSketch 核近似函数#
新的 PolynomialCountSketch 在与线性模型一起使用时可以近似特征空间的 polynomial 展开,但比 PolynomialFeatures 使用更少的内存。
from sklearn.datasets import fetch_covtype
from sklearn.kernel_approximation import PolynomialCountSketch
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import train_test_split
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import MinMaxScaler
X, y = fetch_covtype(return_X_y=True)
pipe = make_pipeline(
MinMaxScaler(),
PolynomialCountSketch(degree=2, n_components=300),
LogisticRegression(max_iter=1000),
)
X_train, X_test, y_train, y_test = train_test_split(
X, y, train_size=5000, test_size=10000, random_state=42
)
pipe.fit(X_train, y_train).score(X_test, y_test)
0.7361
作为比较,这是相同数据的线性基准分数
linear_baseline = make_pipeline(MinMaxScaler(), LogisticRegression(max_iter=1000))
linear_baseline.fit(X_train, y_train).score(X_test, y_test)
0.7141
个体条件期望图(Individual Conditional Expectation plots)#
一种新的局部依赖图现已可用:个体条件期望(ICE)图。ICE 图分别可视化每个样本的预测对某一特征的依赖关系,每个样本用一条线表示。请参阅用户指南
from sklearn.datasets import fetch_california_housing
from sklearn.ensemble import RandomForestRegressor
# from sklearn.inspection import plot_partial_dependence
from sklearn.inspection import PartialDependenceDisplay
X, y = fetch_california_housing(return_X_y=True, as_frame=True)
features = ["MedInc", "AveOccup", "HouseAge", "AveRooms"]
est = RandomForestRegressor(n_estimators=10)
est.fit(X, y)
# plot_partial_dependence has been removed in version 1.2. From 1.2, use
# PartialDependenceDisplay instead.
# display = plot_partial_dependence(
display = PartialDependenceDisplay.from_estimator(
est,
X,
features,
kind="individual",
subsample=50,
n_jobs=3,
grid_resolution=20,
random_state=0,
)
display.figure_.suptitle(
"Partial dependence of house value on non-location features\n"
"for the California housing dataset, with BayesianRidge"
)
display.figure_.subplots_adjust(hspace=0.3)

DecisionTreeRegressor 的新泊松分割标准#
泊松回归估计的集成从 0.23 版本开始。 DecisionTreeRegressor 现在支持新的 'poisson' 分割标准。如果您的目标是计数或频率,设置 criterion="poisson" 可能是一个不错的选择。
import numpy as np
from sklearn.model_selection import train_test_split
from sklearn.tree import DecisionTreeRegressor
n_samples, n_features = 1000, 20
rng = np.random.RandomState(0)
X = rng.randn(n_samples, n_features)
# positive integer target correlated with X[:, 5] with many zeros:
y = rng.poisson(lam=np.exp(X[:, 5]) / 2)
X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=rng)
regressor = DecisionTreeRegressor(criterion="poisson", random_state=0)
regressor.fit(X_train, y_train)
新的文档改进#
为了持续改进对机器学习实践的理解,添加了新的示例和文档页面
关于常见陷阱和推荐实践的新部分,
一个示例,说明如何统计比较使用
GridSearchCV评估的模型的性能,一个关于如何解释线性模型系数的示例,
一个比较主成分回归(Principal Component Regression)和偏最小二乘法(Partial Least Squares)的示例。
脚本总运行时间: (0 minutes 14.909 seconds)
相关示例