开始入门#
本指南旨在阐述 scikit-learn
提供的一些主要功能。它假设您对机器学习实践(模型拟合、预测、交叉验证等)有非常基本的了解。有关安装 scikit-learn
的说明,请参阅我们的安装指南。
Scikit-learn
是一个支持有监督学习和无监督学习的开源机器学习库。它还提供了用于模型拟合、数据预处理、模型选择、模型评估以及许多其他实用工具。
拟合与预测:估计器基础#
Scikit-learn
提供了数十种内置机器学习算法和模型,称为估计器。每个估计器都可以使用其fit方法拟合到一些数据。
这是一个简单示例,我们将一个RandomForestClassifier
拟合到一些非常基础的数据
>>> from sklearn.ensemble import RandomForestClassifier
>>> clf = RandomForestClassifier(random_state=0)
>>> X = [[ 1, 2, 3], # 2 samples, 3 features
... [11, 12, 13]]
>>> y = [0, 1] # classes of each sample
>>> clf.fit(X, y)
RandomForestClassifier(random_state=0)
fit方法通常接受2个输入
样本矩阵(或设计矩阵)X。
X
的大小通常是(n_samples, n_features)
,这意味着样本表示为行,特征表示为列。目标值y,回归任务中是实数,分类任务中是整数(或任何其他离散值集)。对于无监督学习任务,无需指定
y
。y
通常是一个一维数组,其中第i
个条目对应于X
中第i
个样本(行)的目标。
X
和 y
通常期望是 NumPy 数组或等效的类数组数据类型,尽管某些估计器也支持其他格式,例如稀疏矩阵。
一旦估计器拟合完成,它就可以用于预测新数据的目标值。您无需重新训练估计器
>>> clf.predict(X) # predict classes of the training data
array([0, 1])
>>> clf.predict([[4, 5, 6], [14, 15, 16]]) # predict classes of new data
array([0, 1])
您可以查看选择正确的估计器,了解如何为您的用例选择合适的模型。
转换器和预处理器#
机器学习工作流通常由不同部分组成。典型的管道包括转换或填充数据的预处理步骤,以及预测目标值的最终预测器。
在 scikit-learn
中,预处理器和转换器遵循与估计器对象相同的 API(它们实际上都继承自相同的 BaseEstimator
类)。转换器对象没有predict方法,而是有一个transform方法,该方法输出新的转换后样本矩阵 X
>>> from sklearn.preprocessing import StandardScaler
>>> X = [[0, 15],
... [1, -10]]
>>> # scale data according to computed scaling values
>>> StandardScaler().fit(X).transform(X)
array([[-1., 1.],
[ 1., -1.]])
有时,您希望对不同的特征应用不同的转换:ColumnTransformer就是为此类用例而设计的。
管道:链接预处理器和估计器#
转换器和估计器(预测器)可以组合成一个统一的对象:Pipeline
。管道提供了与普通估计器相同的 API:它可以使用 fit
和 predict
进行拟合和预测。正如我们稍后将看到的,使用管道还可以防止数据泄露,即训练数据中泄露一些测试数据。
在以下示例中,我们加载 Iris 数据集,将其分成训练集和测试集,并计算管道在测试数据上的准确率得分。
>>> from sklearn.preprocessing import StandardScaler
>>> from sklearn.linear_model import LogisticRegression
>>> from sklearn.pipeline import make_pipeline
>>> from sklearn.datasets import load_iris
>>> from sklearn.model_selection import train_test_split
>>> from sklearn.metrics import accuracy_score
...
>>> # create a pipeline object
>>> pipe = make_pipeline(
... StandardScaler(),
... LogisticRegression()
... )
...
>>> # load the iris dataset and split it into train and test sets
>>> X, y = load_iris(return_X_y=True)
>>> X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=0)
...
>>> # fit the whole pipeline
>>> pipe.fit(X_train, y_train)
Pipeline(steps=[('standardscaler', StandardScaler()),
('logisticregression', LogisticRegression())])
>>> # we can now use it like any other estimator
>>> accuracy_score(pipe.predict(X_test), y_test)
0.97...
模型评估#
将模型拟合到某些数据并不意味着它在新数据上也会表现良好。这需要直接进行评估。我们刚刚看到了train_test_split
辅助函数,它将数据集分成训练集和测试集,但 scikit-learn
提供了许多其他用于模型评估的工具,特别是用于交叉验证的工具。
我们在这里简要展示如何使用cross_validate
辅助函数执行5折交叉验证过程。请注意,也可以手动迭代折叠、使用不同的数据分割策略以及使用自定义评分函数。有关更多详细信息,请参阅我们的用户指南。
>>> from sklearn.datasets import make_regression
>>> from sklearn.linear_model import LinearRegression
>>> from sklearn.model_selection import cross_validate
...
>>> X, y = make_regression(n_samples=1000, random_state=0)
>>> lr = LinearRegression()
...
>>> result = cross_validate(lr, X, y) # defaults to 5-fold CV
>>> result['test_score'] # r_squared score is high because dataset is easy
array([1., 1., 1., 1., 1.])
自动参数搜索#
所有估计器都有可调的参数(文献中常称为超参数)。估计器的泛化能力通常关键取决于几个参数。例如,一个RandomForestRegressor
有一个 n_estimators
参数,它决定了森林中树的数量,以及一个 max_depth
参数,它决定了每棵树的最大深度。通常,这些参数的确切值应该是什么并不清楚,因为它们取决于具体的数据。
Scikit-learn
提供了自动寻找最佳参数组合(通过交叉验证)的工具。在以下示例中,我们使用RandomizedSearchCV
对象在随机森林的参数空间中进行随机搜索。搜索完成后,RandomizedSearchCV
的行为就像一个已经用最佳参数集拟合过的RandomForestRegressor
。更多内容请参阅用户指南
>>> from sklearn.datasets import fetch_california_housing
>>> from sklearn.ensemble import RandomForestRegressor
>>> from sklearn.model_selection import RandomizedSearchCV
>>> from sklearn.model_selection import train_test_split
>>> from scipy.stats import randint
...
>>> X, y = fetch_california_housing(return_X_y=True)
>>> X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=0)
...
>>> # define the parameter space that will be searched over
>>> param_distributions = {'n_estimators': randint(1, 5),
... 'max_depth': randint(5, 10)}
...
>>> # now create a searchCV object and fit it to the data
>>> search = RandomizedSearchCV(estimator=RandomForestRegressor(random_state=0),
... n_iter=5,
... param_distributions=param_distributions,
... random_state=0)
>>> search.fit(X_train, y_train)
RandomizedSearchCV(estimator=RandomForestRegressor(random_state=0), n_iter=5,
param_distributions={'max_depth': ...,
'n_estimators': ...},
random_state=0)
>>> search.best_params_
{'max_depth': 9, 'n_estimators': 4}
>>> # the search object now acts like a normal random forest estimator
>>> # with max_depth=9 and n_estimators=4
>>> search.score(X_test, y_test)
0.73...
下一步#
我们简要介绍了估计器拟合与预测、预处理步骤、管道、交叉验证工具和自动超参数搜索。本指南应能让您对该库的一些主要功能有所了解,但 scikit-learn
还有更多内容!
有关我们提供的所有工具的详细信息,请参阅我们的用户指南。您还可以在API 参考中找到公共 API 的详尽列表。
您还可以查看我们的众多示例,它们阐述了 scikit-learn
在许多不同上下文中的使用。