【LGBM】LightGBM sklearn API超参数解释与使用方法(优化)

接下来我们进一步解释LGBM的sklearn API中各评估器中的超参数及使用方法。

在LGBM的sklearn API中,总共包含四个模型类(也就是四个评估器),分别是lightgbm.LGBMModel、LGBMClassifier 和 LGBMRegressor 以及LGBMRanker:

LGBMModel

LGBMModel 是 LightGBM 的基础模型类,它提供了所有 LightGBM 模型的通用接口。虽然它本身不是为特定任务设计的,但它包含了所有基本的训练和预测方法。

主要方法:
  • fit(X, y, sample_weight=None, init_score=None, eval_set=None, eval_names=None, eval_sample_weight=None, eval_class_weight=None, eval_init_score=None, eval_metric=None, early_stopping_rounds=None, verbose=True, feature_name='auto', categorical_feature='auto', callbacks=None, init_model=None)
  • predict(X, raw_score=False, start_iteration=0, num_iteration=None, pred_leaf=False, pred_contrib=False, **kwargs)
  • feature_importances_:返回特征的重要性评分。

LGBMClassifier

LGBMClassifier 是用于分类任务的模型类,适用于二分类和多分类问题。

主要超参数:
  • boosting_type='gbdt':提升类型,可选值有 'gbdt' (默认), 'dart', 'goss', 'rf'。
  • num_leaves=31:每棵树的最大叶子数。
  • max_depth=-1:树的最大深度,负值表示不限制。
  • learning_rate=0.1:学习率,控制每次迭代的学习步长。
  • n_estimators=100:提升树的数量。
  • subsample_for_bin=200000:构造直方图时使用的样本数量。
  • min_split_gain=0.0:分裂节点所需的最小增益。
  • min_child_weight=0.001:叶子节点的最小权重。
  • min_child_samples=20:叶子节点的最小样本数。
  • subsample=1.0:每棵树训练时使用的样本比例。
  • colsample_bytree=1.0:每棵树训练时使用的特征比例。
  • reg_alpha=0.0:L1 正则化系数。
  • reg_lambda=0.0:L2 正则化系数。
  • random_state=None:随机种子,用于复现结果。
  • n_jobs=-1:并行任务数,-1 表示使用所有可用的 CPU 核心。
  • silent=True:是否静默模式,不显示训练过程中的信息。
  • importance_type='split':特征重要性的计算方式,可选值有 'split' 和 'gain'。
示例代码:
python 复制代码
from lightgbm import LGBMClassifier
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split

# 加载数据集
data = load_iris()
X, y = data.data, data.target

# 划分训练集和测试集
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)

# 创建 LGBMClassifier 模型
model = LGBMClassifier(
    n_estimators=100,
    learning_rate=0.1,
    max_depth=5,
    num_leaves=31,
    subsample=0.8,
    colsample_bytree=0.8,
    reg_alpha=0.1,
    reg_lambda=0.1,
    random_state=42
)

# 训练模型
model.fit(X_train, y_train)

# 预测
predictions = model.predict(X_test)

# 获取特征重要性
feature_importances = model.feature_importances_
print("Feature importances:", feature_importances)

LGBMRegressor

LGBMRegressor 是用于回归任务的模型类,适用于预测连续值目标变量的问题。

主要超参数:
  • boosting_type='gbdt':提升类型,可选值有 'gbdt' (默认), 'dart', 'goss', 'rf'。
  • num_leaves=31:每棵树的最大叶子数。
  • max_depth=-1:树的最大深度,负值表示不限制。
  • learning_rate=0.1:学习率,控制每次迭代的学习步长。
  • n_estimators=100:提升树的数量。
  • subsample_for_bin=200000:构造直方图时使用的样本数量。
  • min_split_gain=0.0:分裂节点所需的最小增益。
  • min_child_weight=0.001:叶子节点的最小权重。
  • min_child_samples=20:叶子节点的最小样本数。
  • subsample=1.0:每棵树训练时使用的样本比例。
  • colsample_bytree=1.0:每棵树训练时使用的特征比例。
  • reg_alpha=0.0:L1 正则化系数。
  • reg_lambda=0.0:L2 正则化系数。
  • random_state=None:随机种子,用于复现结果。
  • n_jobs=-1:并行任务数,-1 表示使用所有可用的 CPU 核心。
  • silent=True:是否静默模式,不显示训练过程中的信息。
  • importance_type='split':特征重要性的计算方式,可选值有 'split' 和 'gain'。
示例代码:
python 复制代码
from lightgbm import LGBMRegressor
from sklearn.datasets import load_boston
from sklearn.model_selection import train_test_split

