XGBoost Regression Model for Boston Housing Data Prediction

  • Share this:

Code introduction


This function uses the XGBoost library to train a regression model and predict the results of the test dataset. It first loads the Boston housing dataset, then splits it into training and testing sets. Next, it creates an XGBoost regressor and uses the training set to train this model. Finally, it uses the trained model to predict the results of the test set.


Technology Stack : XGBoost library, scikit-learn, numpy, Boston housing dataset

Code Type : The type of code

Code Difficulty :


                
                    
def random_xgboost_prediction(input_data, num_iterations=100):
    import xgboost as xgb
    from sklearn.model_selection import train_test_split
    from sklearn.datasets import load_boston
    import numpy as np

    # Load the Boston housing dataset
    boston = load_boston()
    X, y = boston.data, boston.target

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

    # Create an XGBoost regressor object
    reg = xgb.XGBRegressor(objective='reg:squarederror', colsample_bytree=0.3, learning_rate=0.1,
                           max_depth=5, alpha=10, n_estimators=num_iterations)

    # Fit the model
    reg.fit(X_train, y_train)

    # Predict the test set results
    predictions = reg.predict(X_test)

    return predictions