基于LGBMClassifier写一个lightgbm二分类模型
时间: 2024-02-16 07:04:20 浏览: 76
LGBMClassifier 是一个用于分类问题的 LightGBM 模型,可以直接用于二分类问题。以下是一个示例代码:
```python
import lightgbm as lgb
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score
# 准备数据集
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
# 定义模型参数
params = {
'boosting_type': 'gbdt',
'objective': 'binary',
'metric': 'binary_logloss',
'num_leaves': 31,
'learning_rate': 0.05,
'feature_fraction': 0.9,
'bagging_fraction': 0.8,
'bagging_freq': 5,
'verbose': 0
}
# 训练模型
model = lgb.LGBMClassifier(**params)
model.fit(X_train, y_train, eval_set=[(X_test, y_test)], early_stopping_rounds=200, verbose=False)
# 模型评估
y_pred = model.predict(X_test)
accuracy = accuracy_score(y_test, y_pred)
print('Accuracy:', accuracy)
# 模型应用
new_data = pd.read_csv('new_data.csv')
new_X = new_data.drop('target', axis=1)
new_y_pred = model.predict(new_X)
```
其中,params 和 model 的定义与示例一致。模型的训练和评估也与示例一致,但是预测值不需要进行处理,直接将模型预测的值与真实值进行比较即可。
阅读全文