Kew*_*ewl 7 python scikit-learn xgboost
在 Python 中,XGBoost 允许您使用其 Booster 类或使用其 sklearn API ( http://xgboost.readthedocs.io/en/latest/python/python_api.html ) 进行训练/预测。我正在使用 sklearn API,并且想要使用pred_contribsXGBoost 的功能。我希望这能起作用,但事实并非如此:
model = xgb.XGBClassifier().fit(X_train, y_train)
pred = model.predict_proba(X_test, pred_contribs=True)
Run Code Online (Sandbox Code Playgroud)
看起来pred_contribs只是Booster类预测函数的一个参数。如何通过 sklearn API 使用此参数?或者是否有一个简单的解决方法可以在使用 sklearn API 进行训练后获取预测贡献者?
Viv*_*mar 10
您可以使用get_booster()XGBClassifier 中的方法,在 XGBClassifier 安装了训练数据后,该方法将返回 Booster 对象。
之后,您可以简单地使用 调用predict()Booster 对象pred_contribs = True。
示例代码:
from xgboost import XGBClassifier, DMatrix
from sklearn.datasets import load_iris
iris_data = load_iris()
# Taking only first 100 samples to make this a binary problem,
# else it will be multi-class and shape of pred_contribs will change
X, y = iris_data.data[:100], iris_data.target[:100]
# This data has 4 features
print(X.shape)
Output: (100, 4)
clf = XGBClassifier()
clf.fit(X, y)
# This is what you need
booster = clf.get_booster()
# Using only a single sample for predict, you can use multiple
test_X = [X[0]]
# Wrapping the test X into a DMatrix, need by Booster
predictions = booster.predict(DMatrix(test_X), pred_contribs=True)
print(predictions.shape)
# Output has 5 columns, 1 for each feature, and last for bias
Output: (1, 5)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3673 次 |
| 最近记录: |