用python写一个lightGBM机器学习回归预测模型
时间: 2023-06-11 22:07:39 浏览: 128
基于机器学习LightGBM单模型的信用卡逾期预测python源码+项目说明.zip
好的,下面是一个简单的 LightGBM 回归模型的 Python 代码示例:
首先需要安装 LightGBM:
```python
!pip install lightgbm
```
然后加载数据集,这里使用的是 sklearn 自带的波士顿房价数据集:
```python
from sklearn.datasets import load_boston
boston = load_boston()
X, y = boston['data'], boston['target']
```
接下来,我们将数据集划分为训练集和测试集:
```python
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
```
然后导入 LightGBM 并训练模型:
```python
import lightgbm as lgb
train_data = lgb.Dataset(X_train, label=y_train)
params = {
'objective': 'regression',
'metric': 'l2',
'num_leaves': 31,
'learning_rate': 0.05,
'feature_fraction': 0.9
}
num_round = 100
model = lgb.train(params, train_data, num_round)
```
最后,用模型进行预测并计算均方误差:
```python
import numpy as np
from sklearn.metrics import mean_squared_error
y_pred = model.predict(X_test)
mse = mean_squared_error(y_test, y_pred)
print(f"MSE: {mse}")
```
完整代码如下:
```python
from sklearn.datasets import load_boston
from sklearn.model_selection import train_test_split
from sklearn.metrics import mean_squared_error
import lightgbm as lgb
import numpy as np
# 加载数据集
boston = load_boston()
X, y = boston['data'], boston['target']
# 划分训练集和测试集
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
# 训练模型
train_data = lgb.Dataset(X_train, label=y_train)
params = {
'objective': 'regression',
'metric': 'l2',
'num_leaves': 31,
'learning_rate': 0.05,
'feature_fraction': 0.9
}
num_round = 100
model = lgb.train(params, train_data, num_round)
# 预测并计算均方误差
y_pred = model.predict(X_test)
mse = mean_squared_error(y_test, y_pred)
print(f"MSE: {mse}")
```
阅读全文