在多变量xgboost模型中,可以将自定义eval函数与默认目标函数一起使用吗?

时间:2019-07-07 20:38:52

标签: python machine-learning scikit-learn xgboost

我正在多变量xgboost模型中使用自定义评估函数。我不确定feval是否正确使用

我尝试了feval=customeval1,当我使用其他自定义评估函数(customeval2肯定是错误的)时,我得到了相同的答案。因此,不确定代码中feval的用法是否正确。

这是我使用的代码:

# first custom eval function
def customeval1(preds, y_train):
    error=mahalanobis(x=preds,data=y_train) #y_train has two columns for two outcomes
    return 'customeval', error

# evaluation metric to model correlation between outcomes
def mahalanobis(x=None, data=None, cov=None):
    x_minus_mu = x - np.array(np.mean(data)) 
    if not cov:
        cov = np.cov(data.values.T)
    inv_covmat = sp.linalg.inv(cov)
    left_term = np.dot(x_minus_mu, inv_covmat)
    mahal = np.einsum('ij,ji->i', left_term,x_minus_mu.T)  #finding diagonal
    return np.mean(mahal)

multixg = MultiOutputRegressor(XGBRegressor(objective='reg:squarederror',booster='gbtree',
colsample_bytree = 1, nthread=8,learning_rate = 0.5,subsample=1,
disable_default_eval_metric=1, max_depth = 4, gamma=0, reg_lambda=0,
n_estimators=10, verbosity=2,feval=customeval1)) 

multixg.fit(X_train, y_train)

y_pred=multixg.predict(X_test1)
rmse1 = np.sqrt(mean_squared_error(y_test1.iloc[:,0], y_pred[:,0]))
rmse2 = np.sqrt(mean_squared_error(y_test1.iloc[:,1], y_pred[:,1]))
print(rmse1)
print(rmse2)

如果将自定义eval函数更改为以下代码,则使用上述代码获得的rmse1rmse2的答案仍然相同:

# second custom eval function
def customeval2(preds, y_train):
    error=mahalanobis(x=preds,data=y_train) #y_train has two columns for two outcomes
    return 'customeval', 1

customeval2中,我返回一个常数1(这是错误的),以检查运行multixg.fit(X_train, y_train)时代码是否抛出错误。但是我没有收到错误,最终得到的rmse1rmse2的答案与以前一样。

注意:我使用的是默认目标reg:squarederror,而不是使用默认的rmse作为评估指标,而是使用平均马哈拉诺比斯距离作为评估指标因为它可以模拟结果之间的相关性。

我在多变量xgboost模型中正确使用feval吗?

0 个答案:

没有答案