提交 2f5dc5ae 编写于 作者: W wizardforcel

2019-04-09 23:02:07

上级 f847218a
...@@ -40,7 +40,7 @@ XGBoost 模型可以在训练期间评估和报告模型的测试集上的性能 ...@@ -40,7 +40,7 @@ XGBoost 模型可以在训练期间评估和报告模型的测试集上的性能
例如,我们可以在独立测试集( **eval_set** )上报告二进制分类错误率(“_ 错误 _”),同时训练 XGBoost 模型,如下所示: 例如,我们可以在独立测试集( **eval_set** )上报告二进制分类错误率(“_ 错误 _”),同时训练 XGBoost 模型,如下所示:
``` ```py
eval_set = [(X_test, y_test)] eval_set = [(X_test, y_test)]
model.fit(X_train, y_train, eval_metric="error", eval_set=eval_set, verbose=True) model.fit(X_train, y_train, eval_metric="error", eval_set=eval_set, verbose=True)
``` ```
...@@ -59,7 +59,7 @@ XGBoost 支持一套评估指标,不仅限于: ...@@ -59,7 +59,7 @@ XGBoost 支持一套评估指标,不仅限于:
完整示例如下: 完整示例如下:
``` ```py
# monitor training performance # monitor training performance
from numpy import loadtxt from numpy import loadtxt
from xgboost import XGBClassifier from xgboost import XGBClassifier
...@@ -90,7 +90,7 @@ print("Accuracy: %.2f%%" % (accuracy * 100.0)) ...@@ -90,7 +90,7 @@ print("Accuracy: %.2f%%" % (accuracy * 100.0))
下面提供了输出,为简洁起见,将其截断。我们可以看到,每次训练迭代都会报告分类错误(在每个提升的树被添加到模型之后)。 下面提供了输出,为简洁起见,将其截断。我们可以看到,每次训练迭代都会报告分类错误(在每个提升的树被添加到模型之后)。
``` ```py
... ...
[89] validation_0-error:0.204724 [89] validation_0-error:0.204724
[90] validation_0-error:0.208661 [90] validation_0-error:0.208661
...@@ -116,21 +116,21 @@ Accuracy: 77.95% ...@@ -116,21 +116,21 @@ Accuracy: 77.95%
例如: 例如:
``` ```py
eval_set = [(X_train, y_train), (X_test, y_test)] eval_set = [(X_train, y_train), (X_test, y_test)]
model.fit(X_train, y_train, eval_metric="error", eval_set=eval_set, verbose=True) model.fit(X_train, y_train, eval_metric="error", eval_set=eval_set, verbose=True)
``` ```
此外,通过调用 **model.evals_result()**函数,模型在训练后存储并使模型在每个评估集上的性能可用。这将返回评估数据集和分数的字典,例如: 此外,通过调用 **model.evals_result()**函数,模型在训练后存储并使模型在每个评估集上的性能可用。这将返回评估数据集和分数的字典,例如:
``` ```py
results = model.evals_result() results = model.evals_result()
print(results) print(results)
``` ```
这将打印如下结果(为简洁起见,将其截断): 这将打印如下结果(为简洁起见,将其截断):
``` ```py
{ {
'validation_0': {'error': [0.259843, 0.26378, 0.26378, ...]}, 'validation_0': {'error': [0.259843, 0.26378, 0.26378, ...]},
'validation_1': {'error': [0.22179, 0.202335, 0.196498, ...]} 'validation_1': {'error': [0.22179, 0.202335, 0.196498, ...]}
...@@ -141,7 +141,7 @@ print(results) ...@@ -141,7 +141,7 @@ print(results)
可以按如下方式访问特定的结果数组,例如第一个数据集和错误度量标准: 可以按如下方式访问特定的结果数组,例如第一个数据集和错误度量标准:
``` ```py
results['validation_0']['error'] results['validation_0']['error']
``` ```
...@@ -151,7 +151,7 @@ results['validation_0']['error'] ...@@ -151,7 +151,7 @@ results['validation_0']['error']
下面是完整的代码示例,显示了如何在线图上显示收集的结果。 下面是完整的代码示例,显示了如何在线图上显示收集的结果。
``` ```py
# plot learning curve # plot learning curve
from numpy import loadtxt from numpy import loadtxt
from xgboost import XGBClassifier from xgboost import XGBClassifier
...@@ -223,7 +223,7 @@ XGBoost 支持在固定次数的迭代后提前停止。 ...@@ -223,7 +223,7 @@ XGBoost 支持在固定次数的迭代后提前停止。
例如,我们可以检查 10 个时期的对数损失没有改善如下: 例如,我们可以检查 10 个时期的对数损失没有改善如下:
``` ```py
eval_set = [(X_test, y_test)] eval_set = [(X_test, y_test)]
model.fit(X_train, y_train, early_stopping_rounds=10, eval_metric="logloss", eval_set=eval_set, verbose=True) model.fit(X_train, y_train, early_stopping_rounds=10, eval_metric="logloss", eval_set=eval_set, verbose=True)
``` ```
...@@ -232,7 +232,7 @@ model.fit(X_train, y_train, early_stopping_rounds=10, eval_metric="logloss", eva ...@@ -232,7 +232,7 @@ model.fit(X_train, y_train, early_stopping_rounds=10, eval_metric="logloss", eva
下面提供了完整性的完整示例,提前停止。 下面提供了完整性的完整示例,提前停止。
``` ```py
# early stopping # early stopping
from numpy import loadtxt from numpy import loadtxt
from xgboost import XGBClassifier from xgboost import XGBClassifier
...@@ -261,7 +261,7 @@ print("Accuracy: %.2f%%" % (accuracy * 100.0)) ...@@ -261,7 +261,7 @@ print("Accuracy: %.2f%%" % (accuracy * 100.0))
运行该示例提供以下输出,为简洁起见,将其截断: 运行该示例提供以下输出,为简洁起见,将其截断:
``` ```py
... ...
[35] validation_0-logloss:0.487962 [35] validation_0-logloss:0.487962
[36] validation_0-logloss:0.488218 [36] validation_0-logloss:0.488218
......
...@@ -47,7 +47,7 @@ XGBoost 在 C ++中实现,以明确地使用 [OpenMP API](https://en.wikipedia ...@@ -47,7 +47,7 @@ XGBoost 在 C ++中实现,以明确地使用 [OpenMP API](https://en.wikipedia
默认情况下,此参数设置为-1 以使用系统中的所有核心。 默认情况下,此参数设置为-1 以使用系统中的所有核心。
``` ```py
model = XGBClassifier(nthread=-1) model = XGBClassifier(nthread=-1)
``` ```
...@@ -59,7 +59,7 @@ model = XGBClassifier(nthread=-1) ...@@ -59,7 +59,7 @@ model = XGBClassifier(nthread=-1)
例如,如果您的系统有 4 个核心,您可以训练 8 个不同的模型,并计算创建每个模型所需的时间(以秒为单位),然后比较时间。 例如,如果您的系统有 4 个核心,您可以训练 8 个不同的模型,并计算创建每个模型所需的时间(以秒为单位),然后比较时间。
``` ```py
# evaluate the effect of the number of threads # evaluate the effect of the number of threads
results = [] results = []
num_threads = [1, 2, 3, 4] num_threads = [1, 2, 3, 4]
...@@ -76,7 +76,7 @@ for n in num_threads: ...@@ -76,7 +76,7 @@ for n in num_threads:
您可以更改 **num_threads** 阵列以满足系统上的核心数。 您可以更改 **num_threads** 阵列以满足系统上的核心数。
``` ```py
# Otto, tune number of threads # Otto, tune number of threads
from pandas import read_csv from pandas import read_csv
from xgboost import XGBClassifier from xgboost import XGBClassifier
...@@ -111,7 +111,7 @@ pyplot.show() ...@@ -111,7 +111,7 @@ pyplot.show()
运行此示例总结了每个配置的执行时间(以秒为单位),例如: 运行此示例总结了每个配置的执行时间(以秒为单位),例如:
``` ```py
(1, 115.51652717590332) (1, 115.51652717590332)
(2, 62.7727689743042) (2, 62.7727689743042)
(3, 46.042901039123535) (3, 46.042901039123535)
...@@ -146,7 +146,7 @@ scikit-learn 中的 k-fold 交叉验证支持也支持多线程。 ...@@ -146,7 +146,7 @@ scikit-learn 中的 k-fold 交叉验证支持也支持多线程。
默认情况下,此值设置为 1,但可以设置为-1 以使用系统上的所有 CPU 核心,这是一种很好的做法。例如: 默认情况下,此值设置为 1,但可以设置为-1 以使用系统上的所有 CPU 核心,这是一种很好的做法。例如:
``` ```py
results = cross_val_score(model, X, label_encoded_y, cv=kfold, scoring='log_loss', n_jobs=-1, verbose=1) results = cross_val_score(model, X, label_encoded_y, cv=kfold, scoring='log_loss', n_jobs=-1, verbose=1)
``` ```
...@@ -162,7 +162,7 @@ results = cross_val_score(model, X, label_encoded_y, cv=kfold, scoring='log_loss ...@@ -162,7 +162,7 @@ results = cross_val_score(model, X, label_encoded_y, cv=kfold, scoring='log_loss
完整的代码示例如下所示。 完整的代码示例如下所示。
``` ```py
# Otto, parallel cross validation # Otto, parallel cross validation
from pandas import read_csv from pandas import read_csv
from xgboost import XGBClassifier from xgboost import XGBClassifier
...@@ -202,7 +202,7 @@ print("Parallel Thread XGBoost and CV: %f" % (elapsed)) ...@@ -202,7 +202,7 @@ print("Parallel Thread XGBoost and CV: %f" % (elapsed))
运行该示例将打印以下结果: 运行该示例将打印以下结果:
``` ```py
Single Thread XGBoost, Parallel Thread CV: 359.854589 Single Thread XGBoost, Parallel Thread CV: 359.854589
Parallel Thread XGBoost, Single Thread CV: 330.498101 Parallel Thread XGBoost, Single Thread CV: 330.498101
Parallel Thread XGBoost and CV: 313.382301 Parallel Thread XGBoost and CV: 313.382301
......
...@@ -33,7 +33,7 @@ XGBoost 因其速度和性能而成为 Gradient Boosting 的流行实现。 ...@@ -33,7 +33,7 @@ XGBoost 因其速度和性能而成为 Gradient Boosting 的流行实现。
下面是原始数据集的示例。您可以从 [UCI 机器学习库](http://archive.ics.uci.edu/ml/datasets/Iris)中了解有关此数据集的更多信息并以 CSV 格式下载原始数据。 下面是原始数据集的示例。您可以从 [UCI 机器学习库](http://archive.ics.uci.edu/ml/datasets/Iris)中了解有关此数据集的更多信息并以 CSV 格式下载原始数据。
``` ```py
5.1,3.5,1.4,0.2,Iris-setosa 5.1,3.5,1.4,0.2,Iris-setosa
4.9,3.0,1.4,0.2,Iris-setosa 4.9,3.0,1.4,0.2,Iris-setosa
4.7,3.2,1.3,0.2,Iris-setosa 4.7,3.2,1.3,0.2,Iris-setosa
...@@ -45,7 +45,7 @@ XGBoost 无法按原样对此问题进行建模,因为它要求输出变量为 ...@@ -45,7 +45,7 @@ XGBoost 无法按原样对此问题进行建模,因为它要求输出变量为
我们可以使用 [LabelEncoder](http://scikit-learn.org/stable/modules/generated/sklearn.preprocessing.LabelEncoder.html) 轻松地将字符串值转换为整数值。三个类值(Iris-setosa,Iris-versicolor,Iris-virginica)被映射到整数值(0,1,2)。 我们可以使用 [LabelEncoder](http://scikit-learn.org/stable/modules/generated/sklearn.preprocessing.LabelEncoder.html) 轻松地将字符串值转换为整数值。三个类值(Iris-setosa,Iris-versicolor,Iris-virginica)被映射到整数值(0,1,2)。
``` ```py
# encode string class values as integers # encode string class values as integers
label_encoder = LabelEncoder() label_encoder = LabelEncoder()
label_encoder = label_encoder.fit(Y) label_encoder = label_encoder.fit(Y)
...@@ -56,7 +56,7 @@ label_encoded_y = label_encoder.transform(Y) ...@@ -56,7 +56,7 @@ label_encoded_y = label_encoder.transform(Y)
下面是一个演示如何加载虹膜数据集的完整示例。请注意,Pandas 用于加载数据以处理字符串类值。 下面是一个演示如何加载虹膜数据集的完整示例。请注意,Pandas 用于加载数据以处理字符串类值。
``` ```py
# multiclass classification # multiclass classification
import pandas import pandas
import xgboost import xgboost
...@@ -90,7 +90,7 @@ print("Accuracy: %.2f%%" % (accuracy * 100.0)) ...@@ -90,7 +90,7 @@ print("Accuracy: %.2f%%" % (accuracy * 100.0))
运行该示例将生成以下输出: 运行该示例将生成以下输出:
``` ```py
XGBClassifier(base_score=0.5, colsample_bylevel=1, colsample_bytree=1, XGBClassifier(base_score=0.5, colsample_bylevel=1, colsample_bytree=1,
gamma=0, learning_rate=0.1, max_delta_step=0, max_depth=3, gamma=0, learning_rate=0.1, max_delta_step=0, max_depth=3,
min_child_weight=1, missing=None, n_estimators=100, nthread=-1, min_child_weight=1, missing=None, n_estimators=100, nthread=-1,
...@@ -109,7 +109,7 @@ Accuracy: 92.00% ...@@ -109,7 +109,7 @@ Accuracy: 92.00%
下面是原始数据集的示例。您可以在 [UCI 机器学习库](http://archive.ics.uci.edu/ml/datasets/Breast+Cancer)中了解有关此数据集的更多信息,并从 [mldata.org](http://mldata.org/repository/data/viewslug/datasets-uci-breast-cancer/) 以 CSV 格式下载。 下面是原始数据集的示例。您可以在 [UCI 机器学习库](http://archive.ics.uci.edu/ml/datasets/Breast+Cancer)中了解有关此数据集的更多信息,并从 [mldata.org](http://mldata.org/repository/data/viewslug/datasets-uci-breast-cancer/) 以 CSV 格式下载。
``` ```py
'40-49','premeno','15-19','0-2','yes','3','right','left_up','no','recurrence-events' '40-49','premeno','15-19','0-2','yes','3','right','left_up','no','recurrence-events'
'50-59','ge40','15-19','0-2','no','1','right','central','no','no-recurrence-events' '50-59','ge40','15-19','0-2','no','1','right','central','no','no-recurrence-events'
'50-59','ge40','35-39','0-2','no','2','left','left_low','no','recurrence-events' '50-59','ge40','35-39','0-2','no','2','left','left_low','no','recurrence-events'
...@@ -121,7 +121,7 @@ Accuracy: 92.00% ...@@ -121,7 +121,7 @@ Accuracy: 92.00%
我们可以重用上一节中的相同方法,并将字符串类值转换为整数值,以使用 LabelEncoder 对预测进行建模。例如: 我们可以重用上一节中的相同方法,并将字符串类值转换为整数值,以使用 LabelEncoder 对预测进行建模。例如:
``` ```py
# encode string class values as integers # encode string class values as integers
label_encoder = LabelEncoder() label_encoder = LabelEncoder()
label_encoder = label_encoder.fit(Y) label_encoder = label_encoder.fit(Y)
...@@ -130,7 +130,7 @@ label_encoded_y = label_encoder.transform(Y) ...@@ -130,7 +130,7 @@ label_encoded_y = label_encoder.transform(Y)
我们可以在 X 中的每个输入要素上使用相同的方法,但这只是一个起点。 我们可以在 X 中的每个输入要素上使用相同的方法,但这只是一个起点。
``` ```py
# encode string input values as integers # encode string input values as integers
features = [] features = []
for i in range(0, X.shape[1]): for i in range(0, X.shape[1]):
...@@ -147,7 +147,7 @@ XGBoost 可以假设每个输入变量的编码整数值具有序数关系。例 ...@@ -147,7 +147,7 @@ XGBoost 可以假设每个输入变量的编码整数值具有序数关系。例
例如,breast-quad 变量具有以下值: 例如,breast-quad 变量具有以下值:
``` ```py
left-up left-up
left-low left-low
right-up right-up
...@@ -157,7 +157,7 @@ central ...@@ -157,7 +157,7 @@ central
我们可以将其建模为 5 个二进制变量,如下所示: 我们可以将其建模为 5 个二进制变量,如下所示:
``` ```py
left-up, left-low, right-up, right-low, central left-up, left-low, right-up, right-low, central
1,0,0,0,0 1,0,0,0,0
0,1,0,0,0 0,1,0,0,0
...@@ -170,20 +170,20 @@ left-up, left-low, right-up, right-low, central ...@@ -170,20 +170,20 @@ left-up, left-low, right-up, right-low, central
在我们对其进行标签编码后,我们可以对每个功能进行热编码。首先,我们必须将要素数组转换为 2 维 NumPy 数组,其中每个整数值是长度为 1 的要素向量。 在我们对其进行标签编码后,我们可以对每个功能进行热编码。首先,我们必须将要素数组转换为 2 维 NumPy 数组,其中每个整数值是长度为 1 的要素向量。
``` ```py
feature = feature.reshape(X.shape[0], 1) feature = feature.reshape(X.shape[0], 1)
``` ```
然后我们可以创建 OneHotEncoder 并对特征数组进行编码。 然后我们可以创建 OneHotEncoder 并对特征数组进行编码。
``` ```py
onehot_encoder = OneHotEncoder(sparse=False) onehot_encoder = OneHotEncoder(sparse=False)
feature = onehot_encoder.fit_transform(feature) feature = onehot_encoder.fit_transform(feature)
``` ```
最后,我们可以通过逐个连接一个热编码特征来建立输入数据集,将它们作为新列添加(轴= 2)。我们最终得到一个由 43 个二进制输入变量组成的输入向量。 最后,我们可以通过逐个连接一个热编码特征来建立输入数据集,将它们作为新列添加(轴= 2)。我们最终得到一个由 43 个二进制输入变量组成的输入向量。
``` ```py
# encode string input values as integers # encode string input values as integers
encoded_x = None encoded_x = None
for i in range(0, X.shape[1]): for i in range(0, X.shape[1]):
...@@ -203,7 +203,7 @@ print("X shape: : ", encoded_x.shape) ...@@ -203,7 +203,7 @@ print("X shape: : ", encoded_x.shape)
下面是带有标签和一个热编码输入变量和标签编码输出变量的完整示例。 下面是带有标签和一个热编码输入变量和标签编码输出变量的完整示例。
``` ```py
# binary classification, breast cancer dataset, label and one hot encoded # binary classification, breast cancer dataset, label and one hot encoded
import numpy import numpy
from pandas import read_csv from pandas import read_csv
...@@ -254,7 +254,7 @@ print("Accuracy: %.2f%%" % (accuracy * 100.0)) ...@@ -254,7 +254,7 @@ print("Accuracy: %.2f%%" % (accuracy * 100.0))
运行此示例,我们得到以下输出: 运行此示例,我们得到以下输出:
``` ```py
('X shape: : ', (285, 43)) ('X shape: : ', (285, 43))
XGBClassifier(base_score=0.5, colsample_bylevel=1, colsample_bytree=1, XGBClassifier(base_score=0.5, colsample_bylevel=1, colsample_bytree=1,
gamma=0, learning_rate=0.1, max_delta_step=0, max_depth=3, gamma=0, learning_rate=0.1, max_delta_step=0, max_depth=3,
...@@ -280,27 +280,27 @@ Horse Colic 数据集是演示此功能的一个很好的示例,因为它包 ...@@ -280,27 +280,27 @@ Horse Colic 数据集是演示此功能的一个很好的示例,因为它包
这些值由空格分隔,我们可以使用 Pandas 函数 [read_csv](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_csv.html) 轻松加载它。 这些值由空格分隔,我们可以使用 Pandas 函数 [read_csv](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_csv.html) 轻松加载它。
``` ```py
dataframe = read_csv("horse-colic.csv", delim_whitespace=True, header=None) dataframe = read_csv("horse-colic.csv", delim_whitespace=True, header=None)
``` ```
加载后,我们可以看到缺少的数据标有问号字符('?')。我们可以将这些缺失值更改为 XGBoost 预期的稀疏值,即值零(0)。 加载后,我们可以看到缺少的数据标有问号字符('?')。我们可以将这些缺失值更改为 XGBoost 预期的稀疏值,即值零(0)。
``` ```py
# set missing values to 0 # set missing values to 0
X[X == '?'] = 0 X[X == '?'] = 0
``` ```
由于缺少的数据被标记为字符串,因此缺少数据的那些列都作为字符串数据类型加载。我们现在可以将整个输入数据集转换为数值。 由于缺少的数据被标记为字符串,因此缺少数据的那些列都作为字符串数据类型加载。我们现在可以将整个输入数据集转换为数值。
``` ```py
# convert to numeric # convert to numeric
X = X.astype('float32') X = X.astype('float32')
``` ```
最后,这是一个二元分类问题,尽管类值用整数 1 和 2 标记。我们将 XGBoost 中的二进制分类问题建模为逻辑 0 和 1 值。我们可以使用 LabelEncoder 轻松地将 Y 数据集转换为 0 和 1 整数,就像我们在虹膜花示例中所做的那样。 最后,这是一个二元分类问题,尽管类值用整数 1 和 2 标记。我们将 XGBoost 中的二进制分类问题建模为逻辑 0 和 1 值。我们可以使用 LabelEncoder 轻松地将 Y 数据集转换为 0 和 1 整数,就像我们在虹膜花示例中所做的那样。
``` ```py
# encode Y class values as integers # encode Y class values as integers
label_encoder = LabelEncoder() label_encoder = LabelEncoder()
label_encoder = label_encoder.fit(Y) label_encoder = label_encoder.fit(Y)
...@@ -309,7 +309,7 @@ label_encoded_y = label_encoder.transform(Y) ...@@ -309,7 +309,7 @@ label_encoded_y = label_encoder.transform(Y)
完整性代码清单如下所示。 完整性代码清单如下所示。
``` ```py
# binary classification, missing data # binary classification, missing data
from pandas import read_csv from pandas import read_csv
from xgboost import XGBClassifier from xgboost import XGBClassifier
...@@ -348,7 +348,7 @@ print("Accuracy: %.2f%%" % (accuracy * 100.0)) ...@@ -348,7 +348,7 @@ print("Accuracy: %.2f%%" % (accuracy * 100.0))
运行此示例将生成以下输出。 运行此示例将生成以下输出。
``` ```py
XGBClassifier(base_score=0.5, colsample_bylevel=1, colsample_bytree=1, XGBClassifier(base_score=0.5, colsample_bylevel=1, colsample_bytree=1,
gamma=0, learning_rate=0.1, max_delta_step=0, max_depth=3, gamma=0, learning_rate=0.1, max_delta_step=0, max_depth=3,
min_child_weight=1, missing=None, n_estimators=100, nthread=-1, min_child_weight=1, missing=None, n_estimators=100, nthread=-1,
...@@ -359,13 +359,13 @@ Accuracy: 83.84% ...@@ -359,13 +359,13 @@ Accuracy: 83.84%
我们可以通过使用非零值(例如 1)标记缺失值来梳理 XGBoost 自动处理缺失值的效果。 我们可以通过使用非零值(例如 1)标记缺失值来梳理 XGBoost 自动处理缺失值的效果。
``` ```py
X[X == '?'] = 1 X[X == '?'] = 1
``` ```
重新运行该示例表明模型的准确性下降。 重新运行该示例表明模型的准确性下降。
``` ```py
Accuracy: 79.80% Accuracy: 79.80%
``` ```
...@@ -373,7 +373,7 @@ Accuracy: 79.80% ...@@ -373,7 +373,7 @@ Accuracy: 79.80%
通常使用列的平均值或中值。我们可以使用 scikit-learn [Imputer](http://scikit-learn.org/stable/modules/generated/sklearn.preprocessing.Imputer.html) 类轻松地估算缺失的数据。 通常使用列的平均值或中值。我们可以使用 scikit-learn [Imputer](http://scikit-learn.org/stable/modules/generated/sklearn.preprocessing.Imputer.html) 类轻松地估算缺失的数据。
``` ```py
# impute missing values as the mean # impute missing values as the mean
imputer = Imputer() imputer = Imputer()
imputed_x = imputer.fit_transform(X) imputed_x = imputer.fit_transform(X)
...@@ -381,7 +381,7 @@ imputed_x = imputer.fit_transform(X) ...@@ -381,7 +381,7 @@ imputed_x = imputer.fit_transform(X)
下面是完整的示例,其中缺少的数据与每列的平均值估算。 下面是完整的示例,其中缺少的数据与每列的平均值估算。
``` ```py
# binary classification, missing data, impute with mean # binary classification, missing data, impute with mean
import numpy import numpy
from pandas import read_csv from pandas import read_csv
...@@ -425,7 +425,7 @@ print("Accuracy: %.2f%%" % (accuracy * 100.0)) ...@@ -425,7 +425,7 @@ print("Accuracy: %.2f%%" % (accuracy * 100.0))
运行此示例,我们看到的结果等同于将值固定为一(1)。这表明至少在这种情况下,我们最好用不同的零(0)值而不是有效值(1)或估算值来标记缺失值。 运行此示例,我们看到的结果等同于将值固定为一(1)。这表明至少在这种情况下,我们最好用不同的零(0)值而不是有效值(1)或估算值来标记缺失值。
``` ```py
Accuracy: 79.80% Accuracy: 79.80%
``` ```
......
...@@ -40,13 +40,13 @@ XGBoost 是梯度提升决策树的一种实现,旨在提高竞争机器学习 ...@@ -40,13 +40,13 @@ XGBoost 是梯度提升决策树的一种实现,旨在提高竞争机器学习
例如: 例如:
``` ```py
sudo pip install xgboost sudo pip install xgboost
``` ```
要更新 XGBoost 的安装,您可以键入: 要更新 XGBoost 的安装,您可以键入:
``` ```py
sudo pip install --upgrade xgboost sudo pip install --upgrade xgboost
``` ```
...@@ -54,7 +54,7 @@ sudo pip install --upgrade xgboost ...@@ -54,7 +54,7 @@ sudo pip install --upgrade xgboost
例如,要在 Mac OS X 上没有多线程构建 XGBoost(已经通过 macports 或 homebrew 安装了 GCC),您可以键入: 例如,要在 Mac OS X 上没有多线程构建 XGBoost(已经通过 macports 或 homebrew 安装了 GCC),您可以键入:
``` ```py
git clone --recursive https://github.com/dmlc/xgboost git clone --recursive https://github.com/dmlc/xgboost
cd xgboost cd xgboost
cp make/minimum.mk ./config.mk cp make/minimum.mk ./config.mk
...@@ -85,7 +85,7 @@ sudo python setup.py install ...@@ -85,7 +85,7 @@ sudo python setup.py install
我们将从导入我们打算在本教程中使用的类和函数开始。 我们将从导入我们打算在本教程中使用的类和函数开始。
``` ```py
from numpy import loadtxt from numpy import loadtxt
from xgboost import XGBClassifier from xgboost import XGBClassifier
from sklearn.model_selection import train_test_split from sklearn.model_selection import train_test_split
...@@ -94,14 +94,14 @@ from sklearn.metrics import accuracy_score ...@@ -94,14 +94,14 @@ from sklearn.metrics import accuracy_score
接下来,我们可以使用 NumPy 函数 **loadtext()**将 CSV 文件作为 NumPy 数组加载。 接下来,我们可以使用 NumPy 函数 **loadtext()**将 CSV 文件作为 NumPy 数组加载。
``` ```py
# load data # load data
dataset = loadtxt('pima-indians-diabetes.csv', delimiter=",") dataset = loadtxt('pima-indians-diabetes.csv', delimiter=",")
``` ```
我们必须将数据集的列(属性或特征)分成输入模式(X)和输出模式(Y)。我们可以通过以 NumPy 数组格式指定列索引来轻松完成此操作。 我们必须将数据集的列(属性或特征)分成输入模式(X)和输出模式(Y)。我们可以通过以 NumPy 数组格式指定列索引来轻松完成此操作。
``` ```py
# split data into X and y # split data into X and y
X = dataset[:,0:8] X = dataset[:,0:8]
Y = dataset[:,8] Y = dataset[:,8]
...@@ -111,7 +111,7 @@ Y = dataset[:,8] ...@@ -111,7 +111,7 @@ Y = dataset[:,8]
为此,我们将使用 scikit-learn 库中的 **train_test_split()**函数。我们还为随机数生成器指定种子,以便每次执行此示例时始终获得相同的数据分割。 为此,我们将使用 scikit-learn 库中的 **train_test_split()**函数。我们还为随机数生成器指定种子,以便每次执行此示例时始终获得相同的数据分割。
``` ```py
# split data into train and test sets # split data into train and test sets
seed = 7 seed = 7
test_size = 0.33 test_size = 0.33
...@@ -130,7 +130,7 @@ XGBoost 提供了一个包装类,允许在 scikit-learn 框架中将模型视 ...@@ -130,7 +130,7 @@ XGBoost 提供了一个包装类,允许在 scikit-learn 框架中将模型视
训练模型的参数可以传递给构造函数中的模型。在这里,我们使用合理的默认值。 训练模型的参数可以传递给构造函数中的模型。在这里,我们使用合理的默认值。
``` ```py
# fit model no training data # fit model no training data
model = XGBClassifier() model = XGBClassifier()
model.fit(X_train, y_train) model.fit(X_train, y_train)
...@@ -138,7 +138,7 @@ model.fit(X_train, y_train) ...@@ -138,7 +138,7 @@ model.fit(X_train, y_train)
您可以通过打印模型来查看训练模型中使用的参数,例如: 您可以通过打印模型来查看训练模型中使用的参数,例如:
``` ```py
print(model) print(model)
``` ```
...@@ -156,7 +156,7 @@ print(model) ...@@ -156,7 +156,7 @@ print(model)
默认情况下,XGBoost 进行的预测是概率。因为这是二元分类问题,所以每个预测是输入模式属于第一类的概率。我们可以通过将它们四舍五入为 0 或 1 来轻松地将它们转换为二进制类值。 默认情况下,XGBoost 进行的预测是概率。因为这是二元分类问题,所以每个预测是输入模式属于第一类的概率。我们可以通过将它们四舍五入为 0 或 1 来轻松地将它们转换为二进制类值。
``` ```py
# make predictions for test data # make predictions for test data
y_pred = model.predict(X_test) y_pred = model.predict(X_test)
predictions = [round(value) for value in y_pred] predictions = [round(value) for value in y_pred]
...@@ -164,7 +164,7 @@ predictions = [round(value) for value in y_pred] ...@@ -164,7 +164,7 @@ predictions = [round(value) for value in y_pred]
现在我们已经使用拟合模型对新数据进行预测,我们可以通过将预测值与预期值进行比较来评估预测的性能。为此,我们将在 scikit-learn 中使用内置的 **accuracy_score()**函数。 现在我们已经使用拟合模型对新数据进行预测,我们可以通过将预测值与预期值进行比较来评估预测的性能。为此,我们将在 scikit-learn 中使用内置的 **accuracy_score()**函数。
``` ```py
# evaluate predictions # evaluate predictions
accuracy = accuracy_score(y_test, predictions) accuracy = accuracy_score(y_test, predictions)
print("Accuracy: %.2f%%" % (accuracy * 100.0)) print("Accuracy: %.2f%%" % (accuracy * 100.0))
...@@ -174,7 +174,7 @@ print("Accuracy: %.2f%%" % (accuracy * 100.0)) ...@@ -174,7 +174,7 @@ print("Accuracy: %.2f%%" % (accuracy * 100.0))
我们可以将所有这些部分组合在一起,下面是完整的代码清单。 我们可以将所有这些部分组合在一起,下面是完整的代码清单。
``` ```py
# First XGBoost model for Pima Indians dataset # First XGBoost model for Pima Indians dataset
from numpy import loadtxt from numpy import loadtxt
from xgboost import XGBClassifier from xgboost import XGBClassifier
...@@ -202,7 +202,7 @@ print("Accuracy: %.2f%%" % (accuracy * 100.0)) ...@@ -202,7 +202,7 @@ print("Accuracy: %.2f%%" % (accuracy * 100.0))
运行此示例将生成以下输出。 运行此示例将生成以下输出。
``` ```py
Accuracy: 77.95% Accuracy: 77.95%
``` ```
......
...@@ -37,14 +37,14 @@ ...@@ -37,14 +37,14 @@
我们可以使用 scikit-learn 库中的 **train_test_split()**函数将数据集拆分为火车和测试集。例如,我们可以将数据集拆分为 67%和 33%的分组,用于训练和测试集,如下所示: 我们可以使用 scikit-learn 库中的 **train_test_split()**函数将数据集拆分为火车和测试集。例如,我们可以将数据集拆分为 67%和 33%的分组,用于训练和测试集,如下所示:
``` ```py
# split data into train and test sets # split data into train and test sets
X_train, X_test, y_train, y_test = train_test_split(X, Y, test_size=0.33, random_state=7) X_train, X_test, y_train, y_test = train_test_split(X, Y, test_size=0.33, random_state=7)
``` ```
下面使用 [Pima 印第安人糖尿病数据集](https://archive.ics.uci.edu/ml/datasets/Pima+Indians+Diabetes)开始提供完整的代码清单,假设它位于当前工作目录中(更新:[从这里下载](https://raw.githubusercontent.com/jbrownlee/Datasets/master/pima-indians-diabetes.data.csv))。具有默认配置的 XGBoost 模型适合训练数据集并在测试数据集上进行评估。 下面使用 [Pima 印第安人糖尿病数据集](https://archive.ics.uci.edu/ml/datasets/Pima+Indians+Diabetes)开始提供完整的代码清单,假设它位于当前工作目录中(更新:[从这里下载](https://raw.githubusercontent.com/jbrownlee/Datasets/master/pima-indians-diabetes.data.csv))。具有默认配置的 XGBoost 模型适合训练数据集并在测试数据集上进行评估。
``` ```py
# train-test split evaluation of xgboost model # train-test split evaluation of xgboost model
from numpy import loadtxt from numpy import loadtxt
from xgboost import XGBClassifier from xgboost import XGBClassifier
...@@ -70,7 +70,7 @@ print("Accuracy: %.2f%%" % (accuracy * 100.0)) ...@@ -70,7 +70,7 @@ print("Accuracy: %.2f%%" % (accuracy * 100.0))
运行此示例总结了测试集上模型的性能。 运行此示例总结了测试集上模型的性能。
``` ```py
Accuracy: 77.95% Accuracy: 77.95%
``` ```
...@@ -88,14 +88,14 @@ k 的选择必须允许每个测试分区的大小足够大以成为问题的合 ...@@ -88,14 +88,14 @@ k 的选择必须允许每个测试分区的大小足够大以成为问题的合
我们可以使用 scikit-learn 中提供的 k-fold 交叉验证支持。首先,我们必须创建 [KFold](http://scikit-learn.org/stable/modules/generated/sklearn.cross_validation.KFold.html) 对象,指定折叠的数量和数据集的大小。然后,我们可以将此方案与特定数据集一起使用。来自 scikit-learn 的 **cross_val_score()**函数允许我们使用交叉验证方案评估模型,并返回每个折叠上训练的每个模型的分数列表。 我们可以使用 scikit-learn 中提供的 k-fold 交叉验证支持。首先,我们必须创建 [KFold](http://scikit-learn.org/stable/modules/generated/sklearn.cross_validation.KFold.html) 对象,指定折叠的数量和数据集的大小。然后,我们可以将此方案与特定数据集一起使用。来自 scikit-learn 的 **cross_val_score()**函数允许我们使用交叉验证方案评估模型,并返回每个折叠上训练的每个模型的分数列表。
``` ```py
kfold = KFold(n_splits=10, random_state=7) kfold = KFold(n_splits=10, random_state=7)
results = cross_val_score(model, X, Y, cv=kfold) results = cross_val_score(model, X, Y, cv=kfold)
``` ```
下面提供了用于评估具有 k 折交叉验证的 XGBoost 模型的完整代码清单,以确保完整性。 下面提供了用于评估具有 k 折交叉验证的 XGBoost 模型的完整代码清单,以确保完整性。
``` ```py
# k-fold cross validation evaluation of xgboost model # k-fold cross validation evaluation of xgboost model
from numpy import loadtxt from numpy import loadtxt
import xgboost import xgboost
...@@ -115,7 +115,7 @@ print("Accuracy: %.2f%% (%.2f%%)" % (results.mean()*100, results.std()*100)) ...@@ -115,7 +115,7 @@ print("Accuracy: %.2f%% (%.2f%%)" % (results.mean()*100, results.std()*100))
运行此示例总结了数据集上默认模型配置的性能,包括平均值和标准差分类精度。 运行此示例总结了数据集上默认模型配置的性能,包括平均值和标准差分类精度。
``` ```py
Accuracy: 76.69% (7.11%) Accuracy: 76.69% (7.11%)
``` ```
...@@ -125,7 +125,7 @@ Accuracy: 76.69% (7.11%) ...@@ -125,7 +125,7 @@ Accuracy: 76.69% (7.11%)
下面是修改为使用分层交叉验证来评估 XGBoost 模型的相同示例。 下面是修改为使用分层交叉验证来评估 XGBoost 模型的相同示例。
``` ```py
# stratified k-fold cross validation evaluation of xgboost model # stratified k-fold cross validation evaluation of xgboost model
from numpy import loadtxt from numpy import loadtxt
import xgboost import xgboost
...@@ -145,7 +145,7 @@ print("Accuracy: %.2f%% (%.2f%%)" % (results.mean()*100, results.std()*100)) ...@@ -145,7 +145,7 @@ print("Accuracy: %.2f%% (%.2f%%)" % (results.mean()*100, results.std()*100))
运行此示例将生成以下输出。 运行此示例将生成以下输出。
``` ```py
Accuracy: 76.95% (5.88%) Accuracy: 76.95% (5.88%)
``` ```
......
...@@ -44,13 +44,13 @@ ...@@ -44,13 +44,13 @@
这些重要性分数可在训练模型的 **feature_importances_** 成员变量中找到。例如,它们可以直接打印如下: 这些重要性分数可在训练模型的 **feature_importances_** 成员变量中找到。例如,它们可以直接打印如下:
``` ```py
print(model.feature_importances_) print(model.feature_importances_)
``` ```
我们可以直接在条形图上绘制这些分数,以直观地显示数据集中每个要素的相对重要性。例如: 我们可以直接在条形图上绘制这些分数,以直观地显示数据集中每个要素的相对重要性。例如:
``` ```py
# plot # plot
pyplot.bar(range(len(model.feature_importances_)), model.feature_importances_) pyplot.bar(range(len(model.feature_importances_)), model.feature_importances_)
pyplot.show() pyplot.show()
...@@ -58,7 +58,7 @@ pyplot.show() ...@@ -58,7 +58,7 @@ pyplot.show()
我们可以通过在 [Pima 印第安人糖尿病数据集](https://archive.ics.uci.edu/ml/datasets/Pima+Indians+Diabetes)上训练 XGBoost 模型并根据计算的特征重要性创建条形图来证明这一点(更新:[从这里下载](https://raw.githubusercontent.com/jbrownlee/Datasets/master/pima-indians-diabetes.data.csv))。 我们可以通过在 [Pima 印第安人糖尿病数据集](https://archive.ics.uci.edu/ml/datasets/Pima+Indians+Diabetes)上训练 XGBoost 模型并根据计算的特征重要性创建条形图来证明这一点(更新:[从这里下载](https://raw.githubusercontent.com/jbrownlee/Datasets/master/pima-indians-diabetes.data.csv))。
``` ```py
# plot feature importance manually # plot feature importance manually
from numpy import loadtxt from numpy import loadtxt
from xgboost import XGBClassifier from xgboost import XGBClassifier
...@@ -80,7 +80,7 @@ pyplot.show() ...@@ -80,7 +80,7 @@ pyplot.show()
运行此示例首先输出重要性分数: 运行此示例首先输出重要性分数:
``` ```py
[ 0.089701    0.17109634  0.08139535  0.04651163  0.10465116  0.2026578 0.1627907   0.14119601] [ 0.089701    0.17109634  0.08139535  0.04651163  0.10465116  0.2026578 0.1627907   0.14119601]
``` ```
...@@ -100,7 +100,7 @@ XGBoost 库提供了一个内置函数来绘制按其重要性排序的特征。 ...@@ -100,7 +100,7 @@ XGBoost 库提供了一个内置函数来绘制按其重要性排序的特征。
该函数称为 **plot_importance()**,可以按如下方式使用: 该函数称为 **plot_importance()**,可以按如下方式使用:
``` ```py
# plot feature importance # plot feature importance
plot_importance(model) plot_importance(model)
pyplot.show() pyplot.show()
...@@ -108,7 +108,7 @@ pyplot.show() ...@@ -108,7 +108,7 @@ pyplot.show()
例如,下面是一个完整的代码清单,使用内置的 **plot_importance()**函数绘制 Pima Indians 数据集的特征重要性。 例如,下面是一个完整的代码清单,使用内置的 **plot_importance()**函数绘制 Pima Indians 数据集的特征重要性。
``` ```py
# plot feature importance using built-in function # plot feature importance using built-in function
from numpy import loadtxt from numpy import loadtxt
from xgboost import XGBClassifier from xgboost import XGBClassifier
...@@ -151,7 +151,7 @@ XGBoost 功能重要性条形图 ...@@ -151,7 +151,7 @@ XGBoost 功能重要性条形图
例如: 例如:
``` ```py
# select features using threshold # select features using threshold
selection = SelectFromModel(model, threshold=thresh, prefit=True) selection = SelectFromModel(model, threshold=thresh, prefit=True)
select_X_train = selection.transform(X_train) select_X_train = selection.transform(X_train)
...@@ -167,7 +167,7 @@ y_pred = selection_model.predict(select_X_test) ...@@ -167,7 +167,7 @@ y_pred = selection_model.predict(select_X_test)
完整的代码清单如下。 完整的代码清单如下。
``` ```py
# use feature importance for feature selection # use feature importance for feature selection
from numpy import loadtxt from numpy import loadtxt
from numpy import sort from numpy import sort
...@@ -209,7 +209,7 @@ for thresh in thresholds: ...@@ -209,7 +209,7 @@ for thresh in thresholds:
运行此示例将输出以下输出: 运行此示例将输出以下输出:
``` ```py
Accuracy: 77.95% Accuracy: 77.95%
Thresh=0.071, n=8, Accuracy: 77.95% Thresh=0.071, n=8, Accuracy: 77.95%
Thresh=0.073, n=7, Accuracy: 76.38% Thresh=0.073, n=7, Accuracy: 76.38%
......
...@@ -221,7 +221,7 @@ You can review the slides from his talk here: ...@@ -221,7 +221,7 @@ You can review the slides from his talk here:
要快速入门,您可以输入: 要快速入门,您可以输入:
``` ```py
sudo pip install xgboost sudo pip install xgboost
``` ```
......
...@@ -37,20 +37,20 @@ XGBoost 是一个用于开发非常快速和准确的梯度提升模型的库。 ...@@ -37,20 +37,20 @@ XGBoost 是一个用于开发非常快速和准确的梯度提升模型的库。
* 2.安装 MacPorts 和可用的 Python 环境后,您可以按如下方式安装和选择 GCC 7: * 2.安装 MacPorts 和可用的 Python 环境后,您可以按如下方式安装和选择 GCC 7:
``` ```py
sudo port install gcc7 sudo port install gcc7
sudo port select --set gcc mp-gcc7 sudo port select --set gcc mp-gcc7
``` ```
* 3.确认您的 GCC 安装成功,如下所示: * 3.确认您的 GCC 安装成功,如下所示:
``` ```py
gcc -v gcc -v
``` ```
你应该看到印刷版的 GCC;例如: 你应该看到印刷版的 GCC;例如:
``` ```py
.. ..
gcc version 7.2.0 (MacPorts gcc7 7.2.0_0) gcc version 7.2.0 (MacPorts gcc7 7.2.0_0)
``` ```
...@@ -64,25 +64,25 @@ gcc version 7.2.0 (MacPorts gcc7 7.2.0_0) ...@@ -64,25 +64,25 @@ gcc version 7.2.0 (MacPorts gcc7 7.2.0_0)
* 1.首先,从 GitHub 查看代码库: * 1.首先,从 GitHub 查看代码库:
``` ```py
git clone --recursive https://github.com/dmlc/xgboost git clone --recursive https://github.com/dmlc/xgboost
``` ```
* 2.转到 xgboost 目录。 * 2.转到 xgboost 目录。
``` ```py
cd xgboost/ cd xgboost/
``` ```
* 3.复制我们打算用来将 XGBoost 编译到位的配置。 * 3.复制我们打算用来将 XGBoost 编译到位的配置。
``` ```py
cp make/config.mk ./config.mk cp make/config.mk ./config.mk
``` ```
* 4.编译 XGBoost;这要求您指定系统上的核心数(例如,8,根据需要进行更改)。 * 4.编译 XGBoost;这要求您指定系统上的核心数(例如,8,根据需要进行更改)。
``` ```py
make -j8 make -j8
``` ```
...@@ -90,7 +90,7 @@ make -j8 ...@@ -90,7 +90,7 @@ make -j8
例如,编译的最后一个片段可能如下所示: 例如,编译的最后一个片段可能如下所示:
``` ```py
... ...
a - build/learner.o a - build/learner.o
a - build/logging.o a - build/logging.o
...@@ -139,13 +139,13 @@ c++ -std=c++11 -Wall -Wno-unknown-pragmas -Iinclude -Idmlc-core/include -Irabit/ ...@@ -139,13 +139,13 @@ c++ -std=c++11 -Wall -Wno-unknown-pragmas -Iinclude -Idmlc-core/include -Irabit/
* 1.将目录更改为 xgboost 项目的 Python 包。 * 1.将目录更改为 xgboost 项目的 Python 包。
``` ```py
cd python-package cd python-package
``` ```
* 2.安装 Python XGBoost 包。 * 2.安装 Python XGBoost 包。
``` ```py
sudo python setup.py install sudo python setup.py install
``` ```
...@@ -153,7 +153,7 @@ sudo python setup.py install ...@@ -153,7 +153,7 @@ sudo python setup.py install
例如,在安装结束时,您可能会看到如下消息: 例如,在安装结束时,您可能会看到如下消息:
``` ```py
... ...
Installed /opt/local/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/xgboost-0.6-py3.6.egg Installed /opt/local/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/xgboost-0.6-py3.6.egg
Processing dependencies for xgboost==0.6 Processing dependencies for xgboost==0.6
...@@ -174,20 +174,20 @@ Finished processing dependencies for xgboost==0.6 ...@@ -174,20 +174,20 @@ Finished processing dependencies for xgboost==0.6
将以下代码保存到名为 _version.py 的文件中。_ 将以下代码保存到名为 _version.py 的文件中。_
``` ```py
import xgboost import xgboost
print("xgboost", xgboost.__version__) print("xgboost", xgboost.__version__)
``` ```
从命令行运行脚本: 从命令行运行脚本:
``` ```py
python version.py python version.py
``` ```
您应该看到 XGBoost 版本打印到屏幕: 您应该看到 XGBoost 版本打印到屏幕:
``` ```py
xgboost 0.6 xgboost 0.6
``` ```
......
...@@ -29,14 +29,14 @@ Pickle 是在 Python 中序列化对象的标准方法。 ...@@ -29,14 +29,14 @@ Pickle 是在 Python 中序列化对象的标准方法。
您可以使用 [Python pickle API](https://docs.python.org/2/library/pickle.html) 序列化您的机器学习算法并将序列化格式保存到文件中,例如: 您可以使用 [Python pickle API](https://docs.python.org/2/library/pickle.html) 序列化您的机器学习算法并将序列化格式保存到文件中,例如:
``` ```py
# save model to file # save model to file
pickle.dump(model, open("pima.pickle.dat", "wb")) pickle.dump(model, open("pima.pickle.dat", "wb"))
``` ```
稍后您可以加载此文件以反序列化模型并使用它来进行新的预测,例如: 稍后您可以加载此文件以反序列化模型并使用它来进行新的预测,例如:
``` ```py
# load model from file # load model from file
loaded_model = pickle.load(open("pima.pickle.dat", "rb")) loaded_model = pickle.load(open("pima.pickle.dat", "rb"))
``` ```
...@@ -45,7 +45,7 @@ loaded_model = pickle.load(open("pima.pickle.dat", "rb")) ...@@ -45,7 +45,7 @@ loaded_model = pickle.load(open("pima.pickle.dat", "rb"))
完整性代码清单如下所示。 完整性代码清单如下所示。
``` ```py
# Train XGBoost model, save to file using pickle, load and make predictions # Train XGBoost model, save to file using pickle, load and make predictions
from numpy import loadtxt from numpy import loadtxt
import xgboost import xgboost
...@@ -81,13 +81,13 @@ print("Accuracy: %.2f%%" % (accuracy * 100.0)) ...@@ -81,13 +81,13 @@ print("Accuracy: %.2f%%" % (accuracy * 100.0))
运行此示例将训练有素的 XGBoost 模型保存到当前工作目录中的 **pima.pickle.dat** pickle 文件中。 运行此示例将训练有素的 XGBoost 模型保存到当前工作目录中的 **pima.pickle.dat** pickle 文件中。
``` ```py
pima.pickle.dat pima.pickle.dat
``` ```
加载模型并对训练数据集进行预测后,将打印模型的准确性。 加载模型并对训练数据集进行预测后,将打印模型的准确性。
``` ```py
Accuracy: 77.95% Accuracy: 77.95%
``` ```
...@@ -99,21 +99,21 @@ Joblib 是 SciPy 生态系统的一部分,并提供用于管道化 Python 作 ...@@ -99,21 +99,21 @@ Joblib 是 SciPy 生态系统的一部分,并提供用于管道化 Python 作
API 看起来很像 pickle API,例如,您可以保存训练有素的模型,如下所示: API 看起来很像 pickle API,例如,您可以保存训练有素的模型,如下所示:
``` ```py
# save model to file # save model to file
joblib.dump(model, "pima.joblib.dat") joblib.dump(model, "pima.joblib.dat")
``` ```
您可以稍后从文件加载模型并使用它来进行如下预测: 您可以稍后从文件加载模型并使用它来进行如下预测:
``` ```py
# load model from file # load model from file
loaded_model = joblib.load("pima.joblib.dat") loaded_model = joblib.load("pima.joblib.dat")
``` ```
下面的示例演示了如何训练 XGBoost 模型在 Pima Indians 糖尿病数据集开始时进行分类,使用 Joblib 将模型保存到文件中,并在以后加载它以进行预测。 下面的示例演示了如何训练 XGBoost 模型在 Pima Indians 糖尿病数据集开始时进行分类,使用 Joblib 将模型保存到文件中,并在以后加载它以进行预测。
``` ```py
# Train XGBoost model, save to file using joblib, load and make predictions # Train XGBoost model, save to file using joblib, load and make predictions
from numpy import loadtxt from numpy import loadtxt
import xgboost import xgboost
...@@ -149,7 +149,7 @@ print("Accuracy: %.2f%%" % (accuracy * 100.0)) ...@@ -149,7 +149,7 @@ print("Accuracy: %.2f%%" % (accuracy * 100.0))
运行该示例将模型保存为当前工作目录中的 **pima.joblib.dat** 文件,并为模型中的每个 NumPy 数组创建一个文件(在本例中为两个附加文件)。 运行该示例将模型保存为当前工作目录中的 **pima.joblib.dat** 文件,并为模型中的每个 NumPy 数组创建一个文件(在本例中为两个附加文件)。
``` ```py
pima.joblib.dat pima.joblib.dat
pima.joblib.dat_01.npy pima.joblib.dat_01.npy
pima.joblib.dat_02.npy pima.joblib.dat_02.npy
...@@ -157,7 +157,7 @@ pima.joblib.dat_02.npy ...@@ -157,7 +157,7 @@ pima.joblib.dat_02.npy
加载模型后,将在训练数据集上对其进行评估,并打印预测的准确性。 加载模型后,将在训练数据集上对其进行评估,并打印预测的准确性。
``` ```py
Accuracy: 77.95% Accuracy: 77.95%
``` ```
......
...@@ -71,7 +71,7 @@ ...@@ -71,7 +71,7 @@
我们可以使用 scikit-learn 内置的网格搜索功能来评估 Otto 数据集中 0.1 到 1.0 的不同子样本值的影响。 我们可以使用 scikit-learn 内置的网格搜索功能来评估 Otto 数据集中 0.1 到 1.0 的不同子样本值的影响。
``` ```py
[0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 1.0] [0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 1.0]
``` ```
...@@ -79,7 +79,7 @@ ...@@ -79,7 +79,7 @@
完整的代码清单如下。 完整的代码清单如下。
``` ```py
# XGBoost on Otto dataset, tune subsample # XGBoost on Otto dataset, tune subsample
from pandas import read_csv from pandas import read_csv
from xgboost import XGBClassifier from xgboost import XGBClassifier
...@@ -123,7 +123,7 @@ pyplot.savefig('subsample.png') ...@@ -123,7 +123,7 @@ pyplot.savefig('subsample.png')
我们可以看到,获得的最佳结果是 0.3,或使用 30%的训练数据集样本训练树。 我们可以看到,获得的最佳结果是 0.3,或使用 30%的训练数据集样本训练树。
``` ```py
Best: -0.000647 using {'subsample': 0.3} Best: -0.000647 using {'subsample': 0.3}
-0.001156 (0.000286) with: {'subsample': 0.1} -0.001156 (0.000286) with: {'subsample': 0.1}
-0.000765 (0.000430) with: {'subsample': 0.2} -0.000765 (0.000430) with: {'subsample': 0.2}
...@@ -154,13 +154,13 @@ XGBoost 中调整行采样率的图 ...@@ -154,13 +154,13 @@ XGBoost 中调整行采样率的图
默认值为 1.0,表示在每个决策树中使用所有列。我们可以评估 **colsample_bytree** 的值在 0.1 和 1.0 之间递增 0.1。 默认值为 1.0,表示在每个决策树中使用所有列。我们可以评估 **colsample_bytree** 的值在 0.1 和 1.0 之间递增 0.1。
``` ```py
[0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 1.0] [0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 1.0]
``` ```
完整的代码清单如下。 完整的代码清单如下。
``` ```py
# XGBoost on Otto dataset, tune colsample_bytree # XGBoost on Otto dataset, tune colsample_bytree
from pandas import read_csv from pandas import read_csv
from xgboost import XGBClassifier from xgboost import XGBClassifier
...@@ -204,7 +204,7 @@ Running this example prints the best configuration as well as the log loss for e ...@@ -204,7 +204,7 @@ Running this example prints the best configuration as well as the log loss for e
我们可以看到该模型的最佳性能是 **colsample_bytree = 1.0** 。这表明对此问题的子采样列不会增加价值。 我们可以看到该模型的最佳性能是 **colsample_bytree = 1.0** 。这表明对此问题的子采样列不会增加价值。
``` ```py
Best: -0.001239 using {'colsample_bytree': 1.0} Best: -0.001239 using {'colsample_bytree': 1.0}
-0.298955 (0.002177) with: {'colsample_bytree': 0.1} -0.298955 (0.002177) with: {'colsample_bytree': 0.1}
-0.092441 (0.000798) with: {'colsample_bytree': 0.2} -0.092441 (0.000798) with: {'colsample_bytree': 0.2}
...@@ -233,7 +233,7 @@ Best: -0.001239 using {'colsample_bytree': 1.0} ...@@ -233,7 +233,7 @@ Best: -0.001239 using {'colsample_bytree': 1.0}
The full code listing is provided below. The full code listing is provided below.
``` ```py
# XGBoost on Otto dataset, tune colsample_bylevel # XGBoost on Otto dataset, tune colsample_bylevel
from pandas import read_csv from pandas import read_csv
from xgboost import XGBClassifier from xgboost import XGBClassifier
...@@ -279,7 +279,7 @@ Running this example prints the best configuration as well as the log loss for e ...@@ -279,7 +279,7 @@ Running this example prints the best configuration as well as the log loss for e
如果每个树的结果建议使用 100%的列,那么建议不要放弃列子采样,而是尝试按每个拆分列子采样。 如果每个树的结果建议使用 100%的列,那么建议不要放弃列子采样,而是尝试按每个拆分列子采样。
``` ```py
Best: -0.001062 using {'colsample_bylevel': 0.7} Best: -0.001062 using {'colsample_bylevel': 0.7}
-0.159455 (0.007028) with: {'colsample_bylevel': 0.1} -0.159455 (0.007028) with: {'colsample_bylevel': 0.1}
-0.034391 (0.003533) with: {'colsample_bylevel': 0.2} -0.034391 (0.003533) with: {'colsample_bylevel': 0.2}
......
...@@ -109,7 +109,7 @@ AWS 控制台 ...@@ -109,7 +109,7 @@ AWS 控制台
* 12.打开终端并将目录更改为您下载密钥对的位置。 * 12.打开终端并将目录更改为您下载密钥对的位置。
* 13.如果尚未执行此操作,请限制密钥对文件的访问权限。这是 SSH 访问服务器的一部分。例如,在您的控制台上,您可以键入: * 13.如果尚未执行此操作,请限制密钥对文件的访问权限。这是 SSH 访问服务器的一部分。例如,在您的控制台上,您可以键入:
``` ```py
cd Downloads cd Downloads
chmod 600 xgboost-keypair.pem chmod 600 xgboost-keypair.pem
``` ```
...@@ -142,7 +142,7 @@ chmod 600 xgboost-keypair.pem ...@@ -142,7 +142,7 @@ chmod 600 xgboost-keypair.pem
* 3.打开终端并将目录更改为您下载密钥对的位置。使用 SSH 登录您的服务器,例如您可以输入: * 3.打开终端并将目录更改为您下载密钥对的位置。使用 SSH 登录您的服务器,例如您可以输入:
``` ```py
ssh -i xgboost-keypair.pem fedora@52.53.185.166 ssh -i xgboost-keypair.pem fedora@52.53.185.166
``` ```
...@@ -152,13 +152,13 @@ ssh -i xgboost-keypair.pem fedora@52.53.185.166 ...@@ -152,13 +152,13 @@ ssh -i xgboost-keypair.pem fedora@52.53.185.166
通过键入,仔细检查实例上的 CPU 核心数 通过键入,仔细检查实例上的 CPU 核心数
``` ```py
cat /proc/cpuinfo | grep processor | wc -l cat /proc/cpuinfo | grep processor | wc -l
``` ```
你应该看到: 你应该看到:
``` ```py
32 32
``` ```
...@@ -170,7 +170,7 @@ cat /proc/cpuinfo | grep processor | wc -l ...@@ -170,7 +170,7 @@ cat /proc/cpuinfo | grep processor | wc -l
这是一行: 这是一行:
``` ```py
sudo dnf install gcc gcc-c++ make git unzip python python2-numpy python2-scipy python2-scikit-learn python2-pandas python2-matplotlib sudo dnf install gcc gcc-c++ make git unzip python python2-numpy python2-scipy python2-scikit-learn python2-pandas python2-matplotlib
``` ```
...@@ -184,13 +184,13 @@ sudo dnf install gcc gcc-c++ make git unzip python python2-numpy python2-scipy p ...@@ -184,13 +184,13 @@ sudo dnf install gcc gcc-c++ make git unzip python python2-numpy python2-scipy p
类型: 类型:
``` ```py
gcc --version gcc --version
``` ```
You should see: You should see:
``` ```py
gcc (GCC) 6.1.1 20160621 (Red Hat 6.1.1-3) gcc (GCC) 6.1.1 20160621 (Red Hat 6.1.1-3)
Copyright (C) 2016 Free Software Foundation, Inc. Copyright (C) 2016 Free Software Foundation, Inc.
This is free software; see the source for copying conditions. There is NO This is free software; see the source for copying conditions. There is NO
...@@ -201,13 +201,13 @@ warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. ...@@ -201,13 +201,13 @@ warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
Type: Type:
``` ```py
python --version python --version
``` ```
You should see: You should see:
``` ```py
Python 2.7.12 Python 2.7.12
``` ```
...@@ -215,7 +215,7 @@ Python 2.7.12 ...@@ -215,7 +215,7 @@ Python 2.7.12
Type: Type:
``` ```py
python -c "import scipy;print(scipy.__version__)" python -c "import scipy;print(scipy.__version__)"
python -c "import numpy;print(numpy.__version__)" python -c "import numpy;print(numpy.__version__)"
python -c "import pandas;print(pandas.__version__)" python -c "import pandas;print(pandas.__version__)"
...@@ -224,7 +224,7 @@ python -c "import sklearn;print(sklearn.__version__)" ...@@ -224,7 +224,7 @@ python -c "import sklearn;print(sklearn.__version__)"
你应该看到类似的东西: 你应该看到类似的东西:
``` ```py
0.16.1 0.16.1
1.11.0 1.11.0
0.18.0 0.18.0
...@@ -241,7 +241,7 @@ XGBoost 的[安装说明已完成,我们可以直接关注它们。](https://x ...@@ -241,7 +241,7 @@ XGBoost 的[安装说明已完成,我们可以直接关注它们。](https://x
首先,我们需要在服务器上下载项目。 首先,我们需要在服务器上下载项目。
``` ```py
git clone --recursive https://github.com/dmlc/xgboost git clone --recursive https://github.com/dmlc/xgboost
cd xgboost cd xgboost
``` ```
...@@ -250,7 +250,7 @@ cd xgboost ...@@ -250,7 +250,7 @@ cd xgboost
如果您选择了不同的 AWS 硬件,则可以适当地进行设置。 如果您选择了不同的 AWS 硬件,则可以适当地进行设置。
``` ```py
make -j32 make -j32
``` ```
...@@ -258,7 +258,7 @@ XGBoost 项目应该成功构建(例如没有错误)。 ...@@ -258,7 +258,7 @@ XGBoost 项目应该成功构建(例如没有错误)。
我们现在准备安装该库的 Python 版本。 我们现在准备安装该库的 Python 版本。
``` ```py
cd python-package cd python-package
sudo python setup.py install sudo python setup.py install
``` ```
...@@ -267,13 +267,13 @@ sudo python setup.py install ...@@ -267,13 +267,13 @@ sudo python setup.py install
我们可以输入以下内容确认安装是否成功: 我们可以输入以下内容确认安装是否成功:
``` ```py
python -c "import xgboost;print(xgboost.__version__)" python -c "import xgboost;print(xgboost.__version__)"
``` ```
这应该打印如下: 这应该打印如下:
``` ```py
0.4 0.4
``` ```
...@@ -299,7 +299,7 @@ python -c "import xgboost;print(xgboost.__version__)" ...@@ -299,7 +299,7 @@ python -c "import xgboost;print(xgboost.__version__)"
下面列出了完整的示例。将其保存在名为 **work / script.py** 的文件中。 下面列出了完整的示例。将其保存在名为 **work / script.py** 的文件中。
``` ```py
# Otto multi-core test # Otto multi-core test
from pandas import read_csv from pandas import read_csv
from xgboost import XGBClassifier from xgboost import XGBClassifier
...@@ -329,7 +329,7 @@ for n in num_threads: ...@@ -329,7 +329,7 @@ for n in num_threads:
**工作/** 目录所在的当前目录中的工作站,键入: **工作/** 目录所在的当前目录中的工作站,键入:
``` ```py
scp -r -i xgboost-keypair.pem work fedora@52.53.185.166:/home/fedora/ scp -r -i xgboost-keypair.pem work fedora@52.53.185.166:/home/fedora/
``` ```
...@@ -339,26 +339,26 @@ scp -r -i xgboost-keypair.pem work fedora@52.53.185.166:/home/fedora/ ...@@ -339,26 +339,26 @@ scp -r -i xgboost-keypair.pem work fedora@52.53.185.166:/home/fedora/
重新登录到您的服务器实例(如果需要): 重新登录到您的服务器实例(如果需要):
``` ```py
ssh -i xgboost-keypair.pem fedora@52.53.185.166 ssh -i xgboost-keypair.pem fedora@52.53.185.166
``` ```
将目录更改为工作目录并解压缩训练数据。 将目录更改为工作目录并解压缩训练数据。
``` ```py
cd work cd work
unzip ./train.csv.data unzip ./train.csv.data
``` ```
现在我们可以运行脚本并训练我们的 XGBoost 模型并计算使用不同数量的核心所需的时间: 现在我们可以运行脚本并训练我们的 XGBoost 模型并计算使用不同数量的核心所需的时间:
``` ```py
python script.py python script.py
``` ```
您应该看到如下输出: 您应该看到如下输出:
``` ```py
(1, 84.26896095275879) (1, 84.26896095275879)
(16, 6.597043037414551) (16, 6.597043037414551)
(32, 7.6703619956970215) (32, 7.6703619956970215)
...@@ -372,7 +372,7 @@ python script.py ...@@ -372,7 +372,7 @@ python script.py
您可以将代码作为后台进程运行,并通过键入以下内容将输出重定向到文件: 您可以将代码作为后台进程运行,并通过键入以下内容将输出重定向到文件:
``` ```py
nohup python script.py >script.py.out 2>&1 & nohup python script.py >script.py.out 2>&1 &
``` ```
...@@ -386,7 +386,7 @@ nohup python script.py >script.py.out 2>&1 & ...@@ -386,7 +386,7 @@ nohup python script.py >script.py.out 2>&1 &
* 1.在终端注销您的实例,例如您可以输入: * 1.在终端注销您的实例,例如您可以输入:
``` ```py
exit exit
``` ```
......
...@@ -61,7 +61,7 @@ ...@@ -61,7 +61,7 @@
我们将树的数量保持为默认值 100,并评估 Otto 数据集上学习率的标准值套件。 我们将树的数量保持为默认值 100,并评估 Otto 数据集上学习率的标准值套件。
``` ```py
learning_rate = [0.0001, 0.001, 0.01, 0.1, 0.2, 0.3] learning_rate = [0.0001, 0.001, 0.01, 0.1, 0.2, 0.3]
``` ```
...@@ -69,7 +69,7 @@ learning_rate = [0.0001, 0.001, 0.01, 0.1, 0.2, 0.3] ...@@ -69,7 +69,7 @@ learning_rate = [0.0001, 0.001, 0.01, 0.1, 0.2, 0.3]
将打印每个学习率的对数损失以及导致最佳性能的值。 将打印每个学习率的对数损失以及导致最佳性能的值。
``` ```py
# XGBoost on Otto dataset, Tune learning_rate # XGBoost on Otto dataset, Tune learning_rate
from pandas import read_csv from pandas import read_csv
from xgboost import XGBClassifier from xgboost import XGBClassifier
...@@ -111,7 +111,7 @@ pyplot.savefig('learning_rate.png') ...@@ -111,7 +111,7 @@ pyplot.savefig('learning_rate.png')
运行此示例将打印每个评估学习速率的最佳结果以及日志丢失。 运行此示例将打印每个评估学习速率的最佳结果以及日志丢失。
``` ```py
Best: -0.001156 using {'learning_rate': 0.2} Best: -0.001156 using {'learning_rate': 0.2}
-2.155497 (0.000081) with: {'learning_rate': 0.0001} -2.155497 (0.000081) with: {'learning_rate': 0.0001}
-1.841069 (0.000716) with: {'learning_rate': 0.001} -1.841069 (0.000716) with: {'learning_rate': 0.001}
...@@ -139,7 +139,7 @@ Best: -0.001156 using {'learning_rate': 0.2} ...@@ -139,7 +139,7 @@ Best: -0.001156 using {'learning_rate': 0.2}
我们可以通过评估参数对的网格来探索这种关系。决策树的数量将在 100 到 500 之间变化,学习率在 log10 范围内从 0.0001 变化到 0.1。 我们可以通过评估参数对的网格来探索这种关系。决策树的数量将在 100 到 500 之间变化,学习率在 log10 范围内从 0.0001 变化到 0.1。
``` ```py
n_estimators = [100, 200, 300, 400, 500] n_estimators = [100, 200, 300, 400, 500]
learning_rate = [0.0001, 0.001, 0.01, 0.1] learning_rate = [0.0001, 0.001, 0.01, 0.1]
``` ```
...@@ -148,7 +148,7 @@ learning_rate = [0.0001, 0.001, 0.01, 0.1] ...@@ -148,7 +148,7 @@ learning_rate = [0.0001, 0.001, 0.01, 0.1]
期望的是,对于给定的学习率,随着树木数量的增加,性能将提高然后稳定。完整的代码清单如下。 期望的是,对于给定的学习率,随着树木数量的增加,性能将提高然后稳定。完整的代码清单如下。
``` ```py
# XGBoost on Otto dataset, Tune learning_rate and n_estimators # XGBoost on Otto dataset, Tune learning_rate and n_estimators
from pandas import read_csv from pandas import read_csv
from xgboost import XGBClassifier from xgboost import XGBClassifier
...@@ -194,7 +194,7 @@ pyplot.savefig('n_estimators_vs_learning_rate.png') ...@@ -194,7 +194,7 @@ pyplot.savefig('n_estimators_vs_learning_rate.png')
运行该示例将打印每个已评估对的最佳组合以及日志丢失。 运行该示例将打印每个已评估对的最佳组合以及日志丢失。
``` ```py
Best: -0.001152 using {'n_estimators': 300, 'learning_rate': 0.1} Best: -0.001152 using {'n_estimators': 300, 'learning_rate': 0.1}
-2.155497 (0.000081) with: {'n_estimators': 100, 'learning_rate': 0.0001} -2.155497 (0.000081) with: {'n_estimators': 100, 'learning_rate': 0.0001}
-2.115540 (0.000159) with: {'n_estimators': 200, 'learning_rate': 0.0001} -2.115540 (0.000159) with: {'n_estimators': 200, 'learning_rate': 0.0001}
...@@ -232,7 +232,7 @@ Best: -0.001152 using {'n_estimators': 300, 'learning_rate': 0.1} ...@@ -232,7 +232,7 @@ Best: -0.001152 using {'n_estimators': 300, 'learning_rate': 0.1}
由于图的大 y 轴比例, **learning_rate = 0.1** 的结果变得模糊。我们可以只为 **learning_rate = 0.1** 提取性能测量并直接绘制它们。 由于图的大 y 轴比例, **learning_rate = 0.1** 的结果变得模糊。我们可以只为 **learning_rate = 0.1** 提取性能测量并直接绘制它们。
``` ```py
# Plot performance for learning_rate=0.1 # Plot performance for learning_rate=0.1
from matplotlib import pyplot from matplotlib import pyplot
n_estimators = [100, 200, 300, 400, 500] n_estimators = [100, 200, 300, 400, 500]
......
...@@ -49,7 +49,7 @@ XGBoost 模型中的树(或舍入)数量是在 n_estimators 参数中指定 ...@@ -49,7 +49,7 @@ XGBoost 模型中的树(或舍入)数量是在 n_estimators 参数中指定
使用 scikit-learn,我们可以对 **n_estimators** 模型参数进行网格搜索,评估 50 到 350 的一系列值,步长为 50(50,150,200,250,300,350) 。 使用 scikit-learn,我们可以对 **n_estimators** 模型参数进行网格搜索,评估 50 到 350 的一系列值,步长为 50(50,150,200,250,300,350) 。
``` ```py
# grid search # grid search
model = XGBClassifier() model = XGBClassifier()
n_estimators = range(50, 400, 50) n_estimators = range(50, 400, 50)
...@@ -62,7 +62,7 @@ result = grid_search.fit(X, label_encoded_y) ...@@ -62,7 +62,7 @@ result = grid_search.fit(X, label_encoded_y)
完整性代码清单如下所示。 完整性代码清单如下所示。
``` ```py
# XGBoost on Otto dataset, Tune n_estimators # XGBoost on Otto dataset, Tune n_estimators
from pandas import read_csv from pandas import read_csv
from xgboost import XGBClassifier from xgboost import XGBClassifier
...@@ -104,7 +104,7 @@ pyplot.savefig('n_estimators.png') ...@@ -104,7 +104,7 @@ pyplot.savefig('n_estimators.png')
运行此示例将打印以下结果。 运行此示例将打印以下结果。
``` ```py
Best: -0.001152 using {'n_estimators': 250} Best: -0.001152 using {'n_estimators': 250}
-0.010970 (0.001083) with: {'n_estimators': 50} -0.010970 (0.001083) with: {'n_estimators': 50}
-0.001239 (0.001730) with: {'n_estimators': 100} -0.001239 (0.001730) with: {'n_estimators': 100}
...@@ -135,7 +135,7 @@ Best: -0.001152 using {'n_estimators': 250} ...@@ -135,7 +135,7 @@ Best: -0.001152 using {'n_estimators': 250}
可以在 **max_depth** 参数中的 **XGBC 分类器****XGBRegressor** XGBoost 包装类中指定最大深度。此参数采用整数值,默认值为 3。 可以在 **max_depth** 参数中的 **XGBC 分类器****XGBRegressor** XGBoost 包装类中指定最大深度。此参数采用整数值,默认值为 3。
``` ```py
model = XGBClassifier(max_depth=3) model = XGBClassifier(max_depth=3)
``` ```
...@@ -143,7 +143,7 @@ model = XGBClassifier(max_depth=3) ...@@ -143,7 +143,7 @@ model = XGBClassifier(max_depth=3)
使用 10 倍交叉验证评估 5 种配置中的每一种,从而构建 50 个模型。完整性代码清单如下所示。 使用 10 倍交叉验证评估 5 种配置中的每一种,从而构建 50 个模型。完整性代码清单如下所示。
``` ```py
# XGBoost on Otto dataset, Tune max_depth # XGBoost on Otto dataset, Tune max_depth
from pandas import read_csv from pandas import read_csv
from xgboost import XGBClassifier from xgboost import XGBClassifier
...@@ -188,7 +188,7 @@ pyplot.savefig('max_depth.png') ...@@ -188,7 +188,7 @@ pyplot.savefig('max_depth.png')
最佳配置为 **max_depth = 5** ,导致对数损失为 0.001236。 最佳配置为 **max_depth = 5** ,导致对数损失为 0.001236。
``` ```py
Best: -0.001236 using {'max_depth': 5} Best: -0.001236 using {'max_depth': 5}
-0.026235 (0.000898) with: {'max_depth': 1} -0.026235 (0.000898) with: {'max_depth': 1}
-0.001239 (0.001730) with: {'max_depth': 3} -0.001239 (0.001730) with: {'max_depth': 3}
...@@ -219,7 +219,7 @@ Best: -0.001236 using {'max_depth': 5} ...@@ -219,7 +219,7 @@ Best: -0.001236 using {'max_depth': 5}
完整的代码清单如下。 完整的代码清单如下。
``` ```py
# XGBoost on Otto dataset, Tune n_estimators and max_depth # XGBoost on Otto dataset, Tune n_estimators and max_depth
from pandas import read_csv from pandas import read_csv
from xgboost import XGBClassifier from xgboost import XGBClassifier
...@@ -266,7 +266,7 @@ pyplot.savefig('n_estimators_vs_max_depth.png') ...@@ -266,7 +266,7 @@ pyplot.savefig('n_estimators_vs_max_depth.png')
运行代码会生成每个参数对的 logloss 列表。 运行代码会生成每个参数对的 logloss 列表。
``` ```py
Best: -0.001141 using {'n_estimators': 200, 'max_depth': 4} Best: -0.001141 using {'n_estimators': 200, 'max_depth': 4}
-0.012127 (0.001130) with: {'n_estimators': 50, 'max_depth': 2} -0.012127 (0.001130) with: {'n_estimators': 50, 'max_depth': 2}
-0.001351 (0.001825) with: {'n_estimators': 100, 'max_depth': 2} -0.001351 (0.001825) with: {'n_estimators': 100, 'max_depth': 2}
......
...@@ -21,7 +21,7 @@ ...@@ -21,7 +21,7 @@
**plot_tree()**函数提供了此功能,该函数将训练模型作为第一个参数,例如: **plot_tree()**函数提供了此功能,该函数将训练模型作为第一个参数,例如:
``` ```py
plot_tree(model) plot_tree(model)
``` ```
...@@ -31,7 +31,7 @@ plot_tree(model) ...@@ -31,7 +31,7 @@ plot_tree(model)
我们可以在 [Pima 印第安人糖尿病数据集](https://archive.ics.uci.edu/ml/datasets/Pima+Indians+Diabetes)上创建一个 XGBoost 模型,并绘制模型中的第一棵树(更新:[从这里下载](https://raw.githubusercontent.com/jbrownlee/Datasets/master/pima-indians-diabetes.data.csv))。完整的代码清单如下: 我们可以在 [Pima 印第安人糖尿病数据集](https://archive.ics.uci.edu/ml/datasets/Pima+Indians+Diabetes)上创建一个 XGBoost 模型,并绘制模型中的第一棵树(更新:[从这里下载](https://raw.githubusercontent.com/jbrownlee/Datasets/master/pima-indians-diabetes.data.csv))。完整的代码清单如下:
``` ```py
# plot decision tree # plot decision tree
from numpy import loadtxt from numpy import loadtxt
from xgboost import XGBClassifier from xgboost import XGBClassifier
...@@ -62,13 +62,13 @@ plt.show() ...@@ -62,13 +62,13 @@ plt.show()
**plot_tree()**函数需要一些参数。您可以通过指定 **num_trees** 参数的索引来绘制特定图形。例如,您可以按顺序绘制序列中的第 5 个提升树: **plot_tree()**函数需要一些参数。您可以通过指定 **num_trees** 参数的索引来绘制特定图形。例如,您可以按顺序绘制序列中的第 5 个提升树:
``` ```py
plot_tree(model, num_trees=4) plot_tree(model, num_trees=4)
``` ```
您还可以通过将 **rankdir** 参数更改为“LR”(从左到右)而不是默认的从上到下(UT)来更改图表的布局从左到右(更容易阅读) )。例如: 您还可以通过将 **rankdir** 参数更改为“LR”(从左到右)而不是默认的从上到下(UT)来更改图表的布局从左到右(更容易阅读) )。例如:
``` ```py
plot_tree(model, num_trees=0, rankdir='LR') plot_tree(model, num_trees=0, rankdir='LR')
``` ```
......
...@@ -122,7 +122,7 @@ XGBoost 开发中的性能已经成为最好的预测建模算法之一,现在 ...@@ -122,7 +122,7 @@ XGBoost 开发中的性能已经成为最好的预测建模算法之一,现在
例如: 例如:
``` ```py
sudo pip install xgboost sudo pip install xgboost
``` ```
...@@ -136,20 +136,20 @@ XGBoost 模型可以使用包装类直接在 scikit-learn 框架中使用, **X ...@@ -136,20 +136,20 @@ XGBoost 模型可以使用包装类直接在 scikit-learn 框架中使用, **X
我们可以通过构造它并调用 **model.fit()**函数来训练 XGBoost 模型进行分类: 我们可以通过构造它并调用 **model.fit()**函数来训练 XGBoost 模型进行分类:
``` ```py
model = XGBClassifier() model = XGBClassifier()
model.fit(X_train, y_train) model.fit(X_train, y_train)
``` ```
然后可以通过在新数据上调用 **model.predict()**函数来使用该模型进行预测。 然后可以通过在新数据上调用 **model.predict()**函数来使用该模型进行预测。
``` ```py
y_pred = model.predict(X_test) y_pred = model.predict(X_test)
``` ```
我们可以将这些结合起来如下: 我们可以将这些结合起来如下:
``` ```py
# First XGBoost model for Pima Indians dataset # First XGBoost model for Pima Indians dataset
from numpy import loadtxt from numpy import loadtxt
from xgboost import XGBClassifier from xgboost import XGBClassifier
...@@ -185,14 +185,14 @@ XGBoost 模型可以在训练期间评估和报告模型的测试集上的性能 ...@@ -185,14 +185,14 @@ XGBoost 模型可以在训练期间评估和报告模型的测试集上的性能
例如,我们可以在训练 XGBoost 模型时报告独立测试集( **eval_set** )上的二进制分类错误率(**错误**),如下所示: 例如,我们可以在训练 XGBoost 模型时报告独立测试集( **eval_set** )上的二进制分类错误率(**错误**),如下所示:
``` ```py
eval_set = [(X_test, y_test)] eval_set = [(X_test, y_test)]
model.fit(X_train, y_train, eval_metric="error", eval_set=eval_set, verbose=True) model.fit(X_train, y_train, eval_metric="error", eval_set=eval_set, verbose=True)
``` ```
使用此配置运行模型将在添加每个树后报告模型的性能。例如: 使用此配置运行模型将在添加每个树后报告模型的性能。例如:
``` ```py
... ...
[89] validation_0-error:0.204724 [89] validation_0-error:0.204724
[90] validation_0-error:0.208661 [90] validation_0-error:0.208661
...@@ -204,7 +204,7 @@ model.fit(X_train, y_train, eval_metric="error", eval_set=eval_set, verbose=True ...@@ -204,7 +204,7 @@ model.fit(X_train, y_train, eval_metric="error", eval_set=eval_set, verbose=True
下面提供了使用 Pima Indians Onset of Diabetes 数据集的完整示例。 下面提供了使用 Pima Indians Onset of Diabetes 数据集的完整示例。
``` ```py
# exmaple of early stopping # exmaple of early stopping
from numpy import loadtxt from numpy import loadtxt
from xgboost import XGBClassifier from xgboost import XGBClassifier
...@@ -241,7 +241,7 @@ print("Accuracy: %.2f%%" % (accuracy * 100.0)) ...@@ -241,7 +241,7 @@ print("Accuracy: %.2f%%" % (accuracy * 100.0))
这些重要性分数可在训练模型的 **feature_importances_** 成员变量中找到。例如,它们可以直接打印如下: 这些重要性分数可在训练模型的 **feature_importances_** 成员变量中找到。例如,它们可以直接打印如下:
``` ```py
print(model.feature_importances_) print(model.feature_importances_)
``` ```
...@@ -249,7 +249,7 @@ XGBoost 库提供了一个内置函数来绘制按其重要性排序的特征。 ...@@ -249,7 +249,7 @@ XGBoost 库提供了一个内置函数来绘制按其重要性排序的特征。
该函数称为 **plot_importance()**,可以按如下方式使用: 该函数称为 **plot_importance()**,可以按如下方式使用:
``` ```py
plot_importance(model) plot_importance(model)
pyplot.show() pyplot.show()
``` ```
...@@ -258,7 +258,7 @@ pyplot.show() ...@@ -258,7 +258,7 @@ pyplot.show()
下面提供了使用 Pima Indians Onset of Diabetes 数据集绘制特征重要性分数的完整示例。 下面提供了使用 Pima Indians Onset of Diabetes 数据集绘制特征重要性分数的完整示例。
``` ```py
# plot feature importance using built-in function # plot feature importance using built-in function
from numpy import loadtxt from numpy import loadtxt
from xgboost import XGBClassifier from xgboost import XGBClassifier
...@@ -313,7 +313,7 @@ scikit-learn 框架提供了搜索参数组合的功能。 ...@@ -313,7 +313,7 @@ scikit-learn 框架提供了搜索参数组合的功能。
例如,我们可以定义一个树的数量( **n_estimators** )和树大小( **max_depth** )的网格,通过将网格定义为: 例如,我们可以定义一个树的数量( **n_estimators** )和树大小( **max_depth** )的网格,通过将网格定义为:
``` ```py
n_estimators = [50, 100, 150, 200] n_estimators = [50, 100, 150, 200]
max_depth = [2, 4, 6, 8] max_depth = [2, 4, 6, 8]
param_grid = dict(max_depth=max_depth, n_estimators=n_estimators) param_grid = dict(max_depth=max_depth, n_estimators=n_estimators)
...@@ -321,7 +321,7 @@ param_grid = dict(max_depth=max_depth, n_estimators=n_estimators) ...@@ -321,7 +321,7 @@ param_grid = dict(max_depth=max_depth, n_estimators=n_estimators)
然后使用 10 倍交叉验证评估每个参数组合: 然后使用 10 倍交叉验证评估每个参数组合:
``` ```py
kfold = StratifiedKFold(n_splits=10, shuffle=True, random_state=7) kfold = StratifiedKFold(n_splits=10, shuffle=True, random_state=7)
grid_search = GridSearchCV(model, param_grid, scoring="neg_log_loss", n_jobs=-1, cv=kfold, verbose=1) grid_search = GridSearchCV(model, param_grid, scoring="neg_log_loss", n_jobs=-1, cv=kfold, verbose=1)
result = grid_search.fit(X, label_encoded_y) result = grid_search.fit(X, label_encoded_y)
...@@ -337,7 +337,7 @@ result = grid_search.fit(X, label_encoded_y) ...@@ -337,7 +337,7 @@ result = grid_search.fit(X, label_encoded_y)
下面是调整 Pima Indians Onset of Diabetes 数据集中 **learning_rate** 的完整示例。 下面是调整 Pima Indians Onset of Diabetes 数据集中 **learning_rate** 的完整示例。
``` ```py
# Tune learning_rate # Tune learning_rate
from numpy import loadtxt from numpy import loadtxt
from xgboost import XGBClassifier from xgboost import XGBClassifier
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册