{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"name":"python","version":"3.10.13","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"},"kaggle":{"accelerator":"none","dataSources":[{"sourceId":82253,"databundleVersionId":8965849,"sourceType":"competition"}],"dockerImageVersionId":30732,"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-06-29T05:32:06.198228Z","iopub.execute_input":"2024-06-29T05:32:06.198640Z","iopub.status.idle":"2024-06-29T05:32:07.288826Z","shell.execute_reply.started":"2024-06-29T05:32:06.198605Z","shell.execute_reply":"2024-06-29T05:32:07.287449Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"**Load the training data and testing data**\n\n* Store Training data in train_df\n* Store Testing data in test_df","metadata":{}},{"cell_type":"code","source":"train1_df=pd.read_csv(\"/kaggle/input/f1nalyze-datathon-ieeecsmuj/train.csv\")\nvalidation_df=pd.read_csv(\"/kaggle/input/f1nalyze-datathon-ieeecsmuj/validation.csv\")\ntest_df=pd.read_csv(\"/kaggle/input/f1nalyze-datathon-ieeecsmuj/test.csv\")","metadata":{"execution":{"iopub.status.busy":"2024-06-29T05:32:07.291766Z","iopub.execute_input":"2024-06-29T05:32:07.292426Z","iopub.status.idle":"2024-06-29T05:32:56.635174Z","shell.execute_reply.started":"2024-06-29T05:32:07.292382Z","shell.execute_reply":"2024-06-29T05:32:56.633969Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train1_df.head()","metadata":{"execution":{"iopub.status.busy":"2024-06-29T05:32:56.636686Z","iopub.execute_input":"2024-06-29T05:32:56.637048Z","iopub.status.idle":"2024-06-29T05:32:56.682131Z","shell.execute_reply.started":"2024-06-29T05:32:56.637000Z","shell.execute_reply":"2024-06-29T05:32:56.680374Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"validation_df.head()","metadata":{"execution":{"iopub.status.busy":"2024-06-29T05:32:56.684872Z","iopub.execute_input":"2024-06-29T05:32:56.685725Z","iopub.status.idle":"2024-06-29T05:32:56.716178Z","shell.execute_reply.started":"2024-06-29T05:32:56.685682Z","shell.execute_reply":"2024-06-29T05:32:56.714957Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"test_df.head()","metadata":{"execution":{"iopub.status.busy":"2024-06-29T05:32:56.717532Z","iopub.execute_input":"2024-06-29T05:32:56.717948Z","iopub.status.idle":"2024-06-29T05:32:56.745696Z","shell.execute_reply.started":"2024-06-29T05:32:56.717902Z","shell.execute_reply":"2024-06-29T05:32:56.744420Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_df = pd.concat([train1_df, validation_df], ignore_index=True)","metadata":{"execution":{"iopub.status.busy":"2024-06-29T05:32:56.747314Z","iopub.execute_input":"2024-06-29T05:32:56.747689Z","iopub.status.idle":"2024-06-29T05:32:58.353667Z","shell.execute_reply.started":"2024-06-29T05:32:56.747644Z","shell.execute_reply":"2024-06-29T05:32:58.352344Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_df.head()","metadata":{"execution":{"iopub.status.busy":"2024-06-29T05:32:58.355295Z","iopub.execute_input":"2024-06-29T05:32:58.355673Z","iopub.status.idle":"2024-06-29T05:32:58.386619Z","shell.execute_reply.started":"2024-06-29T05:32:58.355633Z","shell.execute_reply":"2024-06-29T05:32:58.385226Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"**EDA**","metadata":{}},{"cell_type":"code","source":"import pandas as pd\nimport matplotlib.pyplot as plt\n\n\n# Group by driverId and sum the points for each driver\npoints_sum = train_df.groupby('driverId')['points'].sum()\n\n# Get the top 5 drivers with the most points\ntop_5_points = points_sum.nlargest(5)\n\n# Create a DataFrame for the top 5 drivers\ntop_5_df = pd.DataFrame({\n    'driverId': top_5_points.index,\n    'total_points': top_5_points.values\n})\n\n# Get driver names\ndriver_names = []\nfor driver_id in top_5_df['driverId']:\n    driver_details = train_df[train_df['driverId'] == driver_id].iloc[0]\n    driver_name = f\"{driver_details['forename']} {driver_details['surname']}\"\n    driver_names.append(driver_name)\n\ntop_5_df['driver_name'] = driver_names\n\n# Plotting\nfig, ax = plt.subplots(figsize=(10, 6))\nax.barh(top_5_df['driver_name'], top_5_df['total_points'], color='skyblue')\n\n# Add labels, title, and legend\nax.set_xlabel('Total Points')\nax.set_ylabel('Driver Name')\nax.set_title('Top 5 Drivers with Most Points in F1 History')\nax.invert_yaxis()  # Invert y-axis to show the driver with the most points at the top\n\n# Show plot\nplt.tight_layout()\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2024-06-29T05:32:58.387846Z","iopub.execute_input":"2024-06-29T05:32:58.388256Z","iopub.status.idle":"2024-06-29T05:32:59.163977Z","shell.execute_reply.started":"2024-06-29T05:32:58.388214Z","shell.execute_reply":"2024-06-29T05:32:59.162598Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Filter the dataset to only include rows where a driver has won a race\nwins_df = train_df[train_df['wins'] > 0]\n\n# Group by driverId and count the wins for each driver\nwins_count = wins_df.groupby('driverId')['wins'].sum()\n\n# Get the top 5 drivers with the most wins\ntop_5_wins = wins_count.nlargest(5)\n\n# Create a DataFrame for the top 5 drivers\ntop_5_df = pd.DataFrame({\n    'driverId': top_5_wins.index,\n    'total_wins': top_5_wins.values\n})\n\n# Get driver names\ndriver_names = []\nfor driver_id in top_5_df['driverId']:\n    driver_details = train_df[train_df['driverId'] == driver_id].iloc[0]\n    driver_name = f\"{driver_details['forename']} {driver_details['surname']}\"\n    driver_names.append(driver_name)\n\ntop_5_df['driver_name'] = driver_names\n\n# Plotting\nfig, ax = plt.subplots(figsize=(10, 6))\nax.barh(top_5_df['driver_name'], top_5_df['total_wins'], color='skyblue')\n\n# Add labels, title, and legend\nax.set_xlabel('Total Wins')\nax.set_ylabel('Driver Name')\nax.set_title('Top 5 Drivers with Most Wins in F1 History')\nax.invert_yaxis()  # Invert y-axis to show the driver with the most wins at the top\n\n# Show plot\nplt.tight_layout()\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2024-06-29T05:33:26.527199Z","iopub.execute_input":"2024-06-29T05:33:26.527648Z","iopub.status.idle":"2024-06-29T05:33:27.533212Z","shell.execute_reply.started":"2024-06-29T05:33:26.527613Z","shell.execute_reply":"2024-06-29T05:33:27.532069Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Filter the dataset to only include rows where a team has won a race\nwins_df = train_df[train_df['wins'] > 0]\n\n# Group by constructorId and count the wins for each team\nwins_count = wins_df.groupby('constructorId')['wins'].sum()\n\n# Get the top 5 teams with the most wins\ntop_5_wins = wins_count.nlargest(5)\n\n# Create a DataFrame for the top 5 teams\ntop_5_df = pd.DataFrame({\n    'constructorId': top_5_wins.index,\n    'total_wins': top_5_wins.values\n})\n\n# Get team names\nteam_names = []\nfor constructor_id in top_5_df['constructorId']:\n    team_details = train_df[train_df['constructorId'] == constructor_id].iloc[0]\n    team_name = team_details['company']\n    team_names.append(team_name)\n\ntop_5_df['team_name'] = team_names\n\n# Plotting\nfig, ax = plt.subplots(figsize=(10, 6))\nax.barh(top_5_df['team_name'], top_5_df['total_wins'], color='skyblue')\n\n# Add labels, title, and legend\nax.set_xlabel('Total Wins')\nax.set_ylabel('Team Name')\nax.set_title('Top 5 Teams with Most Wins in F1 History')\nax.invert_yaxis()  # Invert y-axis to show the team with the most wins at the top\n\n# Show plot\nplt.tight_layout()\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2024-06-29T05:34:26.533676Z","iopub.execute_input":"2024-06-29T05:34:26.534140Z","iopub.status.idle":"2024-06-29T05:34:28.227120Z","shell.execute_reply.started":"2024-06-29T05:34:26.534103Z","shell.execute_reply":"2024-06-29T05:34:28.225673Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Group by constructorId and sum the points for each team\npoints_count = train_df.groupby('constructorId')['points'].sum()\n\n# Get the top 5 teams with the most points\ntop_5_points = points_count.nlargest(5)\n\n# Create a DataFrame for the top 5 teams\ntop_5_df = pd.DataFrame({\n    'constructorId': top_5_points.index,\n    'total_points': top_5_points.values\n})\n\n# Get team names\nteam_names = []\nfor constructor_id in top_5_df['constructorId']:\n    team_details = train_df[train_df['constructorId'] == constructor_id].iloc[0]\n    team_name = team_details['company']\n    team_names.append(team_name)\n\ntop_5_df['team_name'] = team_names\n\n# Plotting\nfig, ax = plt.subplots(figsize=(10, 6))\nax.barh(top_5_df['team_name'], top_5_df['total_points'], color='skyblue')\n\n# Add labels, title, and legend\nax.set_xlabel('Total Points')\nax.set_ylabel('Team Name')\nax.set_title('Top 5 Teams with Most Points in F1 History')\nax.invert_yaxis()  # Invert y-axis to show the team with the most points at the top\n\n# Show plot\nplt.tight_layout()\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2024-06-29T05:34:28.229151Z","iopub.execute_input":"2024-06-29T05:34:28.229607Z","iopub.status.idle":"2024-06-29T05:34:29.434731Z","shell.execute_reply.started":"2024-06-29T05:34:28.229564Z","shell.execute_reply":"2024-06-29T05:34:29.433625Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"**Data Preprocessing**\n\n* Drop unnecessary features\n* Handling Missing values\n* Encoding categorical variables\n* Date Components Extraction","metadata":{}},{"cell_type":"code","source":"train_df.replace('\\\\N', pd.NA, inplace=True)","metadata":{"execution":{"iopub.status.busy":"2024-06-29T05:35:38.028619Z","iopub.execute_input":"2024-06-29T05:35:38.029033Z","iopub.status.idle":"2024-06-29T05:36:12.272853Z","shell.execute_reply.started":"2024-06-29T05:35:38.028989Z","shell.execute_reply":"2024-06-29T05:36:12.271799Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_df.isnull().sum()","metadata":{"execution":{"iopub.status.busy":"2024-06-29T05:36:12.274613Z","iopub.execute_input":"2024-06-29T05:36:12.274951Z","iopub.status.idle":"2024-06-29T05:36:22.175119Z","shell.execute_reply.started":"2024-06-29T05:36:12.274921Z","shell.execute_reply":"2024-06-29T05:36:22.173853Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#Dropping the features that containing more missing values and unnecessary features\ntrain_df=train_df.drop(['position_x', 'time_x', 'timetaken_in_millisec', 'fastestLap', 'rank','fastestLapTime', 'max_speed', 'time_y', 'url_x', 'fp1_date', 'fp1_time', 'fp2_date', 'fp2_time', 'fp3_date', 'fp3_time', 'quali_date', 'quali_time', 'sprint_date', 'sprint_time', 'driver_num','driver_code', 'url_y', 'url', 'positionText_y', 'resultId', 'racerId', 'driverRef', 'forename', 'surname'],axis=1)\ntest_df=test_df.drop(['position_x', 'time_x', 'timetaken_in_millisec', 'fastestLap', 'rank','fastestLapTime', 'max_speed', 'time_y', 'url_x', 'fp1_date', 'fp1_time', 'fp2_date', 'fp2_time', 'fp3_date', 'fp3_time', 'quali_date', 'quali_time', 'sprint_date', 'sprint_time', 'driver_num','driver_code', 'url_y', 'url', 'resultId', 'racerId', 'driverRef', 'forename', 'surname'],axis=1)","metadata":{"execution":{"iopub.status.busy":"2024-06-29T01:08:52.060036Z","iopub.execute_input":"2024-06-29T01:08:52.060396Z","iopub.status.idle":"2024-06-29T01:08:53.104293Z","shell.execute_reply.started":"2024-06-29T01:08:52.060367Z","shell.execute_reply":"2024-06-29T01:08:53.102408Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#Handling Missing Values\ntrain_df.replace(['\\\\N'], pd.NA, inplace=True)\ntrain_df.replace(['R', 'N', 'W', 'D', 'F', 'E'], 0, inplace=True)\ntrain_df.dropna(inplace=True)\ntest_df.replace(['\\\\N', 'R', 'N', 'W', 'D', 'F', 'E'], 0, inplace=True)","metadata":{"execution":{"iopub.status.busy":"2024-06-29T01:03:50.517957Z","iopub.execute_input":"2024-06-29T01:03:50.518386Z","iopub.status.idle":"2024-06-29T01:04:20.597230Z","shell.execute_reply.started":"2024-06-29T01:03:50.518353Z","shell.execute_reply":"2024-06-29T01:04:20.595624Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#Encoding categorical variables\nfrom sklearn.preprocessing import LabelEncoder\nlabel_encoder = LabelEncoder()\ntrain_df['grand_prix'] = label_encoder.fit_transform(train_df['grand_prix'])\ntrain_df['nationality'] = label_encoder.fit_transform(train_df['nationality'])\ntrain_df['constructorRef'] = label_encoder.fit_transform(train_df['constructorRef'])\ntrain_df['company'] = label_encoder.fit_transform(train_df['company'])\ntrain_df['nationality_y'] = label_encoder.fit_transform(train_df['nationality_y'])\ntrain_df['status'] = label_encoder.fit_transform(train_df['status'])\n\ntest_df['grand_prix'] = label_encoder.fit_transform(test_df['grand_prix'])\ntest_df['nationality'] = label_encoder.fit_transform(test_df['nationality'])\ntest_df['constructorRef'] = label_encoder.fit_transform(test_df['constructorRef'])\ntest_df['company'] = label_encoder.fit_transform(test_df['company'])\ntest_df['nationality_y'] = label_encoder.fit_transform(test_df['nationality_y'])\ntest_df['status'] = label_encoder.fit_transform(test_df['status'])","metadata":{"execution":{"iopub.status.busy":"2024-06-29T01:04:20.599040Z","iopub.execute_input":"2024-06-29T01:04:20.599417Z","iopub.status.idle":"2024-06-29T01:04:27.411727Z","shell.execute_reply.started":"2024-06-29T01:04:20.599385Z","shell.execute_reply":"2024-06-29T01:04:27.410249Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"**Feature Engineering**","metadata":{}},{"cell_type":"code","source":"#Drivers Age\ntrain_df['dob'] = pd.to_datetime(train_df['dob'])\ntrain_df['date'] = pd.to_datetime(train_df['date'])\ntest_df['dob'] = pd.to_datetime(test_df['dob'])\ntest_df['date'] = pd.to_datetime(test_df['date'])\n\ntrain_df['driver_age'] = train_df['date'].dt.year - train_df['dob'].dt.year\ntest_df['driver_age'] = test_df['date'].dt.year - test_df['dob'].dt.year","metadata":{"execution":{"iopub.status.busy":"2024-06-29T01:04:27.413504Z","iopub.execute_input":"2024-06-29T01:04:27.416422Z","iopub.status.idle":"2024-06-29T01:04:28.961264Z","shell.execute_reply.started":"2024-06-29T01:04:27.416382Z","shell.execute_reply":"2024-06-29T01:04:28.959746Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#Remove dob and Date of the race\ntrain_df=train_df.drop(['dob', 'date'],axis=1)\ntest_df=test_df.drop(['dob', 'date'],axis=1)","metadata":{"execution":{"iopub.status.busy":"2024-06-29T01:04:28.963022Z","iopub.execute_input":"2024-06-29T01:04:28.963409Z","iopub.status.idle":"2024-06-29T01:04:29.375109Z","shell.execute_reply.started":"2024-06-29T01:04:28.963378Z","shell.execute_reply":"2024-06-29T01:04:29.373533Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Change in position\ntrain_df['position_change'] = train_df['grid'] - train_df['positionOrder']\ntest_df['position_change'] = test_df['grid'] - test_df['positionOrder']","metadata":{"execution":{"iopub.status.busy":"2024-06-29T01:04:29.376746Z","iopub.execute_input":"2024-06-29T01:04:29.377156Z","iopub.status.idle":"2024-06-29T01:04:29.397872Z","shell.execute_reply.started":"2024-06-29T01:04:29.377125Z","shell.execute_reply":"2024-06-29T01:04:29.396127Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"**Build Machine Learning Model**","metadata":{}},{"cell_type":"code","source":"train_df.isnull().sum()","metadata":{"execution":{"iopub.status.busy":"2024-06-29T01:04:29.399491Z","iopub.execute_input":"2024-06-29T01:04:29.399898Z","iopub.status.idle":"2024-06-29T01:04:30.147732Z","shell.execute_reply.started":"2024-06-29T01:04:29.399866Z","shell.execute_reply":"2024-06-29T01:04:30.145967Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"X_train=train_df.drop(columns='position',axis=1)\ny_train=train_df['position']","metadata":{"execution":{"iopub.status.busy":"2024-06-29T01:04:30.149295Z","iopub.execute_input":"2024-06-29T01:04:30.149835Z","iopub.status.idle":"2024-06-29T01:04:30.491480Z","shell.execute_reply.started":"2024-06-29T01:04:30.149787Z","shell.execute_reply":"2024-06-29T01:04:30.489855Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from sklearn.ensemble import RandomForestRegressor\nrf = RandomForestRegressor(n_estimators=200, max_depth=10, min_samples_split=5, min_samples_leaf=2, max_features='sqrt', random_state=127)\nrf.fit(X_train,y_train)","metadata":{"execution":{"iopub.status.busy":"2024-06-29T01:04:30.496070Z","iopub.execute_input":"2024-06-29T01:04:30.496561Z","iopub.status.idle":"2024-06-29T01:06:57.339280Z","shell.execute_reply.started":"2024-06-29T01:04:30.496524Z","shell.execute_reply":"2024-06-29T01:06:57.337516Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"predictions = rf.predict(test_df)","metadata":{"execution":{"iopub.status.busy":"2024-06-29T01:06:57.340189Z","iopub.status.idle":"2024-06-29T01:06:57.340638Z","shell.execute_reply.started":"2024-06-29T01:06:57.340411Z","shell.execute_reply":"2024-06-29T01:06:57.340430Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"test_ids = test_df['result_driver_standing']","metadata":{"execution":{"iopub.status.busy":"2024-06-29T01:06:57.342351Z","iopub.status.idle":"2024-06-29T01:06:57.342796Z","shell.execute_reply.started":"2024-06-29T01:06:57.342582Z","shell.execute_reply":"2024-06-29T01:06:57.342601Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"submission_df = pd.DataFrame({'position': predictions , 'result_driver_standing': test_ids})","metadata":{"execution":{"iopub.status.busy":"2024-06-29T01:06:57.344806Z","iopub.status.idle":"2024-06-29T01:06:57.345217Z","shell.execute_reply.started":"2024-06-29T01:06:57.345012Z","shell.execute_reply":"2024-06-29T01:06:57.345039Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"submission_df.to_csv(\"submission.csv\", index=False)","metadata":{"execution":{"iopub.status.busy":"2024-06-29T01:06:57.347722Z","iopub.status.idle":"2024-06-29T01:06:57.348443Z","shell.execute_reply.started":"2024-06-29T01:06:57.348092Z","shell.execute_reply":"2024-06-29T01:06:57.348128Z"},"trusted":true},"execution_count":null,"outputs":[]}]}