lightgbm分类 python代码
时间: 2024-07-17 10:01:08 浏览: 144
LightGBM是一个高效的梯度提升库,特别适合大规模数据集。以下是使用Python进行分类任务的一个简单示例:
```python
# 首先,安装必要的库
!pip install lightgbm pandas sklearn
import lightgbm as lgb
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score
# 加载鸢尾花数据集
iris = load_iris()
X = iris.data
y = iris.target
# 划分训练集和测试集
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
# 定义特征列和标签列
features = ['feature_column_1', 'feature_column_2', ...] # 替换为实际的特征列名
dtrain = lgb.Dataset(X_train[features], label=y_train)
dtest = lgb.Dataset(X_test[features], label=y_test)
# 设置模型参数
params = {
'boosting_type': 'gbdt', # 使用梯度提升算法
'objective': 'multiclass', # 多类别分类任务
'num_class': len(set(y)), # 根据实际类别数设置
'metric': 'multi_logloss', # 用于评估的指标
}
# 训练模型
model = lgb.train(params, dtrain, num_boost_round=100, valid_sets=[dtest])
# 预测
y_pred = model.predict(X_test[features])
# 评估准确率
accuracy = accuracy_score(y_test, y_pred.argmax(axis=1))
print("Accuracy:", accuracy)
#
阅读全文