Scikit-Learn 教程:如何安装和 Scikit-Learn 示例
⚡ 智能摘要
Scikit-learn 是开源的 Python 该库涵盖了预处理、分类、回归、聚类和模型选择,并采用单一一致的估计器接口,从而保持从原始数据到评分预测的完整机器学习工作流程简洁、易读且可重现。
什么是 Scikit-learn?
Scikit学习 是开源的 Python 图书馆 机器学习它支持诸如 KNN、梯度提升、随机森林和 SVM 等成熟算法,并且构建于……之上。 NumPy的 以及 SciPy。Scikit-learn 被广泛应用于 Kaggle 竞赛以及众多知名科技公司。它涵盖了预处理、降维、分类、回归、聚类和模型选择等功能。
Scikit-learn 拥有开源库中最好的文档之一。它甚至提供了一个交互式的估计器图表“选择合适的估计器”,引导你从数据集的大小出发,找到一系列值得尝试的算法。
下图展示了 Scikit-learn 的工作原理。
Scikit-learn 使用起来并不难,而且效果出色。但是,它是在 CPU 上进行训练的:任务通过 `n_jobs` 参数在多个核心上并行执行,而不是在 GPU 上执行。虽然可以用它运行深度学习算法,但很少能达到最佳效果,尤其是在你已经熟悉TensorFlow 的情况下。
如何下载和安装 Scikit-learn
现在在这个 Python 本教程将教您如何下载和安装 Scikit-learn:
选项 1:AWS
scikit-learn 可以在 AWS 上使用。预装了 scikit-learn 的 Docker 镜像可以完全省去安装工作。
要安装开发者版本,请在内部运行以下命令 Jupyter:
import sys !{sys.executable} -m pip install git+git://github.com/scikit-learn/scikit-learn.git
选项 2:Mac 或 Windows 使用 Anaconda
要了解 Anaconda 的安装,请参阅如何下载和安装 TensorFlow。
在编写本教程时,scikit-learn 的开发者发布了一个开发版本,修复了当时正式版中存在的问题,因此以下步骤均基于该开发版本。如今,在新机器上,当前的稳定版本已经包含了本文使用的所有转换器,只需运行`pip install -U scikit-learn`即可。
如何使用 Conda 环境安装 scikit-learn
如果您使用 conda 环境安装了 scikit-learn,请按照以下步骤更新到 0.20 版本。
步骤 1)激活 TensorFlow 环境
source activate hello-tf
步骤 2)使用 conda 命令移除 scikit-learn
conda remove scikit-learn
步骤 3)安装开发者版本
安装 scikit-learn 开发版本以及必要的库。
conda install -c anaconda git
pip install Cython
pip install h5py
pip install git+git://github.com/scikit-learn/scikit-learn.git
注意: Windows 用户需要 Microsoft 视觉 C++ 14. 你可以得到它 开始.
机器学习的 Scikit-Learn 示例
本 Scikit 教程分为两部分:
- 使用 scikit-learn 进行机器学习
- 如何通过 LIME 信任你的模型
第一部分详细介绍了如何构建管道、创建模型和调整超参数,而第二部分则涵盖了模型解释。
步骤1)导入数据
在本 Scikit-learn 教程中,您将使用成人人口普查数据集。
以下代码直接从 UCI 机器学习库读取文件,无需手动下载。如果您对描述性统计数据感兴趣,建议查看“深入分析”和“概览”工具。请参阅此教程了解更多关于“深入分析”和“概览”的信息。
您可以使用 pandas 导入数据集。请注意,您需要将连续变量转换为浮点格式。
该数据集包含八个分类变量,列于 CATE_FEATURES 中:
- 工人阶级
- 教育
- 婚姻
- 占用
- 关系
- 种族
- 性别
- 祖国
它还包括六个连续变量,列于 CONTI_FEATURES 中:
- 年龄
- 风车
- 教育编号
- 资本收益
- 资本损失
- hours_week
此处列表为手动填写,以便您更清楚地了解哪些列正在使用。构建分类列或连续列列表的更快捷方法是:
## List Categorical CATE_FEATURES = df_train.iloc[:,:-1].select_dtypes('object').columns print(CATE_FEATURES) ## List continuous CONTI_FEATURES = df_train._get_numeric_data() print(CONTI_FEATURES)
以下是导入数据的代码:
# Import dataset import pandas as pd ## Define path data COLUMNS = ['age','workclass', 'fnlwgt', 'education', 'education_num', 'marital', 'occupation', 'relationship', 'race', 'sex', 'capital_gain', 'capital_loss', 'hours_week', 'native_country', 'label'] ### Define continuous list CONTI_FEATURES = ['age', 'fnlwgt','capital_gain', 'education_num', 'capital_loss', 'hours_week'] ### Define categorical list CATE_FEATURES = ['workclass', 'education', 'marital', 'occupation', 'relationship', 'race', 'sex', 'native_country'] ## Prepare the data features = ['age','workclass', 'fnlwgt', 'education', 'education_num', 'marital', 'occupation', 'relationship', 'race', 'sex', 'capital_gain', 'capital_loss', 'hours_week', 'native_country'] PATH = "https://archive.ics.uci.edu/ml/machine-learning-databases/adult/adult.data" df_train = pd.read_csv(PATH, skipinitialspace=True, names = COLUMNS, index_col=False) df_train[CONTI_FEATURES] =df_train[CONTI_FEATURES].astype('float64') df_train.describe()
对框架调用 describe() 函数会返回六个连续列的汇总统计信息:
| 年龄 | 风车 | 教育编号 | 资本收益 | 资本损失 | hours_week | |
|---|---|---|---|---|---|---|
| 数 | 32561.000000 | 3.256100e + 04 | 32561.000000 | 32561.000000 | 32561.000000 | 32561.000000 |
| 意味着 | 38.581647 | 1.897784e + 05 | 10.080679 | 1077.648844 | 87.303830 | 40.437456 |
| STD | 13.640433 | 1.055500e + 05 | 2.572720 | 7385.292085 | 402.960219 | 12.347429 |
| 分钟 | 17.000000 | 1.228500e + 04 | 1.000000 | 0.000000 | 0.000000 | 1.000000 |
| 25% | 28.000000 | 1.178270e + 05 | 9.000000 | 0.000000 | 0.000000 | 40.000000 |
| 50% | 37.000000 | 1.783560e + 05 | 10.000000 | 0.000000 | 0.000000 | 40.000000 |
| 75% | 48.000000 | 2.370510e + 05 | 12.000000 | 0.000000 | 0.000000 | 45.000000 |
| 最大 | 90.000000 | 1.484705e + 06 | 16.000000 | 99999.000000 | 4356.000000 | 99.000000 |
您可以查看 native_country 特征的唯一值数量。只有一个家庭来自荷兰。该家庭不提供任何信息,会在训练过程中抛出错误。
df_train.native_country.value_counts()
United-States 29170 Mexico 643 ? 583 Philippines 198 Germany 137 Canada 121 Puerto-Rico 114 El-Salvador 106 India 100 Cuba 95 England 90 Jamaica 81 South 80 China 75 Italy 73 Dominican-Republic 70 Vietnam 67 Guatemala 64 Japan 62 Poland 60 Columbia 59 Taiwan 51 Haiti 44 Iran 43 Portugal 37 Nicaragua 34 Peru 31 France 29 Greece 29 Ecuador 28 Ireland 24 Hong 20 Cambodia 19 Trinadad&Tobago 19 Thailand 18 Laos 18 Yugoslavia 16 Outlying-US(Guam-USVI-etc) 14 Honduras 13 Hungary 13 Scotland 12 Holand-Netherlands 1 Name: native_country, dtype: int64
您可以将这行无意义的数据从数据集中排除:
## Drop Netherland, because only one row df_train = df_train[df_train.native_country != "Holand-Netherlands"]
接下来,将连续特征的位置存储在列表中。在下一步构建管道时,您将需要它。
下面的代码循环遍历 CONTI_FEATURES 中的所有列名,读取每个位置(即其列号),并将其附加到名为 conti_features 的列表中。
## Get the column index of the categorical features conti_features = [] for i in CONTI_FEATURES: position = df_train.columns.get_loc(i) conti_features.append(position) print(conti_features)
[0, 2, 10, 4, 11, 12]
下一个模块对分类变量执行相同的操作。
## Get the column index of the categorical features categorical_features = [] for i in CATE_FEATURES: position = df_train.columns.get_loc(i) categorical_features.append(position) print(categorical_features)
[1, 3, 5, 6, 7, 8, 9, 13]
现在来看数据集本身。每个分类特征都是一个字符串,而模型不能直接输入字符串值,因此必须使用虚拟变量对数据集进行转换。
df_train.head(5)
实际上,每个要素中的每个组都需要一列。首先,运行以下代码计算所需的列总数。
print(df_train[CATE_FEATURES].nunique(), 'There are',sum(df_train[CATE_FEATURES].nunique()), 'groups in the whole dataset')
workclass 9
education 16
marital 7
occupation 15
relationship 6
race 5
sex 2
native_country 41
dtype: int64 There are 101 groups in the whole dataset
如上所示,整个数据集包含 101 个组。仅工作类别特征就包含 9 个组。您可以使用以下代码列出组的名称;unique() 函数返回每个分类特征的不同值。
for i in CATE_FEATURES: print(df_train[i].unique())
['State-gov' 'Self-emp-not-inc' 'Private' 'Federal-gov' 'Local-gov' '?' 'Self-emp-inc' 'Without-pay' 'Never-worked'] ['Bachelors' 'HS-grad' '11th' 'Masters' '9th' 'Some-college' 'Assoc-acdm' 'Assoc-voc' '7th-8th' 'Doctorate' 'Prof-school' '5th-6th' '10th' '1st-4th' 'Preschool' '12th'] ['Never-married' 'Married-civ-spouse' 'Divorced' 'Married-spouse-absent' 'Separated' 'Married-AF-spouse' 'Widowed'] ['Adm-clerical' 'Exec-managerial' 'Handlers-cleaners' 'Prof-specialty' 'Other-service' 'Sales' 'Craft-repair' 'Transport-moving' 'Farming-fishing' 'Machine-op-inspct' 'Tech-support' '?' 'Protective-serv' 'Armed-Forces' 'Priv-house-serv'] ['Not-in-family' 'Husband' 'Wife' 'Own-child' 'Unmarried' 'Other-relative'] ['White' 'Black' 'Asian-Pac-Islander' 'Amer-Indian-Eskimo' 'Other'] ['Male' 'Female'] ['United-States' 'Cuba' 'Jamaica' 'India' '?' 'Mexico' 'South' 'Puerto-Rico' 'Honduras' 'England' 'Canada' 'Germany' 'Iran' 'Philippines' 'Italy' 'Poland' 'Columbia' 'Cambodia' 'Thailand' 'Ecuador' 'Laos' 'Taiwan' 'Haiti' 'Portugal' 'Dominican-Republic' 'El-Salvador' 'France' 'Guatemala' 'China' 'Japan' 'Yugoslavia' 'Peru' 'Outlying-US(Guam-USVI-etc)' 'Scotland' 'Trinadad&Tobago' 'Greece' 'Nicaragua' 'Vietnam' 'Hong' 'Ireland' 'Hungary']
因此,训练数据集将包含 101 + 6 列:独热分组加上六个连续特征。
Scikit-learn 可以分两步完成转换:
- 将字符串转换为 ID。例如,“State-gov”转换为 ID 1,“Self-emp-not-inc”转换为 ID 2,依此类推。LabelEncoder 会自动完成此操作。
- 将每个 ID 转置到新列中。数据集包含 101 个组 ID,因此将有 101 列来捕获每个类别特征组。Scikit-learn 提供了 OneHotEncoder 来进行此操作。
步骤2)创建训练/测试集
现在数据集已准备就绪,将其按 80/20 的比例分割:80% 用于训练集,20% 用于测试集。
您可以使用 `train_test_split` 函数。第一个参数是特征数据框,第二个参数是标签。您可以使用 `test_size` 函数设置测试集的大小。
from sklearn.model_selection import train_test_split X_train, X_test, y_train, y_test = train_test_split(df_train[features], df_train.label, test_size = 0.2, random_state=0) X_train.head(5) print(X_train.shape, X_test.shape)
(26048, 14) (6512, 14)
步骤 3)构建管道
该数据管道使向模型提供一致的数据变得更加容易。其核心思想是将原始数据推送到一个对象中,该对象按顺序执行所有操作。
使用此数据集,您需要对连续变量进行标准化,并将分类变量进行转换。任何操作都可以在管道中完成:缺失值可以用均值或中位数替换,也可以创建新变量。
你有两种选择:要么将这两个过程硬编码到代码中,要么构建一个流水线。硬编码可能会将测试数据泄露到拟合统计数据中,并随着时间的推移造成数据不一致,因此构建流水线是更好的选择。
from sklearn.preprocessing import StandardScaler, OneHotEncoder, LabelEncoder from sklearn.compose import ColumnTransformer, make_column_transformer from sklearn.pipeline import make_pipeline from sklearn.linear_model import LogisticRegression
该流程在将数据输入逻辑分类器之前执行两个操作:
- 标准化变量:StandardScaler()
- 转换分类特征:OneHotEncoder(sparse=False)
这两个步骤都需要使用 `make_column_transformer` 函数来完成。本教程编写时,该函数尚未包含在 scikit-learn 的正式发布版本 (0.19) 中,因此使用了开发者构建版本;自 0.20 版本起,该函数已包含在所有稳定版本中。
`make_column_transformer` 函数很简单:您只需声明要转换的列以及要应用的转换。要标准化连续特征,您需要传递以下参数:
- conti_features,在 make_column_transformer 内部的 StandardScaler()
- conti_features:连续列的列表
- StandardScaler:标准化这些列
make_column_transformer 中的 OneHotEncoder 对象会自动对标签进行编码。
preprocess = make_column_transformer(
(conti_features, StandardScaler()),
### Need to be numeric not string to specify columns name
(categorical_features, OneHotEncoder(sparse=False))
)
版本说明:上面代码块中的两个参数已经发生变化。当前版本要求先指定转换器,再指定列,并且sparse在 scikit-learn 1.2 中被重命名为sparse_output,并在 1.4 中被移除,因此新代码应为OneHotEncoder(sparse_output=False)。
您可以使用 fit_transform 来测试该流程是否正常工作。输出结果的形状应为 26048, 107。
preprocess.fit_transform(X_train).shape
(26048, 107)
数据转换器已准备就绪。您可以使用 make_pipeline 创建管道,数据转换完成后,即可将其输入逻辑回归模型。
model = make_pipeline(
preprocess,
LogisticRegression())
使用 scikit-learn 训练模型非常简单:只需调用管道上的 fit 方法即可。您可以使用 score 方法打印准确率。
model.fit(X_train, y_train) print("logistic regression score: %f" % model.score(X_test, y_test))
logistic regression score: 0.850891
最后,您可以使用 predict_proba 函数预测类别,该函数会返回每个类别的概率。请注意,这两个概率之和为 1。
model.predict_proba(X_test)
array([[0.83576663, 0.16423337],
[0.94582765, 0.05417235],
[0.64760587, 0.35239413],
...,
[0.99639252, 0.00360748],
[0.02072181, 0.97927819],
[0.56781353, 0.43218647]])
步骤 4)在网格搜索中使用我们的管道
调整超参数(即决定模型结构的参数值)可能既繁琐又令人疲惫。
评估模型的一种方法是改变训练集的大小并测量其性能,重复此过程十次以观察得分的分布情况。但这需要大量的人工操作。
相反,scikit-learn 提供了一些函数,可以为您执行参数调整和交叉验证。
交叉验证
交叉验证是指在训练过程中,将训练集分成 n 份,并对模型进行 n 次评估。如果 cv 设置为 10,则模型将进行 10 次训练和评估。在每一轮中,分类器使用随机选择的九份数据进行训练,并将第十份数据用于评估。
网格搜索
每个分类器都有需要调整的超参数。您可以逐个尝试不同的值,也可以设置一个参数网格。scikit-learn 文档列出了逻辑分类器接受的所有参数。为了加快训练速度,本示例仅调整了控制正则化的 C 参数。C 值必须为正,较小的值会赋予正则化项更大的权重。
您可以使用 GridSearchCV 对象,该对象接受一个包含待调优超参数的字典。列出每个超参数,并在其后添加您想要尝试的值。要调优 C 参数,您可以这样写:
- 'logisticregression__C': [0.001, 0.01, 0.1, 1.0] — 参数名称前面是小写的分类器名称和两个下划线。
该模型将尝试四个不同的值:0.001、0.01、0.1 和 1。它使用 10 折交叉验证进行训练,即 cv=10。
from sklearn.model_selection import GridSearchCV # Construct the parameter grid param_grid = { 'logisticregression__C': [0.001, 0.01,0.1, 1.0], }
现在可以使用 GridSearchCV 和参数 grid 和 cv 来训练模型。
# Train the model grid_clf = GridSearchCV(model, param_grid, cv=10, iid=False) grid_clf.fit(X_train, y_train)
输出:
GridSearchCV(cv=10, error_score='raise-deprecating', estimator=Pipeline(memory=None, steps=[('columntransformer', ColumnTransformer(n_jobs=1, remainder='drop', transformer_weights=None, transformers=[('standardscaler', StandardScaler(copy=True, with_mean=True, with_std=True), [0, 2, 10, 4, 11, 12]), ('onehotencoder', OneHotEncoder(categorical_features=None, categories=None,...ty='l2', random_state=None, solver='liblinear', tol=0.0001, verbose=0, warm_start=False))]), fit_params=None, iid=False, n_jobs=1, param_grid={'logisticregression__C': [0.001, 0.01, 0.1, 1.0]}, pre_dispatch='2*n_jobs', refit=True, return_train_score='warn', scoring=None, verbose=0)
版本说明:此输出中显示的 iid参数在 scikit-learn 0.22 中已弃用,并在 0.24 中移除,因此在当前版本中应直接从 GridSearchCV 调用中删除。
要访问最佳参数,您可以使用 best_params_。
grid_clf.best_params_
输出:
{'logisticregression__C': 1.0}
使用四种不同的正则化值训练模型后,得到最优参数:
print("best logistic regression from grid search: %f" % grid_clf.best_estimator_.score(X_test, y_test))
网格搜索的最佳逻辑回归:0.850891
要访问预测概率:
grid_clf.best_estimator_.predict_proba(X_test)
array([[0.83576677, 0.16423323],
[0.9458291 , 0.0541709 ],
[0.64760416, 0.35239584],
...,
[0.99639224, 0.00360776],
[0.02072033, 0.97927967],
[0.56782222, 0.43217778]])
使用 scikit-learn 的 XGBoost 模型
现在来试试市面上最强大的分类器之一:XGBoost。它是随机森林算法的梯度提升改进版。其理论背景不在本文讨论范围之内。 Python 可以参考 Scikit 教程,但请记住,XGBoost 已经赢得了许多 Kaggle 竞赛。在中等规模的数据集上,它的性能可以与深度学习算法媲美,甚至更胜一筹。
由于分类器涉及大量参数,因此训练起来颇具挑战性。当然,您可以使用 GridSearchCV 来帮您选择合适的参数。
这里更好的选择是使用 RandomizedSearchCV。当网格很大时,GridSearchCV 的速度会变慢,因为每增加一个参数,搜索空间就会增大。而 RandomizedSearchCV 则在每次迭代中随机抽取每个超参数的值,因此 1,000 次迭代可以评估 1,000 种组合。除此之外,它的工作原理与 GridSearchCV 非常相似。
你需要导入 xgboost 库。如果该库未安装,请运行 `pip3 install xgboost`,或者从 `pip` 内部安装它。 Jupyter 笔记本内含:
use import sys
!{sys.executable} -m pip install xgboost
然后导入分类器和两个搜索辅助函数:
import xgboost from sklearn.model_selection import RandomizedSearchCV from sklearn.model_selection import StratifiedKFold
Scikit 的下一步 Python 本教程旨在指定要调整的参数。XGBoost 官方文档列出了所有参数。为了便于说明,这里我们仅列出需要调整的参数。 Python Sklearn 教程中只选择了两个超参数,每个超参数有两个值,因为 XGBoost 训练时间很长,每个额外的网格点都会增加等待时间。
params = {
'xgbclassifier__gamma': [0.5, 1],
'xgbclassifier__max_depth': [3, 4]
}
然后,您需要构建一个包含 XGBoost 分类器和 600 个估计器的新管道。n_estimators 本身是可调的,过高的值可能导致过拟合。您可以尝试其他值,但请注意,这可能需要数小时。其他所有参数均保持默认值。
model_xgb = make_pipeline(
preprocess,
xgboost.XGBClassifier(
n_estimators=600,
objective='binary:logistic',
silent=True,
nthread=1)
)
您可以使用分层 K 折交叉验证器来改进交叉验证。这里只使用了三折来加快计算速度,但会牺牲一些质量;在您的机器上,您可以将折数增加到 5 折或 10 折以获得更好的结果。模型训练经过四次迭代。
skf = StratifiedKFold(n_splits=3,
shuffle = True,
random_state = 1001)
random_search = RandomizedSearchCV(model_xgb,
param_distributions=params,
n_iter=4,
scoring='accuracy',
n_jobs=4,
cv=skf.split(X_train, y_train),
verbose=3,
random_state=1001)
随机搜索已准备就绪,您可以开始训练模型了。
#grid_xgb = GridSearchCV(model_xgb, params, cv=10, iid=False)
random_search.fit(X_train, y_train)
Fitting 3 folds for each of 4 candidates, totalling 12 fits
[CV] xgbclassifier__max_depth=3, xgbclassifier__gamma=0.5 ............
[CV] xgbclassifier__max_depth=3, xgbclassifier__gamma=0.5 ............
[CV] xgbclassifier__max_depth=3, xgbclassifier__gamma=0.5 ............
[CV] xgbclassifier__max_depth=4, xgbclassifier__gamma=0.5 ............
[CV] xgbclassifier__max_depth=3, xgbclassifier__gamma=0.5, score=0.8759645283888057, total= 1.0min
[CV] xgbclassifier__max_depth=4, xgbclassifier__gamma=0.5 ............
[CV] xgbclassifier__max_depth=3, xgbclassifier__gamma=0.5, score=0.8729701715996775, total= 1.0min
[CV] xgbclassifier__max_depth=3, xgbclassifier__gamma=0.5, score=0.8706519235199263, total= 1.0min
[CV] xgbclassifier__max_depth=4, xgbclassifier__gamma=0.5 ............
[CV] xgbclassifier__max_depth=3, xgbclassifier__gamma=1 ..............
[CV] xgbclassifier__max_depth=4, xgbclassifier__gamma=0.5, score=0.8735460094437406, total= 1.3min
[CV] xgbclassifier__max_depth=3, xgbclassifier__gamma=1 ..............
[CV] xgbclassifier__max_depth=3, xgbclassifier__gamma=1, score=0.8722791661868018, total= 57.7s
[CV] xgbclassifier__max_depth=3, xgbclassifier__gamma=1 ..............
[CV] xgbclassifier__max_depth=3, xgbclassifier__gamma=1, score=0.8753886905447426, total= 1.0min
[CV] xgbclassifier__max_depth=4, xgbclassifier__gamma=1 ..............
[CV] xgbclassifier__max_depth=4, xgbclassifier__gamma=0.5, score=0.8697304768486523, total= 1.3min
[CV] xgbclassifier__max_depth=4, xgbclassifier__gamma=1 ..............
[CV] xgbclassifier__max_depth=4, xgbclassifier__gamma=0.5, score=0.8740066797189912, total= 1.4min
[CV] xgbclassifier__max_depth=4, xgbclassifier__gamma=1 ..............
[CV] xgbclassifier__max_depth=3, xgbclassifier__gamma=1, score=0.8707671043538355, total= 1.0min
[CV] xgbclassifier__max_depth=4, xgbclassifier__gamma=1, score=0.8729701715996775, total= 1.2min
[Parallel(n_jobs=4)]: Done 10 out of 12 | elapsed: 3.6min remaining: 43.5s
[CV] xgbclassifier__max_depth=4, xgbclassifier__gamma=1, score=0.8736611770125533, total= 1.2min
[CV] xgbclassifier__max_depth=4, xgbclassifier__gamma=1, score=0.8692697535130154, total= 1.2min
[Parallel(n_jobs=4)]: Done 12 out of 12 | elapsed: 3.6min finished /Users/Thomas/anaconda3/envs/hello-tf/lib/python3.6/site-packages/sklearn/model_selection/_search.py:737: DeprecationWarning: The default of the `iid` parameter will change from True to False in version 0.22 and will be removed in 0.24. This will change numeric results when test-set sizes are unequal. DeprecationWarning)
RandomizedSearchCV(cv=<generator object _BaseKFold.split at 0x1101eb830>,
error_score='raise-deprecating',
estimator=Pipeline(memory=None,
steps=[('columntransformer', ColumnTransformer(n_jobs=1, remainder='drop', transformer_weights=None,
transformers=[('standardscaler', StandardScaler(copy=True, with_mean=True, with_std=True), [0, 2, 10, 4, 11, 12]), ('onehotencoder', OneHotEncoder(categorical_features=None, categories=None,...
reg_alpha=0, reg_lambda=1, scale_pos_weight=1, seed=None,
silent=True, subsample=1))]),
fit_params=None, iid='warn', n_iter=4, n_jobs=4,
param_distributions={'xgbclassifier__gamma': [0.5, 1], 'xgbclassifier__max_depth': [3, 4]},
pre_dispatch='2*n_jobs', random_state=1001, refit=True,
return_train_score='warn', scoring='accuracy', verbose=3)
如您所见,XGBoost 的得分优于之前的逻辑回归。
print("Best parameter", random_search.best_params_) print("best logistic regression from grid search: %f" % random_search.best_estimator_.score(X_test, y_test))
Best parameter {'xgbclassifier__max_depth': 3, 'xgbclassifier__gamma': 0.5}
best logistic regression from grid search: 0.873157
random_search.best_estimator_.predict(X_test)
array(['<=50K', '<=50K', '<=50K', ..., '<=50K', '>50K', '<=50K'], dtype=object)
在 scikit-learn 中使用 MLPClassifier 创建 DNN
最后,您可以使用 scikit-learn 本身来训练神经网络。方法与其他分类器相同,估计器为 MLPClassifier。
from sklearn.neural_network import MLPClassifier
以下网络定义如下:
- Adam 求解器
- ReLU激活函数
- Alpha = 0.0001
- 批量大小为150
- 两个隐藏层分别有 200 个和 100 个神经元
model_dnn = make_pipeline(
preprocess,
MLPClassifier(solver='adam',
alpha=0.0001,
activation='relu',
batch_size=150,
hidden_layer_sizes=(200, 100),
random_state=1))
你可以通过改变层数来改进模型。
model_dnn.fit(X_train, y_train) print("DNN regression score: %f" % model_dnn.score(X_test, y_test))
DNN 回归分数:0.821253
LIME:相信你的模型
既然你已经有了一个不错的模型,接下来就需要一种方法来信任它。机器学习算法,尤其是随机森林和神经网络,被称为“黑箱模型”:它们能运行,但没人知道为什么。
三位研究人员开发了一种工具,可以展示计算机如何得出预测结果。他们的论文题为《我为什么要相信你?》,他们发布的算法被称为局部可解释模型无关解释(LIME)。
举个例子。有时候,你无法确定机器学习的预测结果是否可信。医生不能仅仅因为诊断结果是由计算机生成的就接受它,而且在将模型投入实际应用之前,你需要知道它是否可靠。
想象一下,即使对于像神经网络、随机森林或具有任意核函数的支持向量机这样复杂的模型,也能清楚地看到任何分类器做出预测的原因。当预测背后的原因清晰可见时,信任预测就变得容易得多;同样,判断何时不该信任某个模型也变得容易得多。LIME 会告诉你哪些特征驱动了分类器的决策。
资料准备
要使用 LIME 运行,需要更改一些设置。 Python首先,在终端中使用 pip install lime 安装 lime。
Lime 使用 LimeTabularExplainer 对象在局部范围内近似模型。此对象需要:
- 数据集 NumPy的 格式
- 特征的名称:feature_names
- 课程名称:class_names
- 分类特征列的索引:categorical_features
- 每个分类特征的组名称:categorical_names
创建 NumPy 训练集
您可以非常轻松地将 pandas 中的 df_train 复制并转换为 NumPy 格式。
df_train.head(5)
# Create numpy data
df_lime = df_train
df_lime.head(3)
获取班级名称
可以通过 unique() 函数访问该标签。您应该看到:
- '<= 50K'
- '> 50K'
# Get the class name
class_names = df_lime.label.unique()
class_names
array(['<=50K', '>50K'], dtype=object)
对分类特征列进行索引
使用之前学到的方法获取每个组的名称。用 LabelEncoder 对标签进行编码,并对每个类别特征重复此操作。
## import sklearn.preprocessing as preprocessing categorical_names = {} for feature in CATE_FEATURES: le = preprocessing.LabelEncoder() le.fit(df_lime[feature]) df_lime[feature] = le.transform(df_lime[feature]) categorical_names[feature] = le.classes_ print(categorical_names)
{'workclass': array(['?', 'Federal-gov', 'Local-gov', 'Never-worked', 'Private',
'Self-emp-inc', 'Self-emp-not-inc', 'State-gov', 'Without-pay'],
dtype=object), 'education': array(['10th', '11th', '12th', '1st-4th', '5th-6th', '7th-8th', '9th',
'Assoc-acdm', 'Assoc-voc', 'Bachelors', 'Doctorate', 'HS-grad',
'Masters', 'Preschool', 'Prof-school', 'Some-college'],
dtype=object), 'marital': array(['Divorced', 'Married-AF-spouse', 'Married-civ-spouse',
'Married-spouse-absent', 'Never-married', 'Separated', 'Widowed'],
dtype=object), 'occupation': array(['?', 'Adm-clerical', 'Armed-Forces', 'Craft-repair',
'Exec-managerial', 'Farming-fishing', 'Handlers-cleaners',
'Machine-op-inspct', 'Other-service', 'Priv-house-serv',
'Prof-specialty', 'Protective-serv', 'Sales', 'Tech-support',
'Transport-moving'], dtype=object), 'relationship': array(['Husband', 'Not-in-family', 'Other-relative', 'Own-child',
'Unmarried', 'Wife'], dtype=object), 'race': array(['Amer-Indian-Eskimo', 'Asian-Pac-Islander', 'Black', 'Other',
'White'], dtype=object), 'sex': array(['Female', 'Male'], dtype=object), 'native_country': array(['?', 'Cambodia', 'Canada', 'China', 'Columbia', 'Cuba',
'Dominican-Republic', 'Ecuador', 'El-Salvador', 'England',
'France', 'Germany', 'Greece', 'Guatemala', 'Haiti', 'Honduras',
'Hong', 'Hungary', 'India', 'Iran', 'Ireland', 'Italy', 'Jamaica',
'Japan', 'Laos', 'Mexico', 'Nicaragua',
'Outlying-US(Guam-USVI-etc)', 'Peru', 'Philippines', 'Poland',
'Portugal', 'Puerto-Rico', 'Scotland', 'South', 'Taiwan',
'Thailand', 'Trinadad&Tobago', 'United-States', 'Vietnam',
'Yugoslavia'], dtype=object)}
df_lime.dtypes
age float64 workclass int64 fnlwgt float64 education int64 education_num float64 marital int64 occupation int64 relationship int64 race int64 sex int64 capital_gain float64 capital_loss float64 hours_week float64 native_country int64 label object dtype: object
现在数据集已准备就绪,您可以构建下面 Scikit-learn 示例中所示的不同数据集。此处数据在管道之外进行转换,以避免 LIME 出现错误:传递给 LimeTabularExplainer 的训练集必须是不包含字符串的 NumPy 数组,而上述方法已经生成了一个这样的数组。
from sklearn.model_selection import train_test_split X_train_lime, X_test_lime, y_train_lime, y_test_lime = train_test_split(df_lime[features], df_lime.label, test_size = 0.2, random_state=0) X_train_lime.head(5)
您可以使用 XGBoost 找到的最佳参数来构建管道。
model_xgb = make_pipeline(
preprocess,
xgboost.XGBClassifier(max_depth = 3,
gamma = 0.5,
n_estimators=600,
objective='binary:logistic',
silent=True,
nthread=1))
model_xgb.fit(X_train_lime, y_train_lime)
/Users/Thomas/anaconda3/envs/hello-tf/lib/python3.6/site-packages/sklearn/preprocessing/_encoders.py:351: FutureWarning: The handling of integer data will change in version 0.22. Currently, the categories are determined based on the range [0, max(values)], while in the future they will be determined based on the unique values. If you want the future behavior and silence this warning, you can specify "categories='auto'."In case you used a LabelEncoder before this OneHotEncoder to convert the categories to integers, then you can now use the OneHotEncoder directly. warnings.warn(msg, FutureWarning)
Pipeline(memory=None, steps=[('columntransformer', ColumnTransformer(n_jobs=1, remainder='drop', transformer_weights=None, transformers=[('standardscaler', StandardScaler(copy=True, with_mean=True, with_std=True), [0, 2, 10, 4, 11, 12]), ('onehotencoder', OneHotEncoder(categorical_features=None, categories=None,... reg_alpha=0, reg_lambda=1, scale_pos_weight=1, seed=None, silent=True, subsample=1))])
你会收到一条警告信息。它解释说,你不需要在管道之前创建标签编码器。如果你不使用 LIME,那么本 Scikit-learn 机器学习教程第一部分中的方法就可以了。否则,请继续使用以下方法:首先创建一个编码后的数据集,然后在管道内应用独热编码器。
print("best logistic regression from grid search: %f" % model_xgb.score(X_test_lime, y_test_lime))
best logistic regression from grid search: 0.873157
model_xgb.predict_proba(X_test_lime)
array([[7.9646105e-01, 2.0353897e-01],
[9.5173013e-01, 4.8269872e-02],
[7.9344827e-01, 2.0655173e-01],
...,
[9.9031430e-01, 9.6856682e-03],
[6.4581633e-04, 9.9935418e-01],
[9.7104281e-01, 2.8957171e-02]], dtype=float32)
在使用 LIME 之前,创建一个 NumPy 数组来存储被错误分类的行的特征。稍后您可以使用该列表来了解是什么误导了分类器。
temp = pd.concat([X_test_lime, y_test_lime], axis= 1) temp['predicted'] = model_xgb.predict(X_test_lime) temp['wrong']= temp['label'] != temp['predicted'] temp = temp.query('wrong==True').drop('wrong', axis=1) temp= temp.sort_values(by=['label']) temp.shape
(826,16)
然后,你需要创建一个 lambda 函数,用于从模型中检索新数据的预测结果。你很快就会用到它。
predict_fn = lambda x: model_xgb.predict_proba(x).astype(float)
X_test_lime.dtypes
age float64 workclass int64 fnlwgt float64 education int64 education_num float64 marital int64 occupation int64 relationship int64 race int64 sex int64 capital_gain float64 capital_loss float64 hours_week float64 native_country int64 dtype: object
predict_fn(X_test_lime)
array([[7.96461046e-01, 2.03538969e-01],
[9.51730132e-01, 4.82698716e-02],
[7.93448269e-01, 2.06551731e-01],
...,
[9.90314305e-01, 9.68566816e-03],
[6.45816326e-04, 9.99354184e-01],
[9.71042812e-01, 2.89571714e-02]])
你将 pandas 数据帧转换为 NumPy 数组。
X_train_lime = X_train_lime.values X_test_lime = X_test_lime.values X_test_lime
array([[4.00000e+01, 5.00000e+00, 1.93524e+05, ..., 0.00000e+00,
4.00000e+01, 3.80000e+01],
[2.70000e+01, 4.00000e+00, 2.16481e+05, ..., 0.00000e+00,
4.00000e+01, 3.80000e+01],
[2.50000e+01, 4.00000e+00, 2.56263e+05, ..., 0.00000e+00,
4.00000e+01, 3.80000e+01],
...,
[2.80000e+01, 6.00000e+00, 2.11032e+05, ..., 0.00000e+00,
4.00000e+01, 2.50000e+01],
[4.40000e+01, 4.00000e+00, 1.67005e+05, ..., 0.00000e+00,
6.00000e+01, 3.80000e+01],
[5.30000e+01, 4.00000e+00, 2.57940e+05, ..., 0.00000e+00,
4.00000e+01, 3.80000e+01]])
model_xgb.predict_proba(X_test_lime)
array([[7.9646105e-01, 2.0353897e-01],
[9.5173013e-01, 4.8269872e-02],
[7.9344827e-01, 2.0655173e-01],
...,
[9.9031430e-01, 9.6856682e-03],
[6.4581633e-04, 9.9935418e-01],
[9.7104281e-01, 2.8957171e-02]], dtype=float32)
print(features,
class_names,
categorical_features,
categorical_names)
['age', 'workclass', 'fnlwgt', 'education', 'education_num', 'marital', 'occupation', 'relationship', 'race', 'sex', 'capital_gain', 'capital_loss', 'hours_week', 'native_country'] ['<=50K' '>50K'] [1, 3, 5, 6, 7, 8, 9, 13] {'workclass': array(['?', 'Federal-gov', 'Local-gov', 'Never-worked', 'Private', 'Self-emp-inc', 'Self-emp-not-inc', 'State-gov', 'Without-pay'], dtype=object), 'education': array(['10th', '11th', '12th', '1st-4th', '5th-6th', '7th-8th', '9th', 'Assoc-acdm', 'Assoc-voc', 'Bachelors', 'Doctorate', 'HS-grad', 'Masters', 'Preschool', 'Prof-school', 'Some-college'], dtype=object), 'marital': array(['Divorced', 'Married-AF-spouse', 'Married-civ-spouse', 'Married-spouse-absent', 'Never-married', 'Separated', 'Widowed'], dtype=object), 'occupation': array(['?', 'Adm-clerical', 'Armed-Forces', 'Craft-repair', 'Exec-managerial', 'Farming-fishing', 'Handlers-cleaners', 'Machine-op-inspct', 'Other-service', 'Priv-house-serv', 'Prof-specialty', 'Protective-serv', 'Sales', 'Tech-support', 'Transport-moving'], dtype=object), 'relationship': array(['Husband', 'Not-in-family', 'Other-relative', 'Own-child', 'Unmarried', 'Wife'], dtype=object), 'race': array(['Amer-Indian-Eskimo', 'Asian-Pac-Islander', 'Black', 'Other', 'White'], dtype=object), 'sex': array(['Female', 'Male'], dtype=object), 'native_country': array(['?', 'Cambodia', 'Canada', 'China', 'Columbia', 'Cuba', 'Dominican-Republic', 'Ecuador', 'El-Salvador', 'England', 'France', 'Germany', 'Greece', 'Guatemala', 'Haiti', 'Honduras', 'Hong', 'Hungary', 'India', 'Iran', 'Ireland', 'Italy', 'Jamaica', 'Japan', 'Laos', 'Mexico', 'Nicaragua', 'Outlying-US(Guam-USVI-etc)', 'Peru', 'Philippines', 'Poland', 'Portugal', 'Puerto-Rico', 'Scotland', 'South', 'Taiwan', 'Thailand', 'Trinadad&Tobago', 'United-States', 'Vietnam', 'Yugoslavia'], dtype=object)}
import lime import lime.lime_tabular ### Train should be label encoded not one hot encoded explainer = lime.lime_tabular.LimeTabularExplainer(X_train_lime , feature_names = features, class_names=class_names, categorical_features=categorical_features, categorical_names=categorical_names, kernel_width=3)
现在从测试集中随机选择一个家庭,看看预测结果以及计算机是如何得出预测结果的。
import numpy as np np.random.seed(1) i = 100 print(y_test_lime.iloc[i]) >50K
X_test_lime[i]
array([4.20000e+01, 4.00000e+00, 1.76286e+05, 7.00000e+00, 1.20000e+01,
2.00000e+00, 4.00000e+00, 0.00000e+00, 4.00000e+00, 1.00000e+00,
0.00000e+00, 0.00000e+00, 4.00000e+01, 3.80000e+01])
您可以使用带有 explain_instance 的解释器来检查模型背后的逻辑。它渲染的图表如下所示。
exp = explainer.explain_instance(X_test_lime[i], predict_fn, num_features=6)
exp.show_in_notebook(show_all=False)
分类器正确预测了这个家庭:其收入确实超过 50 万。
首先需要注意的是,分类器的准确性并不高。它预测收入超过 50 万美元的概率为 64%,而这 64% 的概率主要受资本收益和婚姻状况的影响。蓝色代表对“正向”类别的负面影响,橙色代表正面影响。
分类器对此犹豫不决,因为该家庭的资本收益为零,而资本收益通常是财富的良好预测指标。此外,该家庭每周工作时间不足40小时。年龄、职业和性别均对财富有积极影响。
如果婚姻状况为单身,分类器会预测收入低于 50 万美元(0.64 - 0.18 = 0.46)。
现在试试另一个被错误分类的家庭。解释图表在代码后面。
temp.head(3) temp.iloc[1,:-2]
age 58 workclass 4 fnlwgt 68624 education 11 education_num 9 marital 2 occupation 4 relationship 0 race 4 sex 1 capital_gain 0 capital_loss 0 hours_week 45 native_country 38 Name: 20931, dtype: object
i = 1 print('This observation is', temp.iloc[i,-2:])
This observation is label <=50K
predicted >50K
Name: 20931, dtype: object
exp = explainer.explain_instance(temp.iloc[1,:-2], predict_fn, num_features=6)
exp.show_in_notebook(show_all=False)
分类器预测该家庭收入低于 50 万美元,这是错误的。这个家庭的情况比较特殊:既没有资本收益也没有资本损失,户主已离婚,年龄接近 60 岁,并且受过高等教育(即 education_num > 12)。然而,分类器仍然按照既定模式将该家庭的收入预测低于 50 万美元。
亲自试用 LIME 后,你会发现分类器存在很多明显的错误。该库作者的 GitHub 代码库中提供了关于图像和文本分类的更多文档。
Scikit-learn 命令参考
下面列出一些适用于 scikit-learn 版本 0.20 及更高版本的实用命令。
| 任务 | 函数或类 |
|---|---|
| 创建训练/测试数据集 | 训练测试分割 |
| 构建管道 | |
| 选择列并应用转换 | 生成列转换器 |
| 转换类型 | |
| 标准化 | 标准缩放器 |
| 最小-最大缩放 | 最小最大缩放器 |
| 正常化 | 归一化器 |
| 填补缺失值 | 简易计算机 |
| 转换分类 | 热编码器 |
| 拟合和变换数据 | 拟合变换 |
| 建立管道 | make_pipeline |
| 基本型号 | |
| 逻辑回归 | Logistic回归 |
| XGBoost | XGB分类器 |
| 神经网络 | MLP分类器 |
| 网格搜索 | 网格搜索CV |
| 随机搜索 | 随机搜索CV |



