{"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":"nvidiaTeslaT4","dataSources":[{"sourceId":82611,"databundleVersionId":9553358,"sourceType":"competition"}],"dockerImageVersionId":30786,"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":true}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"code","source":"# This Python 3 environment comes with many helpful analytics libraries installed\n# It is defined by the kaggle/python Docker image: https://github.com/kaggle/docker-python\n# For example, here's several helpful packages to load\n\nimport numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)\nimport matplotlib.pyplot as plt\n\n# Input data files are available in the read-only \"../input/\" directory\n# For example, running this (by clicking run or pressing Shift+Enter) will list all files under the input directory\n\nimport os\nfor dirname, _, filenames in os.walk('/kaggle/input'):\n    for filename in filenames:\n        print(os.path.join(dirname, filename))\n\n# You can write up to 20GB to the current directory (/kaggle/working/) that gets preserved as output when you create a version using \"Save & Run All\" \n# You can also write temporary files to /kaggle/temp/, but they won't be saved outside of the current session","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","execution":{"iopub.status.busy":"2024-10-06T12:18:21.487568Z","iopub.execute_input":"2024-10-06T12:18:21.488077Z","iopub.status.idle":"2024-10-06T12:18:21.498509Z","shell.execute_reply.started":"2024-10-06T12:18:21.488023Z","shell.execute_reply":"2024-10-06T12:18:21.497400Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"Let's import necessary libraries","metadata":{}},{"cell_type":"code","source":"import numpy as np\nimport catboost as cb\nimport xgboost as xgb\nfrom sklearn.svm import SVR\nfrom sklearn.impute import SimpleImputer \nfrom sklearn.model_selection import KFold\nfrom sklearn.metrics import mean_squared_error\nfrom sklearn.tree import DecisionTreeRegressor\nfrom sklearn.preprocessing import StandardScaler, LabelEncoder\nfrom sklearn.ensemble import AdaBoostRegressor, RandomForestRegressor\nfrom sklearn.linear_model import LinearRegression, Ridge, Lasso, ElasticNet","metadata":{"execution":{"iopub.status.busy":"2024-10-06T12:18:21.500236Z","iopub.execute_input":"2024-10-06T12:18:21.500919Z","iopub.status.idle":"2024-10-06T12:18:21.527815Z","shell.execute_reply.started":"2024-10-06T12:18:21.500883Z","shell.execute_reply":"2024-10-06T12:18:21.526772Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"Let us load the train and test datasets","metadata":{}},{"cell_type":"code","source":"train = pd.read_csv('/kaggle/input/brist1d/train.csv', low_memory=False)\ntest = pd.read_csv('/kaggle/input/brist1d/test.csv', low_memory=False)","metadata":{"execution":{"iopub.status.busy":"2024-10-06T12:18:21.529457Z","iopub.execute_input":"2024-10-06T12:18:21.530231Z","iopub.status.idle":"2024-10-06T12:18:35.857788Z","shell.execute_reply.started":"2024-10-06T12:18:21.530180Z","shell.execute_reply":"2024-10-06T12:18:35.856982Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"Let us see calculate some statistics on our dataset","metadata":{}},{"cell_type":"code","source":"train.describe()","metadata":{"execution":{"iopub.status.busy":"2024-10-06T12:18:35.858983Z","iopub.execute_input":"2024-10-06T12:18:35.859809Z","iopub.status.idle":"2024-10-06T12:18:39.042199Z","shell.execute_reply.started":"2024-10-06T12:18:35.859772Z","shell.execute_reply":"2024-10-06T12:18:39.041219Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"Now, we will check how many empty data points are there in our datasets","metadata":{}},{"cell_type":"code","source":"train.isnull().sum()","metadata":{"execution":{"iopub.status.busy":"2024-10-06T12:18:39.044865Z","iopub.execute_input":"2024-10-06T12:18:39.045206Z","iopub.status.idle":"2024-10-06T12:18:39.641409Z","shell.execute_reply.started":"2024-10-06T12:18:39.045172Z","shell.execute_reply":"2024-10-06T12:18:39.640430Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"test.isnull().sum()","metadata":{"execution":{"iopub.status.busy":"2024-10-06T12:18:39.642691Z","iopub.execute_input":"2024-10-06T12:18:39.643071Z","iopub.status.idle":"2024-10-06T12:18:39.664302Z","shell.execute_reply.started":"2024-10-06T12:18:39.643035Z","shell.execute_reply":"2024-10-06T12:18:39.663392Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"We will also see the percentage of missing data in each of the columns","metadata":{}},{"cell_type":"code","source":"missing_values = train.isnull().sum()\n\n\ntotal_rows = train.shape[0]\nmissing_percentage = (missing_values / total_rows) * 100\n\n\nresults_df = pd.DataFrame({'Column': missing_values.index,\n                          'Missing Values': missing_values.values,\n                          'Missing Percentage (%)': missing_percentage.values})\n\n\nresults_df = results_df.sort_values(by='Missing Percentage (%)', ascending=False)\n\nprint(results_df)","metadata":{"execution":{"iopub.status.busy":"2024-10-06T12:18:39.665431Z","iopub.execute_input":"2024-10-06T12:18:39.665726Z","iopub.status.idle":"2024-10-06T12:18:40.263915Z","shell.execute_reply.started":"2024-10-06T12:18:39.665679Z","shell.execute_reply":"2024-10-06T12:18:40.262897Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"Convert 'time' column to datetime that can be used as a feature","metadata":{}},{"cell_type":"code","source":"train['time'] = pd.to_datetime(train['time'], format='%H:%M:%S')\ntest['time'] = pd.to_datetime(test['time'], format='%H:%M:%S')\n\n\n\ntrain['hour'] = train['time'].dt.hour\ntrain['minute'] = train['time'].dt.minute\ntrain.drop('time', axis=1, inplace=True)\n\ntest['hour'] = test['time'].dt.hour\ntest['minute'] = test['time'].dt.minute\ntest.drop('time', axis=1, inplace=True)\n","metadata":{"execution":{"iopub.status.busy":"2024-10-06T12:18:40.265229Z","iopub.execute_input":"2024-10-06T12:18:40.265682Z","iopub.status.idle":"2024-10-06T12:18:40.620516Z","shell.execute_reply.started":"2024-10-06T12:18:40.265638Z","shell.execute_reply":"2024-10-06T12:18:40.619674Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"Next thing we will segregate the numerical and categorical columns. It is because we will preporcess these columns separetely.\n\nFor numerical columns,we will first fill the empty columns and then apply standar scaler\n\nFor categorical columns , we will apply label encoder to assign labels to the categories","metadata":{}},{"cell_type":"code","source":"numerical_cols = train.select_dtypes(include=['float64', 'int64']).columns.tolist()\nnumerical_cols.remove('bg+1:00')\ncategorical_cols = [col for col in train.columns if 'activity' in col]","metadata":{"execution":{"iopub.status.busy":"2024-10-06T12:18:40.621838Z","iopub.execute_input":"2024-10-06T12:18:40.622261Z","iopub.status.idle":"2024-10-06T12:18:40.842204Z","shell.execute_reply.started":"2024-10-06T12:18:40.622196Z","shell.execute_reply":"2024-10-06T12:18:40.841374Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"imputer = SimpleImputer(strategy='constant', fill_value = 0)             #Not sure if mean would be the right measure. For next versions, I will ty with other methods\ntrain[numerical_cols] = imputer.fit_transform(train[numerical_cols])\ntest[numerical_cols] = imputer.transform(test[numerical_cols])\n\nfor col in categorical_cols:\n    train[col] = train[col].fillna('None')\n    test[col] = test[col].fillna('None')\n    le = LabelEncoder()\n    combined_data = pd.concat([train[col], test[col]], axis=0)\n    le.fit(combined_data)\n    train[col] = le.transform(train[col])\n    test[col] = le.transform(test[col])\n\n\nscaler = StandardScaler()                        #we can use minmax scaler as well based on performamnce\ntrain[numerical_cols] = scaler.fit_transform(train[numerical_cols])\ntest[numerical_cols] = scaler.transform(test[numerical_cols])","metadata":{"execution":{"iopub.status.busy":"2024-10-06T12:18:40.843574Z","iopub.execute_input":"2024-10-06T12:18:40.844248Z","iopub.status.idle":"2024-10-06T12:18:49.294890Z","shell.execute_reply.started":"2024-10-06T12:18:40.844201Z","shell.execute_reply":"2024-10-06T12:18:49.294115Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"Let's separate the train dataset and test dataset by removing the target variable from feature variables","metadata":{}},{"cell_type":"code","source":"X = train.drop(['id', 'p_num', 'bg+1:00'], axis=1)\ny = train['bg+1:00']\n\nX_test_final = test.drop(['id', 'p_num'], axis=1)","metadata":{"execution":{"iopub.status.busy":"2024-10-06T12:18:49.295952Z","iopub.execute_input":"2024-10-06T12:18:49.296263Z","iopub.status.idle":"2024-10-06T12:18:50.007700Z","shell.execute_reply.started":"2024-10-06T12:18:49.296230Z","shell.execute_reply":"2024-10-06T12:18:50.006910Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"This is just to make sure we have all the columns in numerical values before we start training the model","metadata":{}},{"cell_type":"code","source":"non_numeric_cols = X.select_dtypes(include=['object']).columns.tolist()\nif non_numeric_cols:\n    print(\"Non-numeric columns in X_train:\", non_numeric_cols)\n    \n    X.drop(non_numeric_cols, axis=1, inplace=True)\n    X_test_final.drop(non_numeric_cols, axis=1, inplace=True)","metadata":{"execution":{"iopub.status.busy":"2024-10-06T12:18:50.008817Z","iopub.execute_input":"2024-10-06T12:18:50.009134Z","iopub.status.idle":"2024-10-06T12:18:50.015096Z","shell.execute_reply.started":"2024-10-06T12:18:50.009090Z","shell.execute_reply":"2024-10-06T12:18:50.014272Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"Now since I wanted to try most of the models to see which one is performing better, I kind of trained all the models one by one in loop and then cross validated and took the average RMSE value. Then, I will use the model with lowest RMSE to perform further testing","metadata":{}},{"cell_type":"code","source":"# models = {\n#     \"Linear Regression\": LinearRegression(),\n#     \"Ridge Regression\": Ridge(alpha=1.0),\n#     \"Lasso Regression\": Lasso(alpha=0.1),\n#     \"ElasticNet\": ElasticNet(alpha=0.1, l1_ratio=0.5),\n#     \"Decision Tree\": DecisionTreeRegressor(max_depth=25, random_state=69),\n#     \"Random Forest\": RandomForestRegressor(n_estimators=250, max_depth=25, random_state=69),\n#     \"SVR\": SVR(kernel='rbf', C=1.0, epsilon=0.1),\n#     \"XGBoost\": xgb.XGBRegressor(n_estimators=250, max_depth=25, tree_method='hist', device='cuda', random_state=69),\n#     \"AdaBoost\": AdaBoostRegressor(n_estimators=250, random_state=69),\n#     \"CatBoost\": cb.CatBoostRegressor(n_estimators=250, depth=10, task_type=\"GPU\", devices='0', random_state=69, silent=True),\n# }\n\n# kf = KFold(n_splits=5, shuffle=True, random_state=69)\n\n# rmse_scores = {}\n\n# for model_name, model in models.items():\n#     cv_scores = []\n    \n    \n#     for train_index, test_index in kf.split(X,y):\n        \n#         X_train, X_test = X.iloc[train_index], X.iloc[test_index]\n#         y_train, y_test = y.iloc[train_index], y.iloc[test_index]\n        \n#         model.fit(X_train, y_train)\n        \n#         y_pred = model.predict(X_test)\n        \n#         rmse = np.sqrt(mean_squared_error(y_test, y_pred))\n#         cv_scores.append(rmse)\n    \n#     avg_rmse = np.mean(cv_scores)\n#     rmse_scores[model_name] = avg_rmse\n#     print(f\"{model_name} RMSE: {avg_rmse}\")\n\n# best_model_name = min(rmse_scores, key=rmse_scores.get)\n# print(f\"Best model: {best_model_name} with RMSE: {rmse_scores[best_model_name]}\")\n","metadata":{"execution":{"iopub.status.busy":"2024-10-06T12:18:50.016371Z","iopub.execute_input":"2024-10-06T12:18:50.016689Z","iopub.status.idle":"2024-10-06T12:18:50.024891Z","shell.execute_reply.started":"2024-10-06T12:18:50.016657Z","shell.execute_reply":"2024-10-06T12:18:50.024031Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"Just a heads up, since some of the above mentioned models don't support computation on GPU natively, It is going to take a lot of time to train these models. Hence, I have added cuML supported models to increase the computation speed.","metadata":{}},{"cell_type":"code","source":"# import cuml\n# from cuml import Ridge as cuRidge\n# from cuml import Lasso as cuLasso\n# from cuml import ElasticNet as cuElasticNet\n# from cuml.ensemble import RandomForestRegressor as cuRandomForest\n# from cuml import SVR as cuSVR\n\n\n\n# models = {\n#     \"cuML Ridge Regression\": cuRidge(alpha=1.0),\n#     \"cuML Lasso Regression\": cuLasso(alpha=0.1),\n#     \"cuML ElasticNet\": cuElasticNet(alpha=0.1, l1_ratio=0.5),\n#     \"cuML Random Forest\": cuRandomForest(n_estimators=250, max_depth=25, random_state=69),\n#     \"Decision Tree\": DecisionTreeRegressor(max_depth=25, random_state=69),\n#     \"cuML SVR\": cuSVR(kernel='rbf', C=1.0, epsilon=0.1),\n#     \"XGBoost\": xgb.XGBRegressor(n_estimators=250, max_depth=25, tree_method='hist', device='cuda', random_state=69),\n#     \"AdaBoost\": AdaBoostRegressor(n_estimators=250, random_state=69), \n#     \"CatBoost\": cb.CatBoostRegressor(n_estimators=250, depth=10, task_type=\"GPU\", devices='0', random_state=69, silent=True),\n# }\n\n\n# kf = KFold(n_splits=5, shuffle=True, random_state=69)\n\n# rmse_scores = {}\n\n# for model_name, model in models.items():\n#     cv_scores = []\n    \n#     for train_index, test_index in kf.split(X):\n\n#         X_train, X_test = X.iloc[train_index], X.iloc[test_index]\n#         y_train, y_test = y.iloc[train_index], y.iloc[test_index]\n        \n#         model.fit(X_train, y_train)\n        \n#         y_pred = model.predict(X_test)\n        \n#         rmse = np.sqrt(mean_squared_error(y_test, y_pred))\n#         cv_scores.append(rmse)\n    \n#     avg_rmse = np.mean(cv_scores)\n#     rmse_scores[model_name] = avg_rmse\n#     print(f\"{model_name} RMSE: {avg_rmse}\")\n\n    \n# best_model_name = min(rmse_scores, key=rmse_scores.get)\n# print(f\"Best model: {best_model_name} with RMSE: {rmse_scores[best_model_name]}\")\n","metadata":{"execution":{"iopub.status.busy":"2024-10-06T12:18:50.027918Z","iopub.execute_input":"2024-10-06T12:18:50.028423Z","iopub.status.idle":"2024-10-06T12:18:50.036435Z","shell.execute_reply.started":"2024-10-06T12:18:50.028390Z","shell.execute_reply":"2024-10-06T12:18:50.035499Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"So we can see that the XG Boost is perfroming better, so we will continue our hperparameter tuning for this model in our next version","metadata":{}},{"cell_type":"code","source":"models = {\n    \"XGBoost\": xgb.XGBRegressor(objective='reg:squarederror', n_estimators=100, max_depth=25, tree_method='hist', device='cuda', random_state=69),\n}\n\n\nkf = KFold(n_splits=5, shuffle=True, random_state=69)\n\nmodel = models[\"XGBoost\"]\ncv_scores = []\n    \nfor train_index, test_index in kf.split(X):\n\n    X_train, X_test = X.iloc[train_index], X.iloc[test_index]\n    y_train, y_test = y.iloc[train_index], y.iloc[test_index]\n\n    model.fit(X_train, y_train)\n\n    y_pred = model.predict(X_test)\n\n    rmse = np.sqrt(mean_squared_error(y_test, y_pred))\n    cv_scores.append(rmse)\n\navg_rmse = np.mean(cv_scores)\nprint(avg_rmse)\n\n\n","metadata":{"execution":{"iopub.status.busy":"2024-10-06T12:18:50.037600Z","iopub.execute_input":"2024-10-06T12:18:50.037930Z","iopub.status.idle":"2024-10-06T12:37:55.878645Z","shell.execute_reply.started":"2024-10-06T12:18:50.037898Z","shell.execute_reply":"2024-10-06T12:37:55.877731Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"Now let's submit our results and see how it is performing","metadata":{}},{"cell_type":"code","source":"test_preds = model.predict(X_test_final)\n\n\nsubmission = pd.DataFrame({\n    'id': test['id'],\n    'bg+1:00': test_preds\n})\n\nsubmission.to_csv('/kaggle/working/submission.csv', index=False)","metadata":{"execution":{"iopub.status.busy":"2024-10-06T12:42:09.663445Z","iopub.execute_input":"2024-10-06T12:42:09.664343Z","iopub.status.idle":"2024-10-06T12:42:09.830050Z","shell.execute_reply.started":"2024-10-06T12:42:09.664298Z","shell.execute_reply":"2024-10-06T12:42:09.829078Z"},"trusted":true},"execution_count":null,"outputs":[]}]}