LightGBM Binary Classification Model Training and Prediction

  • Share this:

Code introduction


This function uses the LightGBM library to train a binary classification model, including data splitting, model training, and prediction.


Technology Stack : The package and technology stack used in the code include LightGBM, scikit-learn, and NumPy.

Code Type : The type of code

Code Difficulty : Advanced


                
                    
import lightgbm as lgb
from sklearn.model_selection import train_test_split
import numpy as np

def random_lightgbm_classification(X, y):
    # Splitting the data into training and testing sets
    X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
    
    # Creating a LightGBM dataset
    train_data = lgb.Dataset(X_train, label=y_train)
    
    # Defining the parameters for the LightGBM model
    params = {
        'objective': 'binary',
        'metric': 'binary_logloss',
        'boosting_type': 'gbdt',
        'learning_rate': 0.1,
        'num_leaves': 31
    }
    
    # Training the LightGBM model
    gbm = lgb.train(params, train_data)
    
    # Making predictions on the test set
    y_pred = gbm.predict(X_test)
    
    # Returning the predictions
    return y_pred