{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"name":"python","version":"3.10.14","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"},"kaggle":{"accelerator":"none","dataSources":[{"sourceId":85542,"databundleVersionId":9725219,"sourceType":"competition"}],"dockerImageVersionId":30786,"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":false}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"markdown","source":"# Basic XGBoost Solution for Tabular Only\n\n**Generated from this prompt:**\n\n```\nCreate a Kaggle notebook that uses XGBoost to perform a regression prediction on these files:\n\n/kaggle/input/applications-of-gen-ai-wustl-fall-2024/df-test_200x11.csv\n/kaggle/input/applications-of-gen-ai-wustl-fall-2024/df-train_1000x12.csv\n\nThe target is: target_homevalue\n\nhomeid - Unique 5-digit home identifier\nfeat_yrbuilt - Year the home was built\nfeat_nrooms - Number of total rooms\nfeat_nbed - Number of bedrooms\nfeat_nbath - Number of bathrooms\nfeat_sqft - Squared footage of the entire home\nfeat_proptype - Whether the home is a single-family, multi-family, or condo\nfeat_basement - Whether the home has a basement\nfeat_stories - Whether the home has a single or multiple floors\nfeat_solar - Whether the home has solar panels\nfeat_nsales - Number of times sold in the past decade\ntarget_homevalue - Home values (rounded to the nearest dollar)\n```","metadata":{}},{"cell_type":"code","source":"!ls /kaggle/input/applications-of-gen-ai-wustl-fall-2024/*.csv","metadata":{"execution":{"iopub.status.busy":"2024-11-04T12:20:39.338877Z","iopub.execute_input":"2024-11-04T12:20:39.339346Z","iopub.status.idle":"2024-11-04T12:20:40.479412Z","shell.execute_reply.started":"2024-11-04T12:20:39.339307Z","shell.execute_reply":"2024-11-04T12:20:40.477836Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Import Libraries","metadata":{}},{"cell_type":"code","source":"import numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nfrom sklearn.preprocessing import LabelEncoder\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import mean_squared_error, mean_absolute_error, r2_score\nimport xgboost as xgb","metadata":{"execution":{"iopub.status.busy":"2024-11-04T12:20:40.481313Z","iopub.execute_input":"2024-11-04T12:20:40.481774Z","iopub.status.idle":"2024-11-04T12:20:42.317634Z","shell.execute_reply.started":"2024-11-04T12:20:40.481729Z","shell.execute_reply":"2024-11-04T12:20:42.316192Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Load Data","metadata":{}},{"cell_type":"code","source":"# Load the training and test datasets\ntrain_df = pd.read_csv('/kaggle/input/applications-of-gen-ai-wustl-fall-2024/df-train_1000x12.csv')\ntest_df = pd.read_csv('/kaggle/input/applications-of-gen-ai-wustl-fall-2024/df-test_200x11.csv')","metadata":{"execution":{"iopub.status.busy":"2024-11-04T12:20:42.320009Z","iopub.execute_input":"2024-11-04T12:20:42.320514Z","iopub.status.idle":"2024-11-04T12:20:42.358410Z","shell.execute_reply.started":"2024-11-04T12:20:42.320474Z","shell.execute_reply":"2024-11-04T12:20:42.357089Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Data Exploration\nLet's take a quick look at the datasets.","metadata":{}},{"cell_type":"code","source":"# Display first few rows of the training data\ntrain_df.head()","metadata":{"execution":{"iopub.status.busy":"2024-11-04T12:20:42.359831Z","iopub.execute_input":"2024-11-04T12:20:42.360281Z","iopub.status.idle":"2024-11-04T12:20:42.391134Z","shell.execute_reply.started":"2024-11-04T12:20:42.360236Z","shell.execute_reply":"2024-11-04T12:20:42.389667Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Display first few rows of the test data\ntest_df.head()","metadata":{"execution":{"iopub.status.busy":"2024-11-04T12:20:42.392823Z","iopub.execute_input":"2024-11-04T12:20:42.393298Z","iopub.status.idle":"2024-11-04T12:20:42.411546Z","shell.execute_reply.started":"2024-11-04T12:20:42.393244Z","shell.execute_reply":"2024-11-04T12:20:42.410055Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"print(f\"Training data shape: {train_df.shape}\")\nprint(f\"Test data shape: {test_df.shape}\")\n","metadata":{"execution":{"iopub.status.busy":"2024-11-04T12:20:42.413345Z","iopub.execute_input":"2024-11-04T12:20:42.414714Z","iopub.status.idle":"2024-11-04T12:20:42.421481Z","shell.execute_reply.started":"2024-11-04T12:20:42.414655Z","shell.execute_reply":"2024-11-04T12:20:42.420271Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Check for missing values in training data\ntrain_df.isnull().sum()","metadata":{"execution":{"iopub.status.busy":"2024-11-04T12:20:42.423347Z","iopub.execute_input":"2024-11-04T12:20:42.423831Z","iopub.status.idle":"2024-11-04T12:20:42.443278Z","shell.execute_reply.started":"2024-11-04T12:20:42.423780Z","shell.execute_reply":"2024-11-04T12:20:42.441432Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Check for missing values in test data\ntest_df.isnull().sum()","metadata":{"execution":{"iopub.status.busy":"2024-11-04T12:20:42.444780Z","iopub.execute_input":"2024-11-04T12:20:42.445173Z","iopub.status.idle":"2024-11-04T12:20:42.454932Z","shell.execute_reply.started":"2024-11-04T12:20:42.445132Z","shell.execute_reply":"2024-11-04T12:20:42.453849Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Data Preprocessing\n## Handle Categorical Variables\n\nThe following features are categorical:\n\n* ```feat_proptype:``` Type of property (single-family, multi-family, condo)\n* ```feat_basement:``` Whether the home has a basement (Yes/No)\n* ```feat_stories:``` Number of floors (Single/Multiple)\n* ```feat_solar:``` Whether the home has solar panels (Yes/No)\n\nWe will encode these categorical variables using LabelEncoder.\n\n","metadata":{}},{"cell_type":"code","source":"# Create copies to avoid modifying originals\ntrain_data = train_df.copy()\ntest_data = test_df.copy()\n\n# List of categorical columns\ncategorical_cols = ['feat_proptype', 'feat_basement', 'feat_stories', 'feat_solar']\n\n# Combine train and test data for consistent encoding\ncombined_data = pd.concat([train_data[categorical_cols], test_data[categorical_cols]], axis=0)\n\n# Apply Label Encoding\nfor col in categorical_cols:\n    le = LabelEncoder()\n    le.fit(combined_data[col])\n    train_data[col] = le.transform(train_data[col])\n    test_data[col] = le.transform(test_data[col])","metadata":{"execution":{"iopub.status.busy":"2024-11-04T12:20:42.458304Z","iopub.execute_input":"2024-11-04T12:20:42.458704Z","iopub.status.idle":"2024-11-04T12:20:42.481916Z","shell.execute_reply.started":"2024-11-04T12:20:42.458664Z","shell.execute_reply":"2024-11-04T12:20:42.480446Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Feature and Target Separation\nSeparate features and target variable from the training data.\n\n","metadata":{}},{"cell_type":"code","source":"X = train_data.drop(['homeid', 'target_homevalue'], axis=1)\ny = train_data['target_homevalue']\nX_test = test_data.drop(['homeid'], axis=1)","metadata":{"execution":{"iopub.status.busy":"2024-11-04T12:20:42.483286Z","iopub.execute_input":"2024-11-04T12:20:42.483825Z","iopub.status.idle":"2024-11-04T12:20:42.493796Z","shell.execute_reply.started":"2024-11-04T12:20:42.483769Z","shell.execute_reply":"2024-11-04T12:20:42.492279Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Train-Test Split\nSplit the training data into training and validation sets.\n","metadata":{}},{"cell_type":"code","source":"X_train, X_valid, y_train, y_valid = train_test_split(\n    X, y, test_size=0.2, random_state=42\n)","metadata":{"execution":{"iopub.status.busy":"2024-11-04T12:20:42.495245Z","iopub.execute_input":"2024-11-04T12:20:42.495730Z","iopub.status.idle":"2024-11-04T12:20:42.508760Z","shell.execute_reply.started":"2024-11-04T12:20:42.495682Z","shell.execute_reply":"2024-11-04T12:20:42.507053Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Model Training\nInitialize the XGBoost regressor and train it on the training set.\n\n","metadata":{}},{"cell_type":"code","source":"xgb_reg = xgb.XGBRegressor(\n    objective='reg:squarederror',\n    random_state=42,\n    n_estimators=100,\n    learning_rate=0.1,\n    max_depth=6\n)\n\nxgb_reg.fit(\n    X_train, y_train,\n    eval_set=[(X_valid, y_valid)],\n    verbose=True\n)\n\nprint(\"done\")","metadata":{"execution":{"iopub.status.busy":"2024-11-04T12:25:21.092888Z","iopub.execute_input":"2024-11-04T12:25:21.093336Z","iopub.status.idle":"2024-11-04T12:25:21.503814Z","shell.execute_reply.started":"2024-11-04T12:25:21.093297Z","shell.execute_reply":"2024-11-04T12:25:21.502499Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Model Evaluation\nEvaluate the model's performance on the validation set.\n\n","metadata":{}},{"cell_type":"code","source":"# Predict on validation set\ny_valid_pred = xgb_reg.predict(X_valid)\n\n# Calculate evaluation metrics\nmse = mean_squared_error(y_valid, y_valid_pred)\nmae = mean_absolute_error(y_valid, y_valid_pred)\nr2 = r2_score(y_valid, y_valid_pred)\n\nprint(f\"Validation MSE: {mse:.2f}\")\nprint(f\"Validation MAE: {mae:.2f}\")\nprint(f\"Validation R2 Score: {r2:.2f}\")","metadata":{"execution":{"iopub.status.busy":"2024-11-04T12:25:55.798619Z","iopub.execute_input":"2024-11-04T12:25:55.799037Z","iopub.status.idle":"2024-11-04T12:25:55.815078Z","shell.execute_reply.started":"2024-11-04T12:25:55.798996Z","shell.execute_reply":"2024-11-04T12:25:55.813823Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Prediction on Test Data\nRetrain the model on the entire training dataset and make predictions on the test dataset.\n\n","metadata":{}},{"cell_type":"code","source":"# Retrain on full training data\nxgb_reg.fit(\n    X_train, y_train,\n    eval_set=[(X_valid, y_valid)],\n    verbose=False\n)\n\n# Predict on test data\ny_test_pred = xgb_reg.predict(X_test)","metadata":{"execution":{"iopub.status.busy":"2024-11-04T12:27:43.526321Z","iopub.execute_input":"2024-11-04T12:27:43.526754Z","iopub.status.idle":"2024-11-04T12:27:43.659738Z","shell.execute_reply.started":"2024-11-04T12:27:43.526712Z","shell.execute_reply":"2024-11-04T12:27:43.658551Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Submission\nCreate a submission file with homeid and the predicted target_homevalue.\n\n","metadata":{}},{"cell_type":"code","source":"# Prepare the submission dataframe\nsubmission = pd.DataFrame({\n    'homeid': test_data['homeid'],\n    'target_homevalue': y_test_pred\n})\n\n# Save to CSV\nsubmission.to_csv('submission.csv', index=False)","metadata":{"execution":{"iopub.status.busy":"2024-11-04T12:27:48.953818Z","iopub.execute_input":"2024-11-04T12:27:48.954360Z","iopub.status.idle":"2024-11-04T12:27:48.963998Z","shell.execute_reply.started":"2024-11-04T12:27:48.954299Z","shell.execute_reply":"2024-11-04T12:27:48.962624Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"","metadata":{}},{"cell_type":"code","source":"submission.head()","metadata":{},"execution_count":null,"outputs":[]}]}