Predicting Heart Disease with XGBoost

  • Share this:

Code introduction


This function uses the XGBoost library to predict heart disease. It first loads the dataset, then splits it into training and testing sets. Next, it creates an XGBoost classifier and trains it on the training set. Finally, it uses the model to make predictions on the test set and calculates the accuracy.


Technology Stack : XGBoost, scikit-learn

Code Type : Machine learning prediction function

Code Difficulty : Intermediate


                
                    
def predict_heart_disease(features):
    import xgboost as xgb
    from sklearn.datasets import load_heart_disease
    from sklearn.model_selection import train_test_split
    from sklearn.metrics import accuracy_score

    # Load the heart disease dataset
    data = load_heart_disease()
    X, y = data.data, data.target

    # Split the dataset 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)

    # Create an XGBoost classifier
    model = xgb.XGBClassifier(use_label_encoder=False, eval_metric='mlogloss')

    # Train the model
    model.fit(X_train, y_train)

    # Predict on the test set
    predictions = model.predict(X_test)

    # Calculate the accuracy
    accuracy = accuracy_score(y_test, predictions)

    return accuracy