# 加载数据集
data = load_boston()
X, y = data.data, data.target

# 划分训练集和测试集
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)

# 创建 LGBMRegressor 模型
model = LGBMRegressor(
    n_estimators=100,
    learning_rate=0.1,
    max_depth=5,
    num_leaves=31,
    subsample=0.8,
    colsample_bytree=0.8,
    reg_alpha=0.1,
    reg_lambda=0.1,
    random_state=42
)

# 训练模型
model.fit(X_train, y_train)

# 预测
predictions = model.predict(X_test)

# 获取特征重要性
feature_importances = model.feature_importances_
print("Feature importances:", feature_importances)

LGBMRanker

LGBMRanker 是用于排序任务的模型类,适用于需要对一组项目进行排序的问题,常见于信息检索和推荐系统中。

主要超参数:
  • boosting_type='gbdt':提升类型,可选值有 'gbdt' (默认), 'dart', 'goss', 'rf'。
  • num_leaves=31:每棵树的最大叶子数。
  • max_depth=-1:树的最大深度,负值表示不限制。
  • learning_rate=0.1:学习率,控制每次迭代的学习步长。
  • n_estimators=100:提升树的数量。
  • subsample_for_bin=200000:构造直方图时使用的样本数量。
  • min_split_gain=0.0:分裂节点所需的最小增益。
  • min_child_weight=0.001:叶子节点的最小权重。
  • min_child_samples=20:叶子节点的最小样本数。
  • subsample=1.0:每棵树训练时使用的样本比例。
  • colsample_bytree=1.0:每棵树训练时使用的特征比例。
  • reg_alpha=0.0:L1 正则化系数。
  • reg_lambda=0.0:L2 正则化系数。
  • random_state=None:随机种子,用于复现结果。
  • n_jobs=-1:并行任务数,-1 表示使用所有可用的 CPU 核心。
  • silent=True:是否静默模式,不显示训练过程中的信息。
  • importance_type='split':特征重要性的计算方式,可选值有 'split' 和 'gain'。
特殊参数:
  • group:每个查询组的大小,必须在 fit 方法中提供。
  • eval_at=[1, 2, 3]:评估排序性能时使用的排名位置。
示例代码:
python 复制代码
from lightgbm import LGBMRanker
import numpy as np

# 生成示例数据
X = np.random.rand(100, 10)  # 100 个样本,每个样本有 10 个特征
y = np.random.randint(0, 5, 100)  # 目标变量,假设是 0 到 4 的评分
group = [10] * 10  # 每个查询组有 10 个样本

# 创建 LGBMRanker 模型
model = LGBMRanker(
    n_estimators=100,
    learning_rate=0.1,
    max_depth=5,
    num_leaves=31,
    subsample=0.8,
    colsample_bytree=0.8,
    reg_alpha=0.1,
    reg_lambda=0.1,
    random_state=42
)

# 训练模型
model.fit(X, y, group=group)

# 预测
predictions = model.predict(X)

# 获取特征重要性
feature_importances = model.feature_importances_
print("Feature importances:", feature_importances)

总结

  • LGBMModel:基础模型类,通常不直接使用。
  • LGBMClassifier:用于分类任务,支持二分类和多分类。
  • LGBMRegressor:用于回归任务,预测连续值目标变量。
  • LGBMRanker:用于排序任务,适用于信息检索和推荐系统。

LGBMClassifier调参

1. 数据集特性分析

在开始调参之前,先对数据集进行一些基本的分析,了解数据的特性和潜在的问题:

  • 数据规模 :数据集的大小会影响模型的选择和参数设置。大规模数据集可能需要更多的树(更大的 n_estimators)和更深的树(更大的 max_depth)。
  • 特征数量 :特征数量较多时,可以考虑减少每棵树使用的特征比例(减小 colsample_bytree)。
  • 类别不平衡 :对于分类问题,如果类别不平衡,可以调整 is_unbalancescale_pos_weight 参数。
  • 噪声和异常值 :数据中存在大量噪声或异常值时,可以增加正则化参数(如 reg_alphareg_lambda)来减少过拟合。

2. 基本参数设置

通用参数:
  • n_estimators:提升树的数量。初始值可以设为 100,然后根据模型性能逐步增加或减少。
  • learning_rate:学习率。初始值可以设为 0.1,如果模型过拟合,可以尝试降低学习率。
  • max_depth:树的最大深度。初始值可以设为 5 或 6,然后根据模型性能进行调整。
  • num_leaves:每棵树的最大叶子数。初始值可以设为 31,然后根据模型性能进行调整。
  • min_child_samples:叶子节点的最小样本数。初始值可以设为 20,如果数据集中有少量样本,可以适当减少这个值。
正则化参数:
  • reg_alpha:L1 正则化系数。初始值可以设为 0,如果模型过拟合,可以尝试增加这个值。
  • reg_lambda:L2 正则化系数。初始值可以设为 0,如果模型过拟合,可以尝试增加这个值。
子采样参数:
  • subsample:每棵树训练时使用的样本比例。初始值可以设为 1.0,如果数据集较大,可以尝试减小这个值(例如 0.8)。
  • colsample_bytree:每棵树训练时使用的特征比例。初始值可以设为 1.0,如果特征数量较多,可以尝试减小这个值(例如 0.8)。
特定任务:
  • 类别不平衡 :如果数据集中类别不平衡,可以使用 class_weight='balanced' 或者手动设置 scale_pos_weight
  • 多分类 :对于多分类任务,可以尝试增加 n_estimatorsmax_depth,因为多分类任务通常需要更复杂的模型。

3. 调参策略

交叉验证

使用交叉验证来评估模型的性能,避免过拟合。scikit-learn 提供了 GridSearchCVRandomizedSearchCV,可以帮助自动寻找最优参数组合。

通过网格搜索(Grid Search)尝试所有可能的参数组合,找到最优的参数设置。

python 复制代码
from sklearn.model_selection import GridSearchCV
from lightgbm import LGBMClassifier

# 定义参数网格
param_grid = {
    'n_estimators': [100, 200, 300],
    'learning_rate': [0.01, 0.1, 0.2],
    'max_depth': [3, 5, 7],
    'num_leaves': [15, 31, 63],
    'min_child_samples': [10, 20, 30],
    'subsample': [0.8, 1.0],
    'colsample_bytree': [0.8, 1.0],
    'reg_alpha': [0, 0.1, 0.5],
    'reg_lambda': [0, 0.1, 0.5]
}

# 创建 LGBMClassifier 模型
model = LGBMClassifier(random_state=42)

# 创建 GridSearchCV 对象
grid_search = GridSearchCV(model, param_grid, cv=5, scoring='accuracy', n_jobs=-1)

# 训练模型
grid_search.fit(X_train, y_train)

# 输出最优参数
print("Best parameters found: ", grid_search.best_params_)

随机搜索(Randomized Search)通过随机采样参数空间,寻找最优参数组合。相比于网格搜索,随机搜索在高维参数空间中更加高效。

python 复制代码
from sklearn.model_selection import RandomizedSearchCV
from lightgbm import LGBMClassifier
from scipy.stats import randint, uniform

# 定义参数分布
param_dist = {
    'n_estimators': randint(100, 500),
    'learning_rate': uniform(0.01, 0.2),
    'max_depth': randint(3, 10),
    'num_leaves': randint(15, 63),
    'min_child_samples': randint(10, 30),
    'subsample': uniform(0.7, 0.3),
    'colsample_bytree': uniform(0.7, 0.3),
    'reg_alpha': uniform(0, 0.5),
    'reg_lambda': uniform(0, 0.5)
}

# 创建 LGBMClassifier 模型
model = LGBMClassifier(random_state=42)

# 创建 RandomizedSearchCV 对象
random_search = RandomizedSearchCV(model, param_distributions=param_dist, n_iter=100, cv=5, scoring='accuracy', n_jobs=-1, random_state=42)

# 训练模型
random_search.fit(X_train, y_train)

# 输出最优参数
print("Best parameters found: ", random_search.best_params_)
相关推荐
IT_陈寒12 分钟前
React 18实战:7个被低估的Hooks技巧让你的开发效率提升50%
前端·人工智能·后端
数据智能老司机1 小时前
精通 Python 设计模式——分布式系统模式
python·设计模式·架构
逛逛GitHub1 小时前
飞书多维表“独立”了!功能强大的超出想象。
人工智能·github·产品
机器之心1 小时前
刚刚,DeepSeek-R1论文登上Nature封面,通讯作者梁文锋
人工智能·openai
数据智能老司机2 小时前
精通 Python 设计模式——并发与异步模式
python·设计模式·编程语言
数据智能老司机2 小时前
精通 Python 设计模式——测试模式
python·设计模式·架构
数据智能老司机2 小时前
精通 Python 设计模式——性能模式
python·设计模式·架构
c8i2 小时前
drf初步梳理
python·django
每日AI新事件2 小时前
python的异步函数
python
这里有鱼汤4 小时前
miniQMT下载历史行情数据太慢怎么办?一招提速10倍!
前端·python