lightgbm的MSE代码
时间: 2023-10-11 11:13:22 浏览: 213
以下是使用LightGBM进行MSE回归的代码示例:
```python
import lightgbm as lgb
from sklearn.metrics import mean_squared_error
from sklearn.datasets import load_boston
from sklearn.model_selection import train_test_split
# 加载数据集
boston = load_boston()
X_train, X_test, y_train, y_test = train_test_split(boston.data, boston.target, test_size=0.2, random_state=42)
# 构建LightGBM模型
params = {
'boosting_type': 'gbdt',
'objective': 'regression',
'metric': 'mse',
'num_leaves': 31,
'learning_rate': 0.05,
'feature_fraction': 0.9
}
train_data = lgb.Dataset(X_train, label=y_train)
test_data = lgb.Dataset(X_test, label=y_test)
gbm = lgb.train(params, train_data, num_boost_round=100, valid_sets=test_data, early_stopping_rounds=5)
# 预测测试集结果
y_pred = gbm.predict(X_test, num_iteration=gbm.best_iteration)
# 计算MSE
mse = mean_squared_error(y_test, y_pred)
print("MSE:", mse)
```
在上面的代码中,我们使用波士顿房价数据集进行回归任务。首先将数据集划分为训练集和测试集,然后定义LightGBM模型的参数,使用训练集训练模型,并使用测试集进行验证和调整。最后,我们使用训练好的模型进行预测,并计算预测结果与真实结果之间的MSE。
阅读全文