You can download this code by clicking the button below.
This code is now available for download.
This code defines a function that loads a heart disease dataset, trains and makes predictions using XGBoost, and calculates the accuracy of the predictions.
Technology Stack : The code uses the XGBoost library, scikit-learn's load_heart_disease dataset, train_test_split for data splitting, DMatrix for model training, XGBClassifier for model creation, and accuracy_score for accuracy calculation.
Code Type : The type of code
Code Difficulty :
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 dataset
data = load_heart_disease()
X = data.data
y = 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 a DMatrix from the training data
dtrain = xgb.DMatrix(X_train, label=y_train)
# Create a XGBoost model
model = xgb.XGBClassifier(use_label_encoder=False, eval_metric='mlogloss')
# Train the model
model.fit(dtrain, evals=[(dtrain, 'train')], eval_metric='mlogloss', verbose=True)
# Predict using the trained model
predictions = model.predict(xgb.DMatrix(X_test))
# Calculate accuracy
accuracy = accuracy_score(y_test, predictions)
return accuracy