lightgbm算法python代码
时间: 2023-09-13 20:11:29 浏览: 136
以下是一个简单的 LightGBM 算法的 Python 代码示例:
```
import lightgbm as lgb
import numpy as np
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.metrics import mean_squared_error
# 加载数据集
data = pd.read_csv('data.csv')
X = data.drop('y', axis=1)
y = data['y']
# 将数据集划分成训练集和测试集
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
# 创建 LightGBM 数据集对象
lgb_train = lgb.Dataset(X_train, y_train)
lgb_test = lgb.Dataset(X_test, y_test, reference=lgb_train)
# 设置 LightGBM 参数
params = {
'boosting_type': 'gbdt',
'objective': 'regression',
'metric': {'rmse'},
'num_leaves': 31,
'learning_rate': 0.05,
'feature_fraction': 0.9,
'bagging_fraction': 0.8,
'bagging_freq': 5,
'verbose': 0
}
# 训练 LightGBM 模型
gbm = lgb.train(params,
lgb_train,
num_boost_round=1000,
valid_sets=lgb_test,
early_stopping_rounds=50)
# 在测试集上评估模型
y_pred = gbm.predict(X_test, num_iteration=gbm.best_iteration)
mse = mean_squared_error(y_test, y_pred)
rmse = np.sqrt(mse)
print('RMSE:', rmse)
```
在这个示例中,我们首先加载数据集并将其划分为训练集和测试集。然后,我们创建了 LightGBM 的数据集对象,并设置了模型参数。接下来,我们使用训练集训练了 LightGBM 模型,并在测试集上评估了模型的表现。最后,我们打印出了模型在测试集上的 RMSE 值。
阅读全文