简体   繁体   English

LightGBMRegressor 自定义评估损失函数作为单个输出的列表错误返回

[英]LightGBMRegressor Custom eval loss fuction return as list error for single output

I want to use custom eval function in my lightGBM model.我想在我的 lightGBM 模型中使用自定义 eval 函数。 My code is as follow:我的代码如下:

X = df.loc[:, "VALUE_1":"TVALUE_33"]
y_true = df.loc[:, "VALUE_34"]
   
X_train, X_test, y_train, y_test = train_test_split(X, y_true, test_size= 0.30, random_state = 333)

def mle_loss(y_true, y_pred):
    y_true = tf.cast(y_true, dtype= tf.float32)
    
    # get params for probability distributions
    mu = y_pred.mean()
    sigma = y_pred.std()
    mu = tf.cast(mu, tf.float32)
    sigma = tf.cast(sigma, tf.float32)
        
    total_dist = tfp.distributions.Normal(loc=mu, scale=sigma)
    total_log_prob = total_dist.log_prob(y_true)[0]
        
    return ["mle_loss", total_log_prob.numpy(), True]

hyper_params_11 = {
    'task': 'train',
    'boosting_type': 'gbdt',
    'objective': 'regression',
    'metric':  "custom",
    'subsample_freq': 250, 
    'subsample': 0.8, 
    'num_leaves': 16,
    'min_split_gain': 50,
    'min_child_samples': 25,
    'max_depth': 5, 
    'max_bin': 1024, 
    'learning_rate': 0.001, 
    'colsample_bytree': 0.5,
    "num_iterations": 10000,
    "lambda_l1" : 1,
    "lambda_l2" : 1
    }

gbm_model_1 = lgb.LGBMRegressor(**hyper_params_1)
gbm_model_1.fit(X_train, y_train,
        eval_set=[(X_test, y_test), (X_train,y_train)],
        eval_metric = mle_loss,
        early_stopping_rounds=100
               )

Unfortunatelu running the piece of code I got error ValueError: too many values to unpack (expected 3).不幸的是,运行这段代码时出现错误 ValueError: too many values to unpack (expected 3)。 WHen I run it without eval_set and early_stopping_rounds, it works fine.当我在没有 eval_set 和 early_stopping_rounds 的情况下运行它时,它工作正常。 Can you please help me?你能帮我么?

Thanks谢谢

Just change your return values as tuples只需将您的返回值更改为元组

def mle_loss(y_true, y_pred):
    ....
        
    return ("mle_loss", total_log_prob.numpy(), True)

Returning as list throws an error, for example,以列表形式返回会引发错误,例如,

feval_ret = ['mle_loss', -1.4523773, True]

if isinstance(feval_ret, list):
    for eval_name, val, is_higher_better in feval_ret:
        pass

will throw the error you mentioned会抛出你提到的错误

ValueError: too many values to unpack (expected 3)

According to docs this happens because it is expecting a tuple for a single element or a list of tuples for multiples elements根据文档,发生这种情况是因为它期望单个元素的元组或多个元素的元组列表

returns (eval_name, eval_result, is_higher_better) or list of (eval_name, eval_result, is_higher_better)返回 (eval_name, eval_result, is_higher_better) 或 (eval_name, eval_result, is_higher_better) 的列表

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM