我已经使用 XGB 分类器训练了数据集,但在本地出现此错误。它在 Colab 上有效,而且我的朋友对相同的代码也没有任何问题。我不知道这个错误意味着什么...
Invalid classes inferred from unique values of y. Expected: [0 1 2 3 4 5], got [1 2 3 4 5 6]
这是我的代码,但我想这不是原因。
start_time = time.time()
xgb = XGBClassifier(n_estimators = 400, learning_rate = 0.1, max_depth = 3)
xgb.fit(X_train.values, y_train)
print('Fit time : ', time.time() - start_time)
Run Code Online (Sandbox Code Playgroud) python classification machine-learning xgboost xgbclassifier
我正在处理 3 个类别 [0,1,2] 的分类问题,类别分布不平衡,如下所示。
我想将XGBClassifier(在 Python 中)应用于此分类问题,但该模型不会响应class_weight调整并偏向多数类 0,并且忽略少数类 1,2。除了其他哪些超参数class_weight可以帮助我?
我尝试过1)使用sklearn计算类别权重compute_class_weight;2)根据类别的相对频率设置权重;3) 并手动调整具有极值的类以查看是否发生任何变化,例如{0:0.5,1:100,2:200}. 但无论如何,它对分类器考虑少数类没有帮助。
观察结果:
我可以在二元情况下处理问题:如果我通过识别类 [1,2] 使问题成为二元分类,那么我可以通过调整使分类器正常工作scale_pos_weight(即使在这种情况下class_weight单独没有帮助)。但是scale_pos_weight,据我所知,适用于二元分类。对于多分类问题,是否有该参数的类似物?
使用RandomForestClassifier代替,我可以通过设置和调整XGBClassifier来解决问题。但是,由于某种原因,这种方法不适用于 XGBClassifier。class_weight='balanced_subsample'max_leaf_nodes
备注:我了解平衡技术,例如过采样/欠采样或 SMOTE。但我想尽可能避免它们,并且如果可能的话,更喜欢使用模型超参数调整的解决方案。我上面的观察表明,这适用于二进制情况。
python xgboost multiclass-classification xgbclassifier imbalanced-data
我现在对XGBoost. 这是我感到困惑的方式:
objective,这是需要最小化的损失函数;eval_metric:用于表示学习结果的度量。这两者完全无关(如果我们不考虑仅用于分类logloss,mlogloss可以用作eval_metric)。这样对吗?如果是,那么对于分类问题,您如何将其rmse用作性能指标?objective为例,reg:logistic和binary:logistic。对于 0/1 分类,通常应将二元逻辑损失或交叉熵视为损失函数,对吗?那么这两个选项中的哪一个是针对这个损失函数的,另一个的值是多少?说,如果binary:logistic代表交叉熵损失函数,那么什么reg:logistic呢?multi:softmax和multi:softprob?他们是否使用相同的损失函数,只是输出格式不同?如果是的话,那应该是相同的reg:logistic,并binary:logistic为好,对不对?第二个问题的补充
比如说,0/1 分类问题的损失函数应该是
L = sum(y_i*log(P_i)+(1-y_i)*log(P_i))。所以如果我需要在binary:logistic这里选择,或者reg:logistic让xgboost分类器使用L损失函数。如果是binary:logistic,那么损失函数reg:logistic使用什么?
我有一个像这样的数据集:
print(X_test.dtypes)
metric1 int64
rank float64
device_type int8
NA_estimate float64
Run Code Online (Sandbox Code Playgroud)
当我尝试对此数据集进行预测时,出现以下错误:
y_test_pred_xgb = clf_xgb.predict(xgb.DMatrix(X_test))
TypeError: Not supported type for data.<class 'xgboost.core.DMatrix'>
Run Code Online (Sandbox Code Playgroud)
我进行了一些搜索,但只找到了object引起问题的变量数据类型的讨论。我的数据是否还有其他问题或者问题是其他原因?我查看了各种博客和 Kaggle 代码,但没有运气。
从树解释器返回的 SHAP 值为.shap_values(some_data)XGB 提供了与随机森林不同的维度/结果。我尝试过研究它,但似乎找不到原因或方式,也找不到斯伦德伯格(SHAP dude)教程中的解释。所以:
下面是一些示例代码!
import xgboost.sklearn as xgb
import pandas as pd
from sklearn.ensemble import RandomForestClassifier
from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import train_test_split
import shap
bc = load_breast_cancer()
cancer_df = pd.DataFrame(bc['data'], columns=bc['feature_names'])
cancer_df['target'] = bc['target']
cancer_df = cancer_df.iloc[0:50, :]
target = cancer_df['target']
cancer_df.drop(['target'], inplace=True, axis=1)
X_train, X_test, y_train, y_test = train_test_split(cancer_df, target, test_size=0.33, random_state = 42)
xg = xgb.XGBClassifier()
xg.fit(X_train, y_train)
rf = RandomForestClassifier()
rf.fit(X_train, y_train)
xg_pred = xg.predict(X_test)
rf_pred = …Run Code Online (Sandbox Code Playgroud) 语境
我正在尝试对 XGBoost 二元分类器使用自定义损失函数。
这个想法是在 XGBoost 中实现 soft-Fbeta 损失,我在这里读到了这一点。简单地说:不使用标准的对数损失,而是使用直接优化 Fbeta 分数的损失函数。
警告
当然,Fbeta 本身是不可微分的,因此不能直接开箱即用。然而,我们的想法是使用概率(因此,在阈值化之前)来创建某种连续的 TP、FP 和 FN。在参考的 Medium 文章中查找更多详细信息。
试图
我的尝试如下(受到几个不同人的启发)。
import numpy as np
import xgboost as xgb
def gradient(y: np.array, p: np.array, beta: float):
"""Compute the gradient of the loss function. y is the true label, p
the probability predicted by the model """
# Define the denominator
D = p.sum() + beta**2 * y.sum()
# Compute the gradient
grad = (1 + beta**2) * y …Run Code Online (Sandbox Code Playgroud) 我有以下代码
eval_set = [(X_train, y_train), (X_test, y_test)]
eval_metric = ["auc","error"]
Run Code Online (Sandbox Code Playgroud)
在下面的部分中,我正在训练XGBClassifier模型
model = XGBClassifier()
%time model.fit(X_train, y_train, eval_set=eval_set, eval_metric=eval_metric, verbose=True)
Run Code Online (Sandbox Code Playgroud)
这给了我以下格式的指标
[0] validation_0-auc:0.840532 validation_0-error:0.187758 validation_1-auc:0.84765 validation_1-error:0.17672
[1] validation_0-auc:0.840536 validation_0-error:0.187758 validation_1-auc:0.847665 validation_1-error:0.17672
....
[99] validation_0-auc:0.917587 validation_0-error:0.13846 validation_1-auc:0.918747 validation_1-error:0.137714
Wall time: 5 s
Run Code Online (Sandbox Code Playgroud)
我从中制作了一个 DataFrame 并在时间 (0-99) 和其他指标之间绘制。有没有其他方法可以直接绘制输出?
importerror python-3.x xgboost jupyter-notebook xgbclassifier
我尝试根据文档设置 XGBoost sklearn APIXGBClassifier以使用自定义目标函数 ( brier):
.. note:: Custom objective function
A custom objective function can be provided for the ``objective``
parameter. In this case, it should have the signature
``objective(y_true, y_pred) -> grad, hess``:
y_true: array_like of shape [n_samples]
The target values
y_pred: array_like of shape [n_samples]
The predicted values
grad: array_like of shape [n_samples]
The value of the gradient for each sample point.
hess: array_like of shape [n_samples]
The value of the second derivative for …Run Code Online (Sandbox Code Playgroud) XGBclassifier 中 xgboost.plot_importance() 和 model.feature_importances_ 有什么区别。
所以我在这里做了一些虚拟数据
import numpy as np
import pandas as pd
# generate some random data for demonstration purpose, use your original dataset here
X = np.random.rand(1000,100) # 1000 x 100 data
y = np.random.rand(1000).round() # 0, 1 labels
a = pd.DataFrame(X)
a.columns = ['param'+str(i+1) for i in range(len(a.columns))]
b = pd.DataFrame(y)
import xgboost as xgb
from xgboost import XGBClassifier
from xgboost import plot_importance
from matplotlib import pyplot as plt
from sklearn.model_selection import train_test_split
model = …Run Code Online (Sandbox Code Playgroud) python feature-selection dimensionality-reduction xgboost xgbclassifier
我有一个关于 xgboost 和多类的问题。我没有使用 sklearn 包装器,因为我总是在某些参数上遇到困难。我想知道是否可以获得概率向量加上 softmax 输出。以下是我的代码:
param = {}
param['objective'] = 'multi:softmax'
param['booster'] = 'gbtree'
param['eta'] = 0.1
param['max_depth'] = 30
param['silent'] = 1
param['nthread'] = 4
param['num_round'] = 40
param['num_class'] = len(np.unique(label)) + 1
model = xgb.train(param, dtrain)
# predict
pred = model.predict(dtest)
Run Code Online (Sandbox Code Playgroud)
我希望能够调用类似的函数predict_proba,但我不知道是否可能。很多答案(例如:https: //datascience.stackexchange.com/questions/14527/xgboost-predict-probabilities)建议转向sklearn包装器,但是,我想继续使用正常的训练方法。
xgbclassifier ×11
python ×10
xgboost ×10
importerror ×1
matplotlib ×1
pandas ×1
python-3.x ×1
scikit-learn ×1
shap ×1
typeerror ×1