{"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":82611,"databundleVersionId":9553358,"sourceType":"competition"}],"dockerImageVersionId":30775,"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":false}},"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)\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-02T11:33:34.440628Z","iopub.execute_input":"2024-10-02T11:33:34.441678Z","iopub.status.idle":"2024-10-02T11:33:34.456685Z","shell.execute_reply.started":"2024-10-02T11:33:34.441621Z","shell.execute_reply":"2024-10-02T11:33:34.455385Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Neccessary Imports","metadata":{}},{"cell_type":"code","source":"from sklearn.model_selection import train_test_split\nfrom sklearn.impute import SimpleImputer\nfrom sklearn.preprocessing import MinMaxScaler\nfrom sklearn.tree import DecisionTreeRegressor\nfrom sklearn.ensemble import RandomForestRegressor\nfrom sklearn.metrics import mean_squared_error","metadata":{"execution":{"iopub.status.busy":"2024-10-02T11:33:39.771172Z","iopub.execute_input":"2024-10-02T11:33:39.771641Z","iopub.status.idle":"2024-10-02T11:33:39.778789Z","shell.execute_reply.started":"2024-10-02T11:33:39.771598Z","shell.execute_reply":"2024-10-02T11:33:39.777199Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Loading Datasets","metadata":{}},{"cell_type":"code","source":"df_train = pd.read_csv('/kaggle/input/brist1d/train.csv', low_memory=False)\ndf_test = pd.read_csv('/kaggle/input/brist1d/test.csv', low_memory=False)","metadata":{"execution":{"iopub.status.busy":"2024-10-02T11:33:43.822397Z","iopub.execute_input":"2024-10-02T11:33:43.822909Z","iopub.status.idle":"2024-10-02T11:34:05.991782Z","shell.execute_reply.started":"2024-10-02T11:33:43.822862Z","shell.execute_reply":"2024-10-02T11:34:05.990506Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"****Exploring Data****","metadata":{}},{"cell_type":"code","source":"df_train.isnull().sum()","metadata":{"execution":{"iopub.status.busy":"2024-10-02T11:34:05.994042Z","iopub.execute_input":"2024-10-02T11:34:05.994488Z","iopub.status.idle":"2024-10-02T11:34:06.749533Z","shell.execute_reply.started":"2024-10-02T11:34:05.994445Z","shell.execute_reply":"2024-10-02T11:34:06.748255Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df_test.isnull().sum()","metadata":{"execution":{"iopub.status.busy":"2024-10-02T11:34:06.780042Z","iopub.execute_input":"2024-10-02T11:34:06.780433Z","iopub.status.idle":"2024-10-02T11:34:06.806458Z","shell.execute_reply.started":"2024-10-02T11:34:06.780394Z","shell.execute_reply":"2024-10-02T11:34:06.805235Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Preprocessing","metadata":{}},{"cell_type":"code","source":"# Converting 'time' object column into datetime in order to use it for training\n\ndf_train['time'] = pd.to_datetime(df_train['time'], format='%H:%M:%S')\ndf_test['time'] = pd.to_datetime(df_test['time'], format='%H:%M:%S')\n\n# Extracting hour and minute as different numerical features\n\ndf_train['hour'] = df_train['time'].dt.hour\ndf_train['minute'] = df_train['time'].dt.minute\ndf_test['hour'] = df_test['time'].dt.hour\ndf_test['minute'] = df_test['time'].dt.minute\n\n# Drop 'time' column because we have already extract hour and minute into separate columns\n\ndf_train.drop('time', axis=1, inplace=True)\ndf_test.drop('time', axis=1, inplace=True)","metadata":{"execution":{"iopub.status.busy":"2024-10-02T11:34:06.808050Z","iopub.execute_input":"2024-10-02T11:34:06.808533Z","iopub.status.idle":"2024-10-02T11:34:07.279372Z","shell.execute_reply.started":"2024-10-02T11:34:06.808481Z","shell.execute_reply":"2024-10-02T11:34:07.278242Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Identify columns that are not numeric in df_train (like 'activity','id',p_num)\n\nnon_numeric_columns = df_train.select_dtypes(include=['object']).columns\n\n# Drop the non-numeric columns from df_train (like 'activity','id',p_num)\n\ndf_train.drop(columns=non_numeric_columns,axis=1,inplace=True)","metadata":{"execution":{"iopub.status.busy":"2024-10-02T11:34:11.989192Z","iopub.execute_input":"2024-10-02T11:34:11.989656Z","iopub.status.idle":"2024-10-02T11:34:12.887427Z","shell.execute_reply.started":"2024-10-02T11:34:11.989613Z","shell.execute_reply":"2024-10-02T11:34:12.886001Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Identify drop 'activity' categorical columns from df_test because it contains many missing values and imputing it may affect the training\n\ncategorical_cols = [col for col in df_test.columns if 'activity' in col]\n\ndf_test.drop(columns=categorical_cols,axis=1,inplace=True)","metadata":{"execution":{"iopub.status.busy":"2024-10-02T11:34:15.204949Z","iopub.execute_input":"2024-10-02T11:34:15.205387Z","iopub.status.idle":"2024-10-02T11:34:15.218513Z","shell.execute_reply.started":"2024-10-02T11:34:15.205347Z","shell.execute_reply":"2024-10-02T11:34:15.217239Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"**I didn't drop 'id' from df_test as it is required for sumission**","metadata":{}},{"cell_type":"code","source":"# Preparing \"training\" and \"training validation\" data\n\nX = df_train.drop(['bg+1:00'], axis=1)\ny = df_train['bg+1:00']\n\ny_filled = y.fillna(y.mean()) #It contains missing value that's why filling it with mean\n\n\nX_train,X_val,y_train,y_val = train_test_split(X,y_filled,test_size=0.2,random_state=44)\n\n# Preparing df_test for submission\nX_test = df_test.drop(['id', 'p_num'], axis=1)\n\n\nnumerical_cols = df_train.select_dtypes(include=['float64', 'int64']).columns.tolist()\nnumerical_cols.remove('bg+1:00')","metadata":{"execution":{"iopub.status.busy":"2024-10-02T11:34:20.342469Z","iopub.execute_input":"2024-10-02T11:34:20.342968Z","iopub.status.idle":"2024-10-02T11:34:21.363301Z","shell.execute_reply.started":"2024-10-02T11:34:20.342924Z","shell.execute_reply":"2024-10-02T11:34:21.361946Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Imputation on input \n\nimputer = SimpleImputer(strategy='mean')\n\nX_train_trf = imputer.fit_transform(X_train)\nX_val_trf = imputer.fit_transform(X_val)\n\nX_test_trf = imputer.transform(X_test)","metadata":{"execution":{"iopub.status.busy":"2024-10-02T11:34:24.983421Z","iopub.execute_input":"2024-10-02T11:34:24.983895Z","iopub.status.idle":"2024-10-02T11:34:28.318317Z","shell.execute_reply.started":"2024-10-02T11:34:24.983812Z","shell.execute_reply":"2024-10-02T11:34:28.316912Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Scaling on input \n\nscaler = MinMaxScaler()\n\nX_train_scaled = scaler.fit_transform(X_train_trf)\nX_val_scaled = scaler.fit_transform(X_val_trf)\nX_test_scaled = scaler.transform(X_test_trf)","metadata":{"execution":{"iopub.status.busy":"2024-10-02T11:34:29.763739Z","iopub.execute_input":"2024-10-02T11:34:29.764605Z","iopub.status.idle":"2024-10-02T11:34:30.386295Z","shell.execute_reply.started":"2024-10-02T11:34:29.764557Z","shell.execute_reply":"2024-10-02T11:34:30.384899Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Training And Testing","metadata":{}},{"cell_type":"markdown","source":"I Will train Decision Tree and Random Forest to see which performs best","metadata":{}},{"cell_type":"markdown","source":"# Decision Tree","metadata":{}},{"cell_type":"code","source":"dt = DecisionTreeRegressor(max_depth=None,criterion='squared_error')\n\ndt.fit(X_train_scaled,y_train)\n\ndt_pred = dt.predict(X_val_scaled)\n\nprint(\"RMSE OF DecisionTreeRegressor: \",np.sqrt(mean_squared_error(y_val,dt_pred)))","metadata":{"execution":{"iopub.status.busy":"2024-10-02T11:34:37.269947Z","iopub.execute_input":"2024-10-02T11:34:37.270429Z","iopub.status.idle":"2024-10-02T11:35:51.915139Z","shell.execute_reply.started":"2024-10-02T11:34:37.270384Z","shell.execute_reply":"2024-10-02T11:35:51.913838Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Random Forest","metadata":{}},{"cell_type":"code","source":"rf = RandomForestRegressor(n_jobs=-1)\n \nrf.fit(X_train_trf,y_train)\n\nrf_pred = rf.predict(X_val_trf)\n\nprint(\"RMSE OF RandomForestRegressor: \",np.sqrt(mean_squared_error(y_val,rf_pred)))","metadata":{"execution":{"iopub.status.busy":"2024-10-02T12:05:55.635167Z","iopub.execute_input":"2024-10-02T12:05:55.635543Z","iopub.status.idle":"2024-10-02T12:35:58.153376Z","shell.execute_reply.started":"2024-10-02T12:05:55.635503Z","shell.execute_reply":"2024-10-02T12:35:58.152276Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"Lets do hyperparameters tuning on above random forest","metadata":{}},{"cell_type":"markdown","source":"Row Sampling with bootstrap true","metadata":{}},{"cell_type":"code","source":"# lets improvie it by taking 85% of rows\nrf = RandomForestRegressor(\nmax_samples = 0.85,\nbootstrap = True,\nn_jobs = -1\n)\n \nrf.fit(X_train_trf,y_train)\n\nrf_pred = rf.predict(X_val_trf)\n\nprint(\"RMSE OF RandomForestRegressor: \",np.sqrt(mean_squared_error(y_val,rf_pred)))","metadata":{"execution":{"iopub.status.busy":"2024-10-02T13:26:17.130422Z","iopub.execute_input":"2024-10-02T13:26:17.130911Z","iopub.status.idle":"2024-10-02T13:53:38.642240Z","shell.execute_reply.started":"2024-10-02T13:26:17.130869Z","shell.execute_reply":"2024-10-02T13:53:38.640780Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"As Random Forest with 0.85 max_samples it decrese peformance little bit","metadata":{}},{"cell_type":"markdown","source":"Now lets try random patches","metadata":{}},{"cell_type":"code","source":"# lets try random patches\nrf = RandomForestRegressor(\nmax_samples = 0.85,\nmax_features = 0.25,  \nbootstrap = True,\nn_jobs = -1\n)\n \nrf.fit(X_train_trf,y_train)\n\nrf_pred = rf.predict(X_val_trf)\n\nprint(\"RMSE OF RandomForestRegressor: \",np.sqrt(mean_squared_error(y_val,rf_pred)))","metadata":{"execution":{"iopub.status.busy":"2024-10-02T14:06:03.256809Z","iopub.execute_input":"2024-10-02T14:06:03.257323Z","iopub.status.idle":"2024-10-02T14:12:59.666300Z","shell.execute_reply.started":"2024-10-02T14:06:03.257279Z","shell.execute_reply":"2024-10-02T14:12:59.665061Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"Random Patches has improved our model performance lets use this for prediction","metadata":{}},{"cell_type":"markdown","source":"# Submission","metadata":{}},{"cell_type":"code","source":"# Preparing Submission File\n\n# prediction on our X_test_trf or (df_test on which we have to predict and create a submission file)\n\ny_pred = rf.predict(X_test_scaled)\n\n\nsubmission_file = pd.DataFrame({\n    'id': df_test['id'],\n    'bg+1:00': y_pred\n})\n\nsubmission_file.to_csv('/kaggle/working/submission.csv',index=False)","metadata":{"execution":{"iopub.status.busy":"2024-10-02T14:13:30.557552Z","iopub.execute_input":"2024-10-02T14:13:30.558057Z","iopub.status.idle":"2024-10-02T14:13:30.644991Z","shell.execute_reply.started":"2024-10-02T14:13:30.558005Z","shell.execute_reply":"2024-10-02T14:13:30.643575Z"},"trusted":true},"execution_count":null,"outputs":[]}]}