diff --git a/submissions_extracted/372/Q3.ipynb b/submissions_extracted/372/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..601c2763eb4096df08731c716223243417d53daf --- /dev/null +++ b/submissions_extracted/372/Q3.ipynb @@ -0,0 +1,220 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "\n", + "\n", + "# Download latest version\n", + "\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q3-exam-data\")\n", + "\n", + "\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "import pandas as pd\n", + "import os\n", + "csv_path = os.path.join(path, \"Q3_data.csv\")\n", + "\n", + "df = pd.read_csv(csv_path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "df.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "df.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "def check_missing_values(df):\n", + " missing_values = df.isnull().sum()\n", + " print(\"Missing Values per Column:\")\n", + " print(missing_values[missing_values > 0])\n", + " if missing_values.any():\n", + " print(\"\\nHandle Missing Values as needed.\")\n", + " else:\n", + " print(\"\\nNo Missing Values Found.\")\n", + "\n", + "check_missing_values(df)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "def check_duplicates(df):\n", + " duplicates = df.duplicated().sum()\n", + " print(f\"Number of Duplicate Samples: {duplicates}\")\n", + " if duplicates > 0:\n", + " print(\"Dropping Duplicates...\")\n", + " df.drop_duplicates(inplace=True)\n", + " print(\"Duplicates Dropped.\")\n", + " else:\n", + " print(\"No Duplicate Samples Found.\")\n", + "\n", + "check_duplicates(df)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "from sklearn.preprocessing import StandardScaler\n", + "\n", + "features = df.columns.drop(\"Target\") # DON'T SCALE THE TARGET\n", + "\n", + "scaler = StandardScaler()\n", + "df[features] = scaler.fit_transform(df[features])\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "X = df.drop(\"target\", axis=1).astype(float)\n", + "y = df[\"target\"].astype(float)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:\n", + "from sklearn.model_selection import StratifiedKFold, train_test_split\n", + "from sklearn.metrics import accuracy_score\n", + "from catboost import CatBoostClassifier\n", + "\n", + "model=CatBoostClassifier(verbose=0, n_estimators=200, max_depth=4)\n", + "n_splits = 5\n", + "skf = StratifiedKFold(n_splits=n_splits, shuffle=True, random_state=42)\n", + "for fold_idx, (train_index, test_index) in enumerate(skf.split(X, y)):\n", + " print(f\"\\nFold {fold_idx + 1}/{n_splits}\")\n", + "#\n", + " # Get the train & test split for this fold\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", + " # Fit the model on train data\n", + " model.fit(X_train, y_train)\n", + "\n", + "# Use the model to predict the test data\n", + " y_pred = model.predict(X_test)\n", + "\n", + "# Calculate evaluation metrics\n", + " accuracy = accuracy_score(y_test, y_pred)\n", + "print(f\"Accuracy: {accuracy}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/373/Q1.ipynb b/submissions_extracted/373/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..09deb24ae8765c4f8b956c5ad64251dc2176ed16 --- /dev/null +++ b/submissions_extracted/373/Q1.ipynb @@ -0,0 +1,346 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import numpy as np\n", + "import pandas as pd\n", + "import matplotlib.pyplot as plt\n", + "import os\n", + "import kagglehub\n", + "import seaborn as sns\n", + "from tqdm import tqdm\n", + "\n", + "from sklearn.model_selection import train_test_split, KFold\n", + "from sklearn.preprocessing import StandardScaler, LabelEncoder\n", + "from sklearn.ensemble import RandomForestRegressor\n", + "from sklearn.metrics import mean_absolute_error, mean_squared_error\n", + "from sklearn.preprocessing import OneHotEncoder\n", + "import warnings\n", + "warnings.filterwarnings('ignore')" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q1-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task1 read data:\n", + "# Load the dataset\n", + "delivery_path = os.path.join(path,'Q1_data.csv')\n", + "df_delivery = pd.read_csv(delivery_path)\n", + "\n", + "print(f\"Dataset shape: {df_delivery.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: using head to show first rows data:\n", + "df_delivery.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: display info to show information of data:\n", + "df_delivery.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: using describe to know the details of data\n", + "df_delivery.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5:\n", + "# delivery_time distribution (target variable)\n", + "plt.figure(figsize=(10, 5))\n", + "plt.hist(df_delivery['Delivery_Time'].dropna(), bins=50, edgecolor='black')\n", + "plt.title('delivery_time Distribution')\n", + "plt.xlabel('delivery_time')\n", + "plt.ylabel('Frequency')\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: drop ID column\n", + "print(f\"Before: {df_delivery.shape}\")\n", + "df_delivery = df_delivery.drop(columns=['Order_ID'])\n", + "print(f\"After dropping Order_ID column: {df_delivery.shape}\")\n", + "\n", + "df_delivery" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: check the missing\n", + "def check_missing_values(df_delivery):\n", + " missing_values = df_delivery.isnull().sum()\n", + " print(\"Missing Values per Column:\")\n", + " print(missing_values[missing_values > 0])\n", + " if missing_values.any():\n", + " print(\"\\nHandle Missing Values as needed.\")\n", + " else:\n", + " print(\"\\nNo Missing Values Found.\")\n", + "\n", + "check_missing_values(df_delivery)\n", + "\n", + "at_cols = ['Weather', 'Traffic_Level', 'Time_of_Day', 'Courier_Experience_yrs', 'Delivery_Time']\n", + "# Drop rows with missing stat values\n", + "df_delivery = df_delivery.dropna(subset=at_cols).copy()\n", + "print(f\"Shape after cleaning: {df_delivery.shape}\")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Dublicate\n", + "def check_duplicates(df_delivery):\n", + " duplicates = df_delivery.duplicated().sum()\n", + " print(f\"Number of Duplicate Samples: {duplicates}\")\n", + " if duplicates > 0:\n", + " print(\"Dropping Duplicates...\")\n", + " df_delivery.drop_duplicates(inplace=True)\n", + " print(\"Duplicates Dropped.\")\n", + " else:\n", + " print(\"No Duplicate Samples Found.\")\n", + "\n", + "check_duplicates(df_delivery)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Do we have categorical columns?\n", + "# encoding\n", + "categorical_cols = df_delivery.select_dtypes(include=[\"object\"]).columns\n", + "for col in categorical_cols:\n", + " print(f\"Encoding column: {col}\")\n", + " le = LabelEncoder()\n", + " df_delivery[col] = le.fit_transform(df_delivery[col])\n", + "df_delivery\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5:\n", + "numerical_cols = df_delivery.select_dtypes(include=[\"int64\", \"float64\"]).columns.drop(\"Delivery_Time\") # DON'T SCALE THE TARGET\n", + "\n", + "scaler = StandardScaler()\n", + "df_delivery[numerical_cols] = scaler.fit_transform(df_delivery[numerical_cols])\n", + "df_delivery.head()\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 6:\n", + "def check_target_imbalance(df_delivery, target_column):\n", + " print(\"Target Distribution:\")\n", + " print(df_delivery[target_column].value_counts(normalize=True))\n", + " sns.countplot(x=df_delivery[target_column])\n", + " plt.title(\"Target Distribution\")\n", + " plt.show()\n", + "\n", + "check_target_imbalance(df_delivery, \"Delivery_Time\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1:\n", + "feature_cols = ['Distance_km',\t'Weather',\t'Traffic_Level',\t'Time_of_Day',\t'Vehicle_Type',\t'Preparation_Time_min',\t'Courier_Experience_yrs']\n", + "X = df_delivery[feature_cols]\n", + "y = df_delivery['Delivery_Time']\n", + "\n", + "# Train-test split (80% train, 20% test)\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n", + "print(f\"Train: {X_train.shape}, Test: {X_test.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "def gradient_descent(X, y, learning_rate, n_iters=500):\n", + " m, n = X.shape # m rows, n columns (dimensions)\n", + " theta = np.zeros(n) # initialize a zeros weight vector with n dimensions\n", + " losses = []\n", + "\n", + " for _ in tqdm(range(n_iters), desc=\"Training Linear Regression\"):\n", + " y_hat = np.dot(X, theta)\n", + " gradient = np.dot(X.T, (y_hat - y)) / m\n", + " theta -= learning_rate * gradient\n", + "\n", + " loss = mean_squared_error(y, y_hat)\n", + " losses.append(loss)\n", + "\n", + " return theta, losses" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "lr_losses = []\n", + "lr_mse = []\n", + "lr_rmse = []\n", + "lr_r2 = []" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:\n", + "#task3\n", + "model = RandomForestRegressor(n_estimators=100, max_depth=20, random_state=42, n_jobs=-1)\n", + "model.fit(X_train, y_train)\n", + "print(\"Model trained!\")\n", + "\n", + "#MSE\n", + "y_pred = model.predict(X_test)\n", + "mae = mean_absolute_error(y_test, y_pred)\n", + "print(f\"MAE: ${mae:,.2f}\")\n", + "\n", + "#\n", + "# K-Fold Cross Validation\n", + "kf = KFold(n_splits=5, shuffle=True, random_state=42)\n", + "\n", + "\n", + "\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "# Feature importance\n", + "feature_importance = pd.DataFrame({\n", + " 'feature': feature_cols,\n", + " 'importance': model.feature_importances_\n", + "}).sort_values('importance', ascending=False)\n", + "\n", + "plt.figure(figsize=(10, 6))\n", + "plt.barh(feature_importance['feature'], feature_importance['importance'])\n", + "plt.xlabel('Importance')\n", + "plt.title('Feature Importance')\n", + "plt.gca().invert_yaxis()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "plt.xlabel(\"Actual Dilvery time (Ground Truth)\")\n", + "plt.ylabel(\"Predicted Dilvery time\")\n", + "plt.title(\"Linear Regression: Predictions vs Ground Truth\")\n", + "plt.grid(True)\n", + "\n", + "plt.tight_layout()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/373/Q2.ipynb b/submissions_extracted/373/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..30ac34bda0135a404ee312ea953c86ad37200088 --- /dev/null +++ b/submissions_extracted/373/Q2.ipynb @@ -0,0 +1,205 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "import pandas as pd\n", + "import torch\n", + "import torch.nn as nn\n", + "from torch.optim import AdamW\n", + "from torchvision.transforms.functional import to_tensor\n", + "from torch.utils.data import DataLoader\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q2-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import os\n", + "import pandas as pd\n", + "import numpy as np\n", + "from PIL import Image\n", + "from sklearn.model_selection import train_test_split\n", + "\n", + "# Load Labels\n", + "labels_df = pd.read_csv(os.path.join(path, \"labels.csv\"))\n", + "img_dir = os.path.join(path, \"images\")\n", + "\n", + "images = []\n", + "ages = []\n", + "\n", + "# Load Images and Resize\n", + "print(\"Loading images...\")\n", + "for index, row in labels_df.iterrows():\n", + " img_name = row.iloc[0]\n", + " age = row.iloc[1]\n", + " img_path = os.path.join(img_dir, img_name)\n", + "\n", + " if os.path.exists(img_path):\n", + " img = Image.open(img_path).convert('RGB')\n", + " img_array = np.array(img) / 255.0 # Normalize pixel values to [0, 1]\n", + " images.append(img_array)\n", + " ages.append(age)\n", + "\n", + "X = np.array(images)\n", + "y = np.array(ages)\n", + "\n", + "# Transpose image dimensions to match PyTorch format (N, C, H, W)\n", + "X = np.transpose(X, (0, 3, 1, 2))\n", + "\n", + "# Split Data\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n", + "\n", + "print(f\"X_train shape: {X_train.shape}\")\n", + "print(f\"X_test shape: {X_test.shape}\")\n", + "print(f\"y_train shape: {y_train.shape}\")\n", + "print(f\"y_test shape: {y_test.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 1. Convert Numpy arrays to PyTorch Tensors\n", + "# Training dataset\n", + "train_dataset = images(root='./datasets', train=True, transform=to_tensor, download=True)\n", + "# Testing dataset\n", + "test_dataset = images(root='./datasets', train=False, transform=to_tensor, download=True)\n", + "\n", + "# Print one sample from the dataset\n", + "sample_image, sample_label = train_dataset[0]\n", + "print(f\"Image shape: {sample_image.shape}\") # (3, 32, 32)\n", + "print(f\"Label: {sample_label}\")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 2. Create TensorDataset objects\n", + "\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 3. Create DataLoaders\n", + "\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 4. Print shape of one batch\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 5. Display sample images\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your model class here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your training loop here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your validation loop here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Define device, model, loss, optimizer:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Start training for 20 epochs:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2 (Bonus): Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/373/Q3.ipynb b/submissions_extracted/373/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..ef986956069dc8b4d5d5eb96091f4b9b6ea032ed --- /dev/null +++ b/submissions_extracted/373/Q3.ipynb @@ -0,0 +1,370 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "import numpy as np\n", + "import pandas as pd\n", + "import matplotlib.pyplot as plt\n", + "import os\n", + "import kagglehub\n", + "import seaborn as sns\n", + "from tqdm import tqdm\n", + "\n", + "from sklearn.model_selection import train_test_split, KFold\n", + "from sklearn.preprocessing import StandardScaler, LabelEncoder\n", + "from sklearn.ensemble import RandomForestRegressor\n", + "from sklearn.metrics import mean_absolute_error, mean_squared_error\n", + "from sklearn.preprocessing import OneHotEncoder\n", + "import warnings\n", + "\n", + "%pip install kagglehub catboost xgboost tqdm imbalanced-learn -q\n", + "warnings.filterwarnings('ignore')\n", + "\n", + "# Download latest version\n", + "\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q3-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "df_path = os.path.join(path,'Q3_data.csv')\n", + "df = pd.read_csv(df_path)\n", + "\n", + "print(f\"Dataset shape: {df.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "df.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "df.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "def check_missing_values(df):\n", + " missing_values = df.isnull().sum()\n", + " print(\"Missing Values per Column:\")\n", + " print(missing_values[missing_values > 0])\n", + " if missing_values.any():\n", + " print(\"\\nHandle Missing Values as needed.\")\n", + " else:\n", + " print(\"\\nNo Missing Values Found.\")\n", + "\n", + "check_missing_values(df)\n", + "\n", + "at_cols = ['P_2',\t'D_39',\t'B_1',\t'B_2',\t'R_1',\t'S_3',\t'D_41',\t'B_3',\t'D_42',\t'D_43','D_137',\t'D_138',\t'D_139',\t'D_140',\t'D_141',\t'D_142',\t'D_143',\t'D_144',\t'D_145',\t'Target']\n", + "\n", + "df[at_cols] = df[at_cols].fillna('none')\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "def check_duplicates(df):\n", + " duplicates = df.duplicated().sum()\n", + " print(f\"Number of Duplicate Samples: {duplicates}\")\n", + " if duplicates > 0:\n", + " print(\"Dropping Duplicates...\")\n", + " df.drop_duplicates(inplace=True)\n", + " print(\"Duplicates Dropped.\")\n", + " else:\n", + " print(\"No Duplicate Samples Found.\")\n", + "\n", + "check_duplicates(df)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "categorical_cols = df.select_dtypes(include=[\"object\"]).columns\n", + "\n", + "print(\"Categorical Columns:\", list(categorical_cols))\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "numerical_cols = df.select_dtypes(include=[\"int64\", \"float64\"]).columns.drop(\"Target\") # DON'T SCALE THE TARGET\n", + "\n", + "scaler = StandardScaler()\n", + "df[numerical_cols] = scaler.fit_transform(df[numerical_cols])\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "def check_target_imbalance(df, target_column):\n", + " print(\"Target Distribution:\")\n", + " print(df[target_column].value_counts(normalize=True))\n", + " sns.countplot(x=df[target_column])\n", + " plt.title(\"Target Distribution\")\n", + " plt.show()\n", + "\n", + "check_target_imbalance(df, \"Target\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "feature_cols = ['P_2',\t'D_39',\t'B_1',\t'B_2',\t'R_1',\t'S_3',\t'D_41',\t'B_3',\t'D_42',\t'D_43','D_137',\t'D_138',\t'D_139',\t'D_140',\t'D_141',\t'D_142',\t'D_143',\t'D_144',\t'D_145']\n", + "X = df[feature_cols]\n", + "y = df['Target']\n", + "\n", + "# Train-test split (80% train, 20% test)\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n", + "print(f\"Train: {X_train.shape}, Test: {X_test.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "from sklearn.model_selection import StratifiedKFold\n", + "from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "def gradient_descent(X, y, learning_rate, n_iters=500):\n", + " m, n = X.shape # m rows, n columns (dimensions)\n", + " theta = np.zeros(n) # initialize a zeros weight vector with n dimensions\n", + " losses = []\n", + "\n", + " for _ in tqdm(range(n_iters), desc=\"Training Linear Regression\"):\n", + " y_hat = np.dot(X, theta)\n", + " gradient = np.dot(X.T, (y_hat - y)) / m\n", + " theta -= learning_rate * gradient\n", + "\n", + " loss = mean_squared_error(y, y_hat)\n", + " losses.append(loss)\n", + "\n", + " return theta, losses" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "from sklearn.linear_model import LogisticRegression\n", + "from sklearn.neighbors import KNeighborsClassifier\n", + "from sklearn.svm import SVC\n", + "from sklearn.tree import DecisionTreeClassifier\n", + "from sklearn.ensemble import RandomForestClassifier\n", + "from xgboost import XGBClassifier\n", + "from catboost import CatBoostClassifier" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "models = {\n", + " \"LR\": LogisticRegression(\n", + " max_iter=1000\n", + " ),\n", + " \"KNN\": KNeighborsClassifier(\n", + " n_neighbors=3,\n", + " ),\n", + " \"SVM\": SVC(\n", + " kernel='rbf',\n", + " C=1.0\n", + " ),\n", + " \"Decision Tree\": DecisionTreeClassifier(\n", + " max_depth=16\n", + " ),\n", + " \"Random Forest\": RandomForestClassifier(\n", + " n_estimators=200,\n", + " max_depth=10\n", + " ),\n", + " \"XGBoost\": XGBClassifier(\n", + " verbosity=0,\n", + " n_estimators=280,\n", + " max_depth=10,\n", + " ),\n", + " \"CatBoost\": CatBoostClassifier(\n", + " verbose=0,\n", + " n_estimators=200,\n", + " max_depth=4\n", + " )\n", + "}" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:\n", + "n_splits = 5 # K=5 Folds\n", + "\n", + "# Stratified 5-Fold Cross-Validation, shuffled\n", + "skf = StratifiedKFold(n_splits=n_splits, shuffle=True, random_state=42)\n", + "\n", + "lr_losses = []\n", + "lr_accuracy = []\n", + "lr_precision = []\n", + "lr_recall = []\n", + "lr_f1 = []\n", + "\n", + "model = CatBoostClassifier(n_estimators=100, max_depth=20, random_state=42, n_jobs=-1)\n", + "model.fit(X_train, y_train)\n", + "print(\"Model trained!\")\n", + "\n", + "for fold_idx, (train_index, test_index) in enumerate(skf.split(X, y)):\n", + " print(f\"\\nFold {fold_idx + 1}/{n_splits}\")\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", + " # Train\n", + " theta, losses = gradient_descent(X_train, y_train, learning_rate=0.5, n_iters=500)\n", + "\n", + " # Validate\n", + " y_pred_proba = sigmoid(np.dot(X_test, theta))\n", + " y_pred = (y_pred_proba >= 0.5).astype(int)\n", + "\n", + " # Calculate evaluation metrics\n", + " accuracy = accuracy_score(y_test, y_pred)\n", + " precision = precision_score(y_test, y_pred, zero_division=0)\n", + " recall = recall_score(y_test, y_pred, zero_division=0)\n", + " f1 = f1_score(y_test, y_pred, zero_division=0)\n", + "\n", + " # Store results\n", + " lr_losses.append(losses)\n", + " lr_accuracy.append(accuracy)\n", + " lr_precision.append(precision)\n", + " lr_recall.append(recall)\n", + " lr_f1.append(f1)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "feature_importance = pd.DataFrame({\n", + " 'feature': feature_cols,\n", + " 'importance': model.feature_importances_\n", + "}).sort_values('importance', ascending=False)\n", + "\n", + "plt.figure(figsize=(10, 6))\n", + "plt.barh(feature_importance['feature'], feature_importance['importance'])\n", + "plt.xlabel('Importance')\n", + "plt.title('Feature Importance')\n", + "plt.gca().invert_yaxis()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "plt.xlabel(\"Actual golden feature (Ground Truth)\")\n", + "plt.ylabel(\"Predicted golden feature\")\n", + "plt.title(\"Linear Regression: Predictions vs Ground Truth\")\n", + "plt.grid(True)\n", + "\n", + "plt.tight_layout()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/374/Q1.ipynb b/submissions_extracted/374/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..62da2d29b559e1b5cd90e7ef7df3c9e4b4619033 --- /dev/null +++ b/submissions_extracted/374/Q1.ipynb @@ -0,0 +1,389 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q1-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import pandas as pd\n", + "import numpy as np\n", + "import matplotlib.pyplot as plt\n", + "import seaborn as sns\n", + "import os" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "csv_path = os.path.join(path, \"Q1_data.csv\")\n", + "\n", + "df = pd.read_csv(csv_path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "df.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "df.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "plt.figure(figsize=(10, 5))\n", + "plt.hist(df['Delivery_Time'].dropna(), bins=20, edgecolor='black')\n", + "plt.title('distribution of Delivery_Time')\n", + "plt.xlabel('Delivery_Time')\n", + "plt.ylabel('Frequency')\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "df = df.drop(['Order_ID'], axis=1)\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "def check_missing_values(df):\n", + " missing_values = df.isnull().sum()\n", + " print(\"Missing Values per Column:\")\n", + " print(missing_values[missing_values > 0])\n", + " if missing_values.any():\n", + " print(\"\\nHandle Missing Values as needed.\")\n", + " else:\n", + " print(\"\\nNo Missing Values Found.\")\n", + "\n", + "check_missing_values(df)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "categorical_column = df.select_dtypes(include='object').columns\n", + "for col in categorical_column:\n", + " df[col] = df[col].fillna('Unknown')" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "check_missing_values(df)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "df[\"Courier_Experience_yrs\"] = df['Courier_Experience_yrs'].fillna(df['Courier_Experience_yrs'].mode()[0])" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "df[\"Delivery_Time\"] = df['Delivery_Time'].fillna(df['Delivery_Time'].mode()[0])" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "check_missing_values(df)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "def check_duplicates(df):\n", + " duplicates = df.duplicated().sum()\n", + " print(f\"Number of Duplicate Samples: {duplicates}\")\n", + " if duplicates > 0:\n", + " print(\"Dropping Duplicates...\")\n", + " df.drop_duplicates(inplace=True)\n", + " print(\"Duplicates Dropped.\")\n", + " else:\n", + " print(\"No Duplicate Samples Found.\")\n", + "\n", + "check_duplicates(df)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# check again\n", + "check_duplicates(df)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "from sklearn.preprocessing import OneHotEncoder\n", + "\n", + "categorical_cols = df.select_dtypes(include=['object']).columns\n", + "\n", + "for col in categorical_cols:\n", + " print(f\"Encoding column: {col}\")\n", + " ohe = OneHotEncoder(sparse_output=False)\n", + "\n", + " df = df.join(\n", + " pd.DataFrame(\n", + " ohe.fit_transform(df[[col]]),\n", + " columns=ohe.get_feature_names_out([col]),\n", + " index=df.index\n", + " )\n", + " ).drop(columns=[col])\n", + "\n", + "df.head()\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "from sklearn.preprocessing import StandardScaler\n", + "\n", + "numerical_cols = df.select_dtypes(include=[\"int64\", \"float64\"]).columns.drop(\"Delivery_Time\")\n", + "\n", + "scaler = StandardScaler()\n", + "df[numerical_cols] = scaler.fit_transform(df[numerical_cols])\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 6: Write your code here:\n", + "df[\"Delivery_Time\"].value_counts()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "## The target is imbalanced" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "X = df.drop(\"Delivery_Time\", axis=1).astype(float)\n", + "y = df['Delivery_Time'].astype(float)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "feature_cols = [\"Distance_km\", \"Weather\", \"Traffic_Level\", \"Time_of_Day\", \"Vehicle_Type\", \"Preparation_Time_min\",\n", + " \"Courier_Experience_yrs\", \"Delivery_Time\"\n", + " ]" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:\n", + "\n", + "# we will use StratifiedKFold because the imbalance\n", + "from sklearn.model_selection import StratifiedKFold\n", + "from sklearn.ensemble import RandomForestRegressor\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "from sklearn.metrics import mean_absolute_error as sklearn_mae\n", + "\n", + "skf = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)\n", + "\n", + "mae_scores = []\n", + "print(\"Stratified K-Fold Cross Validation\\n\" + \"-\"*40)\n", + "\n", + "for fold, (train_idx, test_idx) in enumerate(skf.split(X, y), start=1):\n", + " # indexing for each fold\n", + " X_train, X_test = X.iloc[train_idx], X.iloc[test_idx]\n", + " y_train, y_test = y.iloc[train_idx], y.iloc[test_idx]\n", + "\n", + " print(f\"Fold {fold}\")\n", + " print(\" X_train shape:\", X_train.shape)\n", + " print(\" X_test shape :\", X_test.shape)\n", + " print(\" y_train shape:\", y_train.shape)\n", + " print(\" y_test shape :\", y_test.shape)\n", + "\n", + "\n", + " model = RandomForestRegressor(n_estimators=200)\n", + "\n", + " model.fit(X_train, y_train)\n", + "\n", + " y_pred = model.predict(X_test)\n", + "\n", + " mae_scores.append(sklearn_mae(y_test, y_pred))\n", + "\n", + "mae_scores = np.array(mae_scores)\n", + "\n", + "print(f\"5-Fold Results:\")\n", + "print(f\"MAE: {mae_scores.mean():,.2f}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "feature_importance = pd.DataFrame({\n", + " 'feature': X.columns,\n", + " 'importance': model.feature_importances_\n", + "}).sort_values('importance', ascending=False)\n", + "\n", + "plt.figure(figsize=(10, 6))\n", + "plt.barh(feature_importance['feature'], feature_importance['importance'])\n", + "plt.xlabel('Importance')\n", + "plt.title('Feature Importance')\n", + "plt.gca().invert_yaxis()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "plt.figure(figsize=(6, 4))\n", + "plt.scatter(y_test, y_pred, alpha=0.7)\n", + "plt.plot([min(y_test), max(y_test)], [min(y_test), max(y_test)], 'r--', linewidth=2)\n", + "plt.xlabel(\"Actual y_test (Ground Truth)\")\n", + "plt.ylabel(\"Predicted y_pred \")\n", + "plt.title(\"Predictions vs. Ground Truth\")\n", + "plt.grid(True)\n", + "\n", + "plt.tight_layout()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/374/Q2.ipynb b/submissions_extracted/374/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..ae5ab65e5338b638ce8fb9a30487ec9fb93ed9df --- /dev/null +++ b/submissions_extracted/374/Q2.ipynb @@ -0,0 +1,448 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q2-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import os\n", + "import pandas as pd\n", + "import numpy as np\n", + "from PIL import Image\n", + "from sklearn.model_selection import train_test_split\n", + "\n", + "# Load Labels\n", + "labels_df = pd.read_csv(os.path.join(path, \"labels.csv\"))\n", + "img_dir = os.path.join(path, \"images\")\n", + "\n", + "images = []\n", + "ages = []\n", + "\n", + "# Load Images and Resize\n", + "print(\"Loading images...\")\n", + "for index, row in labels_df.iterrows():\n", + " img_name = row.iloc[0]\n", + " age = row.iloc[1]\n", + " img_path = os.path.join(img_dir, img_name)\n", + "\n", + " if os.path.exists(img_path):\n", + " img = Image.open(img_path).convert('RGB')\n", + " img_array = np.array(img) / 255.0 # Normalize pixel values to [0, 1]\n", + " images.append(img_array)\n", + " ages.append(age)\n", + "\n", + "X = np.array(images)\n", + "y = np.array(ages)\n", + "\n", + "# Transpose image dimensions to match PyTorch format (N, C, H, W)\n", + "X = np.transpose(X, (0, 3, 1, 2))\n", + "\n", + "# Split Data\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n", + "\n", + "print(f\"X_train shape: {X_train.shape}\")\n", + "print(f\"X_test shape: {X_test.shape}\")\n", + "print(f\"y_train shape: {y_train.shape}\")\n", + "print(f\"y_test shape: {y_test.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 1. Convert Numpy arrays to PyTorch Tensors\n", + "import torch\n", + "import torch.nn as nn\n", + "\n", + "X_train = torch.tensor(X_train, dtype=torch.float32)\n", + "X_test = torch.tensor(X_test, dtype=torch.float32)\n", + "y_train = torch.tensor(y_train, dtype=torch.float32)\n", + "y_test = torch.tensor(y_test, dtype=torch.float32)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 2. Create TensorDataset objects\n", + "from torch.utils.data import TensorDataset\n", + "from torch.utils.data import DataLoader\n", + "\n", + "train_dataset = TensorDataset(X_train, y_train)\n", + "test_dataset = TensorDataset(X_test, y_test)\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 3. Create DataLoaders\n", + "from torch.utils.data import DataLoader\n", + "\n", + "# DataLoader for training data\n", + "train_loader = DataLoader(\n", + " train_dataset,\n", + " batch_size=32,\n", + " shuffle=True,\n", + " num_workers=2\n", + ")\n", + "# DataLoader for test/validation data\n", + "test_loader = DataLoader(\n", + " test_dataset,\n", + " batch_size=32,\n", + " shuffle=False,\n", + " num_workers=2\n", + ")\n", + "\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 4. Print shape of one batch\n", + "\n", + "X_batch, y_batch = next(iter(train_loader))\n", + "print(f\"Training batch input shape: {X_batch.shape}\")\n", + "print(f\"Training batch labels shape: {y_batch.shape}\")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 5. Display sample images\n", + "\n", + "sample_image, sample_label = train_dataset[0]\n", + "print(f\"Image shape: {sample_image.shape}\")\n", + "print(f\"Label: {sample_label}\")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import matplotlib.pyplot as plt\n", + "images, labels = next(iter(train_loader))\n", + "\n", + "# Display the first 5 images in the batch\n", + "plt.figure(figsize=(8, 4))\n", + "\n", + "for i in range(5):\n", + " plt.subplot(2, 3, i + 1)\n", + " plt.imshow(images[i].squeeze(), cmap='gray')\n", + " plt.title(f\"Label: {labels[i].item()}\")\n", + " plt.axis('off')\n", + "\n", + "plt.tight_layout()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your model class here:\n", + "class NN3Layer(nn.Module):\n", + "\n", + " def __init__(self, input_dim, hidden_dim, output_dim):\n", + " super(NN3Layer, self).__init__()\n", + "\n", + " # First linear layer: input features -> hidden layer\n", + " self.layer1 = nn.Linear(input_dim, hidden_dim)\n", + "\n", + " # Second linear layer: hidden layer -> hidden layer\n", + " self.layer2 = nn.Linear(hidden_dim, hidden_dim)\n", + "\n", + " # 3id linear layer: hidden layer -> hidden layer\n", + " self.layer2 = nn.Linear(hidden_dim, hidden_dim)\n", + "\n", + " # Output layer: hidden layer -> number of classes (logits)\n", + " self.layer3 = nn.Linear(hidden_dim, output_dim)\n", + "\n", + " # ReLU activation for non-linearity\n", + " self.relu = nn.ReLU()\n", + "\n", + " # Defines how input data flows through the network\n", + " def forward(self, x):\n", + " # First hidden layer\n", + " z1 = self.layer1(x)\n", + " a1 = self.relu(z1)\n", + "\n", + " # Second hidden layer\n", + " z2 = self.layer2(a1)\n", + " a2 = self.relu(z2)\n", + "\n", + " # 3id hidden layer\n", + " z3 = self.layer2(a2)\n", + " a3 = self.relu(z3)\n", + "\n", + " # Output layer\n", + " z4 = self.layer3(a3)\n", + "\n", + " return z4" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your training loop here:\n", + "def train_one_epoch(model, optimizer, criterion, train_loader, device):\n", + " # Set the model to training mode\n", + " model.train()\n", + "\n", + " running_loss = 0.0\n", + "\n", + " for X_batch, y_batch in train_loader:\n", + "\n", + " # Reshape square images into flattened vectors\n", + " # (Note: Without changing the batch dimension!)\n", + " X_batch = X_batch.view(X_batch.size(0), -1)\n", + "\n", + "\n", + " y_batch = y_batch.view(-1, 1).to(device) # shape: (batch_size, 1)\n", + "\n", + "\n", + " # Move batch to the selected device\n", + " X_batch = X_batch.to(device)\n", + " y_batch = y_batch.to(device)\n", + "\n", + " # Forward pass\n", + " outputs = model(X_batch) # shape: (batch_size, 1)\n", + " outputs = torch.tensor(outputs, dtype=torch.long)\n", + " loss = criterion(outputs, y_batch)\n", + "\n", + " # Backward pass & optimization\n", + " optimizer.zero_grad() # Clear previous gradients\n", + " loss.backward() # Compute gradients\n", + " optimizer.step() # Update model parameters\n", + "\n", + " running_loss += loss.item()\n", + "\n", + " # Average loss over all batches\n", + " avg_loss = running_loss / len(train_loader)\n", + "\n", + " return avg_loss" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your validation loop here:\n", + "import torch.nn.functional as F\n", + "\n", + "def validate(model, criterion, test_loader, device):\n", + " # Set the model to evaluation mode\n", + " model.eval()\n", + "\n", + " running_loss = 0.0\n", + " correct = 0\n", + " total = 0\n", + "\n", + " with torch.no_grad():\n", + " for X_batch, y_batch in test_loader:\n", + "\n", + " # Reshape square images into flattened vectors\n", + " # (Note: Without changing the batch dimension!)\n", + " X_batch = X_batch.view(X_batch.size(0), -1)\n", + "\n", + " # Move batch to the selected device\n", + " X_batch = X_batch.to(device)\n", + " y_batch = y_batch.to(device)\n", + "\n", + "\n", + " # Forward pass\n", + " outputs = model(X_batch) # shape: (batch_size, 10)\n", + " loss = criterion(outputs, y_batch)\n", + " running_loss += loss.item()\n", + "\n", + " # Apply Softmax to get probabilities\n", + " probabilities = F.softmax(outputs, dim=1)\n", + "\n", + " # Multiclass predictions\n", + " predicted = torch.argmax(probabilities, dim=1)\n", + "\n", + " # Accuracy calculation\n", + " correct += (predicted == y_batch).sum().item()\n", + " total += y_batch.size(0)\n", + "\n", + " avg_loss = running_loss / len(test_loader)\n", + " accuracy = correct / total\n", + "\n", + " return avg_loss, accuracy" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Define device, model, loss, optimizer:\n", + "from torch.optim import Adam\n", + "\n", + "device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n", + "\n", + "# Model parameters\n", + "input_dim = 36 * 36 *3\n", + "hidden_dim = 10\n", + "output_dim = 1 # the probability of the face age\n", + "\n", + "# Instantiate model\n", + "model = NN3Layer(input_dim, hidden_dim, output_dim).to(device)\n", + "\n", + "# Print the model architecture\n", + "print(\"Model Architecture:\\n\")\n", + "print(model)\n", + "\n", + "# Calculate the total number of trainable parameters\n", + "total_params = sum(p.numel() for p in model.parameters() if p.requires_grad)\n", + "print(f\"\\nTotal trainable parameters: {total_params}\")\n", + "\n", + "\n", + "num_epochs = 20\n", + "learning_rate = 0.001\n", + "\n", + "# Define criterion (loss function) - using CrossEntropyLoss as model now outputs logits\n", + "criterion = nn.CrossEntropyLoss()\n", + "# Define optimizer\n", + "optimizer = Adam(model.parameters(), learning_rate)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Start training for 20 epochs:\n", + "\n", + "train_losses = []\n", + "val_losses = []\n", + "val_accuracies = []\n", + "\n", + "print('Starting Training...')\n", + "for epoch in range(num_epochs):\n", + " # Train one epoch\n", + " train_loss = train_one_epoch(model, optimizer, criterion, train_loader, device)\n", + "\n", + " # Validate\n", + " val_loss, val_accuracy = validate(model, criterion, test_loader, device)\n", + "\n", + " train_losses.append(train_loss)\n", + " val_losses.append(val_loss)\n", + " val_accuracies.append(val_accuracy)\n", + "\n", + " print(f'Epoch [{epoch+1}/{num_epochs}], Train Loss: {train_loss:.4f}, Val Loss: {val_loss:.4f}, Val Accuracy: {val_accuracy:.4f}')\n", + "\n", + "print('Training Complete!')" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "# Plotting results\n", + "plt.figure(figsize=(7, 5))\n", + "\n", + "plt.plot(train_losses, label='Train Loss')\n", + "plt.plot(val_losses, label='Validation Loss')\n", + "plt.title('Loss over Epochs')\n", + "plt.xlabel('Epoch')\n", + "plt.ylabel('Loss (MSE)')\n", + "plt.legend()\n", + "\n", + "plt.tight_layout()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2 (Bonus): Write your code here:\n", + "# Set model to evaluation mode\n", + "model.eval()\n", + "# Get one batch from the test DataLoader\n", + "images, labels = next(iter(test_loader))\n", + "# Move images to device\n", + "images = images.to(device)\n", + "labels = labels.to(device)\n", + "\n", + "with torch.no_grad():\n", + " # Flatten images before passing to the model\n", + " outputs = model(images.view(images.size(0), -1))\n", + " predictions = torch.argmax(outputs, dim=1)\n", + "\n", + "# Move tensors back to CPU for plotting\n", + "images = images.cpu()\n", + "labels = labels.cpu()\n", + "predictions = predictions.cpu()\n", + "\n", + "# Plot first 5 predictions\n", + "plt.figure(figsize=(8, 4))\n", + "for i in range(5):\n", + " plt.subplot(2, 3, i + 1)\n", + " plt.imshow(images[i].squeeze(), cmap='gray')\n", + " plt.title(f\"True: {labels[i]} | Pred: {predictions[i]}\")\n", + " plt.axis('off')\n", + "\n", + "plt.tight_layout()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/374/Q3.ipynb b/submissions_extracted/374/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..1021a6fefc34539dc8dcb0a949a4e6cb9aaa17fe --- /dev/null +++ b/submissions_extracted/374/Q3.ipynb @@ -0,0 +1,286 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "\n", + "\n", + "# Download latest version\n", + "\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q3-exam-data\")\n", + "\n", + "\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "import pandas as pd\n", + "import numpy as np\n", + "import matplotlib.pyplot as plt\n", + "import seaborn as sns\n", + "import os\n", + "\n", + "csv_path = os.path.join(path, \"Q3_data.csv\")\n", + "\n", + "df = pd.read_csv(csv_path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "df.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "df.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "def check_missing_values(df):\n", + " missing_values = df.isnull().sum()\n", + " print(\"Missing Values per Column:\")\n", + " print(missing_values[missing_values > 0])\n", + " if missing_values.any():\n", + " print(\"\\nHandle Missing Values as needed.\")\n", + " else:\n", + " print(\"\\nNo Missing Values Found.\")\n", + "\n", + "check_missing_values(df)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "nums_column = df.select_dtypes(include=[\"int64\", \"float64\"]).columns\n", + "for col in nums_column:\n", + " df[col] = df[col].fillna(df[col].mode()[0])" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "check_missing_values(df)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "def check_duplicates(df):\n", + " duplicates = df.duplicated().sum()\n", + " print(f\"Number of Duplicate Samples: {duplicates}\")\n", + " if duplicates > 0:\n", + " print(\"Dropping Duplicates...\")\n", + " df.drop_duplicates(inplace=True)\n", + " print(\"Duplicates Dropped.\")\n", + " else:\n", + " print(\"No Duplicate Samples Found.\")\n", + "\n", + "check_duplicates(df)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "categorical_cols = df.select_dtypes(include=[\"object\"]).columns\n", + "\n", + "print(\"Categorical Columns:\", list(categorical_cols))" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "from sklearn.preprocessing import StandardScaler\n", + "numerical_cols = df.select_dtypes(include=[\"int64\", \"float64\"]).columns.drop(\"Target\")\n", + "\n", + "scaler = StandardScaler()\n", + "df[numerical_cols] = scaler.fit_transform(df[numerical_cols])\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "df[\"Target\"].value_counts()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "## The target is imbalanced" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "%pip install kagglehub catboost xgboost tqdm -q" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "X = df.drop(\"Target\", axis=1).astype(float)\n", + "y = df['Target'].astype(float)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:\n", + "\n", + "# we will use StratifiedKFold because the imbalance\n", + "from sklearn.model_selection import StratifiedKFold\n", + "from catboost import CatBoostRegressor\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "from sklearn.metrics import mean_absolute_error as sklearn_mae\n", + "\n", + "skf = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)\n", + "\n", + "mae_scores = []\n", + "print(\"Stratified K-Fold Cross Validation\\n\" + \"-\"*40)\n", + "\n", + "for fold, (train_idx, test_idx) in enumerate(skf.split(X, y), start=1):\n", + " # indexing for each fold\n", + " X_train, X_test = X.iloc[train_idx], X.iloc[test_idx]\n", + " y_train, y_test = y.iloc[train_idx], y.iloc[test_idx]\n", + "\n", + " print(f\"Fold {fold}\")\n", + " print(\" X_train shape:\", X_train.shape)\n", + " print(\" X_test shape :\", X_test.shape)\n", + " print(\" y_train shape:\", y_train.shape)\n", + " print(\" y_test shape :\", y_test.shape)\n", + "\n", + "\n", + " model = CatBoostRegressor(verbose=0)\n", + "\n", + " model.fit(X_train, y_train)\n", + "\n", + " y_pred = model.predict(X_test)\n", + "\n", + " mae_scores.append(sklearn_mae(y_test, y_pred))\n", + "\n", + "mae_scores = np.array(mae_scores)\n", + "\n", + "print(f\"5-Fold Results:\")\n", + "print(f\"MAE: {mae_scores.mean():,.2f}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/375/Q1.ipynb b/submissions_extracted/375/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..93177f43117e6af118f49771369e7e140ab9c10f --- /dev/null +++ b/submissions_extracted/375/Q1.ipynb @@ -0,0 +1,315 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q1-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)\n", + "\n", + "import numpy as np\n", + "import pandas as pd\n", + "import matplotlib.pyplot as plt\n", + "import os\n", + "import kagglehub\n", + "\n", + "from sklearn.model_selection import train_test_split, KFold\n", + "from sklearn.preprocessing import StandardScaler, LabelEncoder\n", + "from sklearn.ensemble import RandomForestRegressor\n", + "from sklearn.metrics import mean_absolute_error, mean_squared_error\n", + "\n", + "import warnings\n", + "warnings.filterwarnings('ignore')\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "Q1_path = os.path.join(path, 'Q1_data.csv')\n", + "df = pd.read_csv(Q1_path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "df.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "df.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "plt.figure(figsize=(10, 5))\n", + "plt.hist(df['Delivery_Time'].dropna(), bins=50, edgecolor='black')\n", + "plt.title('Price Distribution')\n", + "plt.xlabel('Price')\n", + "plt.ylabel('Frequency')\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "df.drop(columns=['Order_ID'])" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "def check_missing_values(df):\n", + " missing_values = df.isnull().sum()\n", + " print(\"Missing Values per Column:\")\n", + " print(missing_values[missing_values > 0])\n", + " if missing_values.any():\n", + " print(\"\\nHandle Missing Values as needed.\")\n", + " else:\n", + " print(\"\\nNo Missing Values Found.\")\n", + "\n", + "check_missing_values(df)\n", + "\n", + "\n", + "#drop rows with missing value\n", + "\n", + "df= df.dropna(subset=['Delivery_Time','Weather','Traffic_Level','Time_of_Day','Courier_Experience_yrs'])\n", + "print(\"Handling...\")\n", + "\n", + "check_missing_values(df)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "def check_duplicates(df):\n", + " duplicates = df.duplicated().sum()\n", + " print(f\"Number of Duplicate Samples: {duplicates}\")\n", + " if duplicates > 0:\n", + " print(\"Dropping Duplicates...\")\n", + " df.drop_duplicates(inplace=True)\n", + " print(\"Duplicates Dropped.\")\n", + " else:\n", + " print(\"No Duplicate Samples Found.\")\n", + "\n", + "check_duplicates(df)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "\n", + "categorical_cols = df.select_dtypes(include=[\"object\"]).columns\n", + "\n", + "from sklearn.preprocessing import LabelEncoder\n", + "\n", + "categorical_cols = df.select_dtypes(include=[\"object\"]).columns\n", + "for col in categorical_cols:\n", + " print(f\"Encoding column: {col}\")\n", + " le = LabelEncoder()\n", + " df[col] = le.fit_transform(df[col])\n", + "df" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "from sklearn.preprocessing import StandardScaler\n", + "\n", + "features = df.columns.drop(\"Delivery_Time\") # DON'T SCALE THE TARGET\n", + "\n", + "scaler = StandardScaler()\n", + "df[features] = scaler.fit_transform(df[features])\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 6: Write your code here:\n", + "# Task 5: Write your code here:\n", + "plt.figure(figsize=(10, 5))\n", + "plt.hist(df['Delivery_Time'].dropna(), bins=50, edgecolor='black')\n", + "plt.title('Price Distribution')\n", + "plt.xlabel('Price')\n", + "plt.ylabel('Frequency')\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "X = df.drop(\"Delivery_Time\", axis=1).astype(float)\n", + "y = df['Delivery_Time'].astype(float)\n", + "X.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:\n", + "kf = KFold(n_splits=5, shuffle=True, random_state=42)\n", + "\n", + "X_train, X_test, y_train, y_test = train_test_split(\n", + " X, y,\n", + " test_size=0.2, # 20% for test, remaining 80% for train\n", + " random_state=42, # reproducible output\n", + " shuffle=True,) # representative splits\n", + "\n", + "kf = KFold(n_splits=5, shuffle=True, random_state=42)\n", + "\n", + "# Iterate through folds\n", + "for fold, (train_idx, test_idx) in enumerate(kf.split(X), start=1):\n", + " # indexing for each fold\n", + " X_train, X_test = X.iloc[train_idx], X.iloc[test_idx]\n", + " y_train, y_test = y.iloc[train_idx], y.iloc[test_idx]\n", + " # print shapes\n", + " print(f\"Fold {fold}\")\n", + " print(\" X_train shape:\", X_train.shape)\n", + " print(\" X_test shape :\", X_test.shape)\n", + " print(\" y_train shape:\", y_train.shape)\n", + " print(\" y_test shape :\", y_test.shape)\n", + " print(\"-\" * 30)\n", + "\n", + "model = RandomForestRegressor(n_estimators=200)\n", + "\n", + "mse=[]\n", + "\n", + "for fold_idx, (train_index, test_index) in enumerate(kf.split(X, y)):\n", + " print(f\"\\nFold {fold_idx + 1}/{5}\")\n", + "\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", + " mseval= mean_squared_error(y_test, y_pred)\n", + " print(mseval)\n", + " msev = mse.append(mseval)\n", + "\n", + "\n", + "\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "lr_model = model\n", + "# For multi-class, we can take the mean of the absolute coefficients across classes\n", + "feature_importances_lr = pd.Series(np.mean(np.abs(lr_model.coef_), axis=0), index=X.columns)\n", + "\n", + "# Extract sorted features and their coefficients\n", + "feature_importances_lr = feature_importances_lr.sort_values(ascending=False)\n", + "\n", + "# Plot feature importances\n", + "plt.figure(figsize=(10, 6))\n", + "sns.barplot(x=feature_importances_lr.values, y=feature_importances_lr.index)\n", + "plt.title('Logistic Regression Feature Importances (Absolute Mean Coefficients)')\n", + "plt.xlabel('Absolute Mean Coefficient Value')\n", + "plt.ylabel('Features')\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/375/Q2.ipynb b/submissions_extracted/375/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..1d6394d2dd3e4201ce9b4d6843bb3bd3b8b5e4d9 --- /dev/null +++ b/submissions_extracted/375/Q2.ipynb @@ -0,0 +1,369 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q2-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import os\n", + "import pandas as pd\n", + "import numpy as np\n", + "from PIL import Image\n", + "from sklearn.model_selection import train_test_split\n", + "import torch\n", + "import torch.nn as nn\n", + "from torchvision.datasets import MNIST\n", + "from torch.utils.data import DataLoader\n", + "from torch.optim import Adam\n", + "from torchvision.transforms.functional import to_tensor\n", + "import torch.nn.functional as F\n", + "import matplotlib.pyplot as plt\n", + "\n", + "# Load Labels\n", + "labels_df = pd.read_csv(os.path.join(path, \"labels.csv\"))\n", + "img_dir = os.path.join(path, \"images\")\n", + "\n", + "images = []\n", + "ages = []\n", + "\n", + "# Load Images and Resize\n", + "print(\"Loading images...\")\n", + "for index, row in labels_df.iterrows():\n", + " img_name = row.iloc[0]\n", + " age = row.iloc[1]\n", + " img_path = os.path.join(img_dir, img_name)\n", + "\n", + " if os.path.exists(img_path):\n", + " img = Image.open(img_path).convert('RGB')\n", + " img_array = np.array(img) / 255.0 # Normalize pixel values to [0, 1]\n", + " images.append(img_array)\n", + " ages.append(age)\n", + "\n", + "X = np.array(images)\n", + "y = np.array(ages)\n", + "\n", + "# Transpose image dimensions to match PyTorch format (N, C, H, W)\n", + "X = np.transpose(X, (0, 3, 1, 2))\n", + "\n", + "# Split Data\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n", + "\n", + "print(f\"X_train shape: {X_train.shape}\")\n", + "print(f\"X_test shape: {X_test.shape}\")\n", + "print(f\"y_train shape: {y_train.shape}\")\n", + "print(f\"y_test shape: {y_test.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 1. Convert Numpy arrays to PyTorch Tensors\n", + "import torch\n", + "import torch.nn as nn\n", + "from torch.optim import Adam\n", + "import matplotlib.pyplot as plt\n", + "from sklearn.datasets import load_breast_cancer\n", + "from sklearn.model_selection import train_test_split\n", + "from sklearn.preprocessing import StandardScaler\n", + "from torch.utils.data import TensorDataset\n", + "from torch.utils.data import DataLoader\n", + "\n", + "\n", + "X_train = torch.tensor(X_train, dtype=torch.float32)\n", + "X_test = torch.tensor(X_test, dtype=torch.float32)\n", + "y_train = torch.tensor(y_train, dtype=torch.float32)\n", + "y_test = torch.tensor(y_test, dtype=torch.float32)\n", + "\n", + "\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 2. Create TensorDataset objects\n", + "\n", + "train_dataset = TensorDataset(X_train, y_train)\n", + "test_dataset = TensorDataset(X_test, y_test)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 3. Create DataLoaders\n", + "\n", + "train_loader = DataLoader(train_dataset, batch_size=32, shuffle=True)\n", + "test_loader = DataLoader(test_dataset, batch_size=32, shuffle=False)\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 4. Print shape of one batch\n", + "X_batch, y_batch = next(iter(train_loader))\n", + "print(f\"Training batch input shape: {X_batch.shape}\")\n", + "print(f\"Training batch labels shape: {y_batch.shape}\")\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 5. Display sample images\n", + "# Get one batch of images and labels\n", + "images, labels = next(iter(train_loader))\n", + "\n", + "# Display the first 6 images in the batch\n", + "plt.figure(figsize=(8, 4))\n", + "\n", + "for i in range(6):\n", + " plt.subplot(2, 3, i + 1)\n", + " plt.imshow(images[i].squeeze(), cmap='gray')\n", + " plt.title(f\"Label: {labels[i].item()}\")\n", + " plt.axis('off')\n", + "\n", + "plt.tight_layout()\n", + "plt.show()\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your model class here:\n", + "class NN4Layer(nn.Module):\n", + " def __init__(self, input_dim, hidden_dim):\n", + " super(NN4Layer, self).__init__()\n", + " # TODO: Define the first linear layer: input_dim -> hidden_dim\n", + " self.layer1 = nn.Linear(input_dim, hidden_dim) # \n", + "\n", + " # TODO: Define the second linear layer: hidden_dim -> hidden_dim\n", + " self.layer2 = nn.Linear(hidden_dim, hidden_dim)\n", + "\n", + " # TODO: Define the third linear layer: hidden_dim -> hidden_dim\n", + " self.layer3 = nn.Linear(hidden_dim, hidden_dim)\n", + "\n", + " # TODO: Define the output layer: hidden_dim -> 1 (single value for regression)\n", + " self.layer4 = nn.Linear(hidden_dim, 1)\n", + "\n", + " # TODO: Define ReLU activation\n", + " self.relu = nn.ReLU() # \n", + "\n", + " def forward(self, x):\n", + " # TODO: First hidden layer with ReLU\n", + " a1 = self.relu(self.layer1(x)) # \n", + "\n", + " # TODO: Second hidden layer with ReLU\n", + " a2 = self.relu(self.layer2(a1)) # \n", + "\n", + " # TODO: Output layer (no activation for regression)\n", + " output = self.layer3(a2) # \n", + "\n", + " return output" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your training loop here:\n", + "def train_one_epoch(model, optimizer, criterion, train_loader, device):\n", + " # TODO: Set the model to training mode\n", + " # \n", + " model.train()\n", + "\n", + " running_loss = 0.0\n", + "\n", + " for X_batch, y_batch in train_loader:\n", + " # TODO: Move batch to the selected device\n", + " X_batch = X_batch.to(device)\n", + " y_batch = y_batch.to(device).reshape(-1, 1) # Reshape y_batch here\n", + "\n", + " # TODO: Forward pass - get model predictions\n", + " outputs = model(X_batch) # \n", + "\n", + " # TODO: Compute loss using criterion\n", + " loss = criterion(outputs, y_batch) # \n", + "\n", + " # TODO: Backward pass & optimization\n", + " # Step 1: Clear previous gradients\n", + " # \n", + " optimizer.zero_grad()\n", + "\n", + " # Step 2: Compute gradients (backward pass)\n", + " # \n", + " loss.backward()\n", + "\n", + " # Step 3: Update model parameters\n", + " # \n", + " optimizer.step()\n", + "\n", + " running_loss += loss.item()\n", + "\n", + " # Calculate average loss over all batches\n", + " avg_loss = running_loss / len(train_loader)\n", + "\n", + " return avg_loss\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your validation loop here:\n", + "def validate(model, criterion, test_loader, device):\n", + " # TODO: Set the model to evaluation mode\n", + " # \n", + " model.eval()\n", + "\n", + " running_loss = 0.0\n", + "\n", + " # TODO: Disable gradient computation using torch.no_grad()\n", + " with torch.no_grad():\n", + " for X_batch, y_batch in test_loader:\n", + " # TODO: Move data to device\n", + " X_batch = X_batch.to(device)\n", + " y_batch = y_batch.to(device).reshape(-1, 1) # Reshape y_batch here\n", + "\n", + " # TODO: Forward pass - get model predictions\n", + " outputs = model(X_batch) # \n", + "\n", + " # TODO: Compute loss using criterion\n", + " loss = criterion(outputs, y_batch) # \n", + "\n", + " running_loss += loss.item()\n", + "\n", + " avg_loss = running_loss / len(test_loader)\n", + "\n", + " return avg_loss" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Define device, model, loss, optimizer:\n", + "from torch.optim import Adam\n", + "device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n", + "learning_rate=0.01\n", + "# Model parameters\n", + "input_dim = X_train.shape[1]\n", + "hidden_dim = 64\n", + "\n", + "model = NN4Layer(input_dim, hidden_dim).to(device)\n", + "\n", + "criterion = nn.MSELoss()\n", + "\n", + "optimizer = Adam(model.parameters(), learning_rate)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Start training for 20 epochs:\n", + "num_epochs = 20\n", + "# Run Training\n", + "train_losses = []\n", + "val_losses = []\n", + "\n", + "print('Starting Training...')\n", + "for epoch in range(num_epochs):\n", + " # TODO: Train one epoch using the train_one_epoch function\n", + " train_loss = train_one_epoch(model, optimizer, criterion, train_loader, device) # \n", + "\n", + " # TODO: Validate using the validate function\n", + " val_loss = validate(model, criterion, test_loader, device) # \n", + "\n", + " train_losses.append(train_loss)\n", + " val_losses.append(val_loss)\n", + "\n", + " print(f'Epoch [{epoch+1}/{num_epochs}], Train Loss: {train_loss:.4f}, Val Loss: {val_loss:.4f}')\n", + "\n", + "print('Training Complete!')" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "plt.figure(figsize=(7, 5))\n", + "\n", + "plt.plot(train_losses, label='Train Loss')\n", + "plt.plot(val_losses, label='Validation Loss')\n", + "plt.title('Loss over Epochs')\n", + "plt.xlabel('Epoch')\n", + "plt.ylabel('Loss (MSE)')\n", + "plt.legend()\n", + "\n", + "plt.tight_layout()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2 (Bonus): Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/375/Q3.ipynb b/submissions_extracted/375/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..1eb327e6d0ea056667ab6701ae25a26c309eeb0f --- /dev/null +++ b/submissions_extracted/375/Q3.ipynb @@ -0,0 +1,265 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "\n", + "\n", + "# Download latest version\n", + "\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q3-exam-data\")\n", + "\n", + "\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "import pandas as pd\n", + "import numpy as np\n", + "import matplotlib.pyplot as plt\n", + "import seaborn as sns\n", + "import kagglehub\n", + "import os\n", + "from tqdm import tqdm\n", + "\n", + "csv_path = os.path.join(path, \"Q3_data.csv\")\n", + "\n", + "df = pd.read_csv(csv_path)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "df.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "df.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "from queue import Empty\n", + "# Task 1: Write your code here:\n", + "def check_missing_values(df):\n", + " missing_values = df.isnull().sum()\n", + " print(\"Missing Values per Column:\")\n", + " print(missing_values[missing_values > 0])\n", + " if missing_values.any():\n", + " print(\"\\nHandle Missing Values as needed.\")\n", + " else:\n", + " print(\"\\nNo Missing Values Found.\")\n", + "\n", + "check_missing_values(df)\n", + "\n", + "Empty = df.select.isnull(df)\n", + "\n", + "\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "def check_duplicates(df):\n", + " duplicates = df.duplicated().sum()\n", + " print(f\"Number of Duplicate Samples: {duplicates}\")\n", + " if duplicates > 0:\n", + " print(\"Dropping Duplicates...\")\n", + " df.drop_duplicates(inplace=True)\n", + " print(\"Duplicates Dropped.\")\n", + " else:\n", + " print(\"No Duplicate Samples Found.\")\n", + "\n", + "check_duplicates(df)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "categorical_cols = df.select_dtypes(include=[\"object\"]).columns\n", + "\n", + "from sklearn.preprocessing import LabelEncoder\n", + "\n", + "categorical_cols = df.select_dtypes(include=[\"object\"]).columns\n", + "for col in categorical_cols:\n", + " print(f\"Encoding column: {col}\")\n", + " le = LabelEncoder()\n", + " df[col] = le.fit_transform(df[col])\n", + "df" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "from sklearn.preprocessing import StandardScaler\n", + "\n", + "features = df.columns.drop(\"Target\") # DON'T SCALE THE TARGET\n", + "\n", + "scaler = StandardScaler()\n", + "df[features] = scaler.fit_transform(df[features])\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "def check_target_imbalance(df, target_column):\n", + " print(\"Target Distribution:\")\n", + " print(df[target_column].value_counts(normalize=True))\n", + " sns.countplot(x=df[target_column])\n", + " plt.title(\"Target Distribution\")\n", + " plt.show()\n", + "\n", + "check_target_imbalance(df, \"Target\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "X = df.drop(\"Target\", axis=1).astype(float)\n", + "y = df['Target'].astype(float)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:\n", + "from sklearn.model_selection import StratifiedKFold\n", + "from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score\n", + "from sklearn.linear_model import LogisticRegression\n", + "\n", + "n_splits = 5\n", + "skf = StratifiedKFold(n_splits=n_splits, shuffle=True, random_state=42)\n", + "\n", + "lr_losses = []\n", + "lr_accuracy = []\n", + "lr_precision = []\n", + "lr_recall = []\n", + "lr_f1 = []\n", + "\n", + "model = LogisticRegression()\n", + "\n", + "for train_index, test_index in skf.split(X, y):\n", + " # Split data into training and testing sets\n", + " X_Train, X_Test = X.loc[train_index, :], X.loc[test_index, :]\n", + " y_Train, y_Test = y.iloc[train_index], y.iloc[test_index]\n", + " # Train the model\n", + " model.fit(X_Train, y_Train)\n", + " # Predict on the test set\n", + " y_pred = model.predict(X_Test)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "lr_model = model\n", + "# For multi-class, we can take the mean of the absolute coefficients across classes\n", + "feature_importances_lr = pd.Series(np.mean(np.abs(lr_model), axis=0), index=X.columns)\n", + "\n", + "# Extract sorted features and their coefficients\n", + "feature_importances_lr = feature_importances_lr.sort_values(ascending=False)\n", + "\n", + "# Plot feature importances\n", + "plt.figure(figsize=(10, 6))\n", + "sns.barplot(x=feature_importances_lr.values, y=feature_importances_lr.index)\n", + "plt.title('Logistic Regression Feature Importances (Absolute Mean Coefficients)')\n", + "plt.xlabel('Absolute Mean Coefficient Value')\n", + "plt.ylabel('Features')\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/376/Q1.ipynb b/submissions_extracted/376/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..c435d3bf0e97d99af65a53212a8dc2bf0b0ae7a5 --- /dev/null +++ b/submissions_extracted/376/Q1.ipynb @@ -0,0 +1,320 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import numpy as np\n", + "import pandas as pd\n", + "import matplotlib.pyplot as plt\n", + "import os\n", + "import kagglehub\n", + "\n", + "from sklearn.model_selection import train_test_split, StratifiedKFold, cross_val_score\n", + "from sklearn.preprocessing import StandardScaler, LabelEncoder\n", + "from sklearn.ensemble import RandomForestClassifier\n", + "from sklearn.metrics import classification_report, confusion_matrix, accuracy_score\n", + "\n", + "import warnings\n", + "warnings.filterwarnings('ignore')" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q1-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "# Load the dataset\n", + "Q1_data_path = os.path.join(path, 'Q1_data.csv')\n", + "df_Q1_data = pd.read_csv(Q1_data_path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "print(f\"Dataset shape: {df_Q1_data.shape}\")\n", + "df_Q1_data.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "# Check data types and structure\n", + "df_Q1_data.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "# Descriptive statistics for numerical columns\n", + "df_Q1_data.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "def check_target_distribution(df_Q1_data, target_column):\n", + " df_Q1_data[target_column].hist(bins=30, edgecolor='black')\n", + "\n", + " plt.title(f\"Target Distribution ({target_column})\")\n", + " plt.xlabel(target_column)\n", + " plt.ylabel(\"Delievery time\")\n", + " plt.grid(False)\n", + "\n", + " plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "df_Q1_data.drop(columns=['Order_ID'])" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "def check_missing_values(df_Q1_data):\n", + " missing_values = df_Q1_data.isnull().sum()\n", + " print(\"Missing Values per Column:\")\n", + " print(missing_values[missing_values > 0])\n", + " if missing_values.any():\n", + " print(\"\\nHandle Missing Values as needed.\")\n", + " else:\n", + " print(\"\\nNo Missing Values Found.\")\n", + "\n", + "check_missing_values(df_Q1_data)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "def check_duplicates(df_Q1_data):\n", + " duplicates = df_Q1_data.duplicated().sum()\n", + " print(f\"Number of Duplicate Samples: {duplicates}\")\n", + " if duplicates > 0:\n", + " print(\"Dropping Duplicates...\")\n", + " df_Q1_data.drop_duplicates(inplace=True)\n", + " print(\"Duplicates Dropped.\")\n", + " else:\n", + " print(\"No Duplicate Samples Found.\")\n", + "\n", + "check_duplicates(df_Q1_data)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "\n", + "categorical_cols = df_Q1_data.select_dtypes(include=[\"object\"]).columns\n", + "\n", + "print(\"Categorical Columns:\", list(categorical_cols))" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "from sklearn.preprocessing import StandardScaler\n", + "\n", + "numerical_cols = df_Q1_data.select_dtypes(include=[\"int64\", \"float64\"]df_Q1_data).columns.drop(\"status\")\n", + "\n", + "scaler = StandardScaler()\n", + "df_Q1_data[numerical_cols] = scaler.fit_transform([numerical_cols])\n", + "df_Q1_data.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 6: Write your code here:\n", + "def check_target_imbalance(df_Q1_data):\n", + " print(\"Target Distribution:\")\n", + " print(df_Q1_data[target_column].value_counts(normalize=True))\n", + " sns.countplot(x=df[target_column])\n", + " plt.title(\"Target Distribution\")\n", + " plt.show()\n", + "\n", + "check_target_imbalance(df_Q1_data, \"delivery_time\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "from sklearn.model_selection import StratifiedKFold\n", + "from sklearn.metrics import accuracy_score, f1_score" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "# Define features (X) and target (y)\n", + "feature_cols = [ 'delivery distance', 'restaurant preparation time\", \"traffic conditions', 'order details'\n", + "\n", + "]\n", + "\n", + "X = df_Q1_data_clean[feature_cols]\n", + "y = df_Q1_data_clean['delievery time']" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "from sklearn.ensemble import RandomForestRegressor\n", + "\n", + "# Task 2,3,4,5: Write your code here:\n", + "#Task 2\n", + "n_splits = 3 # K=3 Folds\n", + "\n", + "skf = StratifiedKFold(n_splits=n_splits, shuffle=True, random_state=42)\n", + "# Task 3\n", + "# Train Random Forest Regressor\n", + "model = RandomForestRegressor(n_estimators=100, max_depth=20, random_state=42, n_jobs=-1)\n", + "model.fit(X_train_scaled, y_train)\n", + "print(\"Model trained!\")\n", + "\n", + "# Task 4\n", + "# Get predictions on test set\n", + "model.eval()\n", + "with torch.no_grad():\n", + " # TODO: Get predictions for X_test\n", + " # [HINT]: Move X_test to device, pass through model, then move back to CPU\n", + " predictions = model(X_test.to(device)).cpu().numpy()\n", + "\n", + "# TODO: Calculate evaluation metrics\n", + "mae = mean_absolute_error(y_test.numpy(), p\n", + "\n", + "# Task 5\n", + "for model_name in all_results:\n", + " print(f\"\\n{model_name}:\")\n", + " print(f\" MSE: {np.mean(all_results[model_name]['mse']):.4f}\")\n", + " print(f\" RMSE: {np.mean(all_results[model_name]['rmse']):.4f}\")\n", + " print(f\" R2: {np.mean(all_results[model_name]['r2']):.4f}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "# Feature importance\n", + "importance = pd.DataFrame({\n", + " 'feature': feature_cols,\n", + " 'importance': model.feature_importances_\n", + "}).sort_values('importance', ascending=False)\n", + "\n", + "plt.figure(figsize=(10, 6))\n", + "plt.barh(importance['feature'], importance['importance'], color='purple')\n", + "plt.xlabel('Importance')\n", + "plt.title('Feature Importance')\n", + "plt.gca().invert_yaxis()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "def check_target_distribution(df_Q1_data, target_column):\n", + " df[target_column].hist(bins=30, edgecolor='black')\n", + "\n", + " plt.title(f\"minutes ({target_column})\")\n", + " plt.xlabel(target_column)\n", + " plt.ylabel(\"delievery time\")\n", + " plt.grid(False)\n", + "\n", + " plt.show()\n", + "\n", + "check_target_distribution(df_Q1_data, \"delievery time\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/376/Q2.ipynb b/submissions_extracted/376/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..84bba2d3f5afa0fa7fc79135053323dbea27d2d6 --- /dev/null +++ b/submissions_extracted/376/Q2.ipynb @@ -0,0 +1,408 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q2-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import os\n", + "import pandas as pd\n", + "import numpy as np\n", + "from PIL import Image\n", + "from sklearn.model_selection import train_test_split\n", + "\n", + "# Load Labels\n", + "labels_df = pd.read_csv(os.path.join(path, \"labels.csv\"))\n", + "img_dir = os.path.join(path, \"images\")\n", + "\n", + "images = []\n", + "ages = []\n", + "\n", + "# Load Images and Resize\n", + "print(\"Loading images...\")\n", + "for index, row in labels_df.iterrows():\n", + " img_name = row.iloc[0]\n", + " age = row.iloc[1]\n", + " img_path = os.path.join(img_dir, img_name)\n", + "\n", + " if os.path.exists(img_path):\n", + " img = Image.open(img_path).convert('RGB')\n", + " img_array = np.array(img) / 255.0 # Normalize pixel values to [0, 1]\n", + " images.append(img_array)\n", + " ages.append(age)\n", + "\n", + "X = np.array(images)\n", + "y = np.array(ages)\n", + "\n", + "# Transpose image dimensions to match PyTorch format (N, C, H, W)\n", + "X = np.transpose(X, (0, 3, 1, 2))\n", + "\n", + "# Split Data\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n", + "\n", + "print(f\"X_train shape: {X_train.shape}\")\n", + "print(f\"X_test shape: {X_test.shape}\")\n", + "print(f\"y_train shape: {y_train.shape}\")\n", + "print(f\"y_test shape: {y_test.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Import required libraries\n", + "import kagglehub\n", + "import pandas as pd\n", + "import numpy as np\n", + "import torch\n", + "import torch.nn as nn\n", + "from torch.optim import AdamW\n", + "import matplotlib.pyplot as plt\n", + "from torch.utils.data import DataLoader, TensorDataset\n", + "from sklearn.model_selection import train_test_split\n", + "from sklearn.preprocessing import StandardScaler, LabelEncoder\n", + "from sklearn.metrics import mean_absolute_error, mean_squared_error, r2_score\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 1. Convert Numpy arrays to PyTorch Tensors\n", + "# TODO: Split features from target\n", + "X = df_img_dir.drop(\"age\",axis=1)\n", + "y = df_img_dir['age']\n", + "\n", + "# TODO: Split the dataset into training and testing sets (80% train, 20% test)\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n", + "\n", + "# TODO: Transform to PyTorch tensors with dtype=torch.float32\n", + "X_train = torch.tensor(X_train.values, dtype=torch.float32)\n", + "X_test = torch.tensor(X_test.values, dtype=torch.float32)\n", + "y_train = torch.tensor(y_train.values, dtype=torch.float32)\n", + "y_test = torch.tensor(y_test.values, dtype=torch.float32)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 2. Create TensorDataset objects\n", + "# Create TensorDatasets for training and testing\n", + "train_dataset = TensorDataset(X_train, y_train)\n", + "test_dataset = TensorDataset(X_test, y_test)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 3. Create DataLoaders\n", + "# Create Dataloaders to train and test data in batches\n", + "train_loader = DataLoader(train_dataset, batch_size=32, shuffle=True)\n", + "test_loader = DataLoader(test_dataset, batch_size=32, shuffle=False)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 4. Print shape of one batch\n", + "\n", + "# Get the first batch from the training DataLoader\n", + "X_batch, y_batch = next(iter(train_loader))\n", + "print(f\"Training batch input shape: {X_batch.shape}\")\n", + "print(f\"Training batch labels shape: {y_batch.shape}\")\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 5. Display sample images\n", + "from torchvision.datasets import MNIST\n", + "from torchvision.transforms.functional import to_tensor\n", + "\n", + "# Training dataset\n", + "train_dataset = MNIST(\n", + " root='./datasets', # Dataset storage path\n", + " train=True, # Use training data\n", + " transform=to_tensor, # Convert images to tensors\n", + " download=True # Download if not available\n", + ")\n", + "\n", + "# Testing dataset\n", + "test_dataset = MNIST(\n", + " root='./datasets', # Dataset storage path\n", + " train=False, # Use test data\n", + " transform=to_tensor, # Convert images to tensors\n", + " download=True # Download if not available\n", + ")\n", + "\n", + "# print one sample from the dataset\n", + "# Each sample consists of an image tensor and its label\n", + "sample_image, sample_label = train_dataset[0]\n", + "\n", + "print(f\"\\n Image shape: {sample_image.shape}\") # (1, 28, 28)\n", + "print(f\"Label: {sample_label}\")\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your model class here:\n", + "class NN5Layer(nn.Module):\n", + "\n", + " def __init__(self, input_dim, hidden_dim, output_dim):\n", + " super(NN5Layer, self).__init__()\n", + "\n", + " # TODO: What are the dimensions of the first layer? (hint: features? hidden neurons?)\n", + " self.layer1 = nn.Linear(input_dim, hidden_dim)\n", + "\n", + " # TODO: What are the dimensions from previous and next layer?\n", + " self.layer2 = nn.Linear(hidden_dim, hidden_dim)\n", + "\n", + " # TODO: What are the dimensions from previous and next layer?\n", + " self.layer3 = nn.Linear(hidden_dim, hidden_dim)\n", + "\n", + " # TODO: What are the dimensions from previous and next layer?\n", + " self.layer4 = nn.Linear(hidden_dim, hidden_dim)\n", + "\n", + " # Defines how input data flows through the network\n", + " def forward(self, x):\n", + " # Layer 1: TODO\n", + " z1 = self.layer1(x)\n", + " a1 = self.relu(z1)\n", + "\n", + " # Layer 2 TODO\n", + " z2 = self.layer2(a1)\n", + " a2 = self.relu(z2)\n", + "\n", + " # Layer 3 TODO\n", + " z3 = self.layer3(a2)\n", + " a3 = self.relu(z3)\n", + "\n", + " # Layer 4 TODO\n", + " z4 = self.layer4(a3)\n", + " a4 = self.relu(z4)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your training loop here:\n", + "def train_one_epoch(model, optimizer, criterion, train_loader, device):\n", + " # Set the model to training mode\n", + " model.train()\n", + "\n", + " running_loss = 0.0\n", + "\n", + " for X_batch, y_batch in train_loader:\n", + " # Move batch to the selected device\n", + " X_batch = X_batch.to(device) # shape: (batch_size, num_features)\n", + " y_batch = y_batch.to(device) # shape: (batch_size,)\n", + "\n", + " # Forward pass (outputs are logits)\n", + " outputs = model(X_batch) # shape: (batch_size, num_classes)\n", + " loss = criterion(outputs, y_batch)\n", + "\n", + " # Backward pass & optimization\n", + " optimizer.zero_grad() # Clear previous gradients\n", + " loss.backward() # Compute gradients\n", + " optimizer.step() # Update model parameters\n", + "\n", + " running_loss += loss.item()\n", + "\n", + " # Average loss over all batches\n", + " avg_loss = running_loss / len(train_loader)\n", + "\n", + " return avg_loss" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your validation loop here:\n", + "def validate(model, criterion, test_loader, device):\n", + " # Set the model to evaluation mode\n", + " model.eval()\n", + "\n", + " running_loss = 0.0\n", + " correct = 0\n", + " total = 0\n", + "\n", + " with torch.no_grad():\n", + " for X_batch, y_batch in test_loader:\n", + " # Move data to device\n", + " X_batch = X_batch.to(device) # shape: (batch_size, num_features)\n", + " y_batch = y_batch.to(device) # shape: (batch_size,)\n", + "\n", + " # Forward pass\n", + " outputs = model(X_batch) # shape: (batch_size, num_classes)\n", + " loss = criterion(outputs, y_batch)\n", + " running_loss += loss.item()\n", + "\n", + " # Apply Softmax to get probabilities\n", + " probabilities = F.softmax(outputs, dim=1)\n", + "\n", + " # Pick the classes with highest probabilities\n", + " predicted = torch.argmax(probabilities, dim=1)\n", + "\n", + " # Accuracy calculation\n", + " correct += (predicted == y_batch).sum().item()\n", + " total += y_batch.size(0)\n", + "\n", + " avg_loss = running_loss / len(test_loader)\n", + " accuracy = correct / total\n", + "\n", + " return avg_loss, accuracy" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Device setup\n", + "device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n", + "\n", + "# Model parameters\n", + "input_dim = X_train.shape[1] # Number of tabular features\n", + "hidden_dim = 14 # Design choice\n", + "output_dim = 4 # Weather classes: Rainy, Sunny, Cloudy, Snowy\n", + "\n", + "# Instantiate model\n", + "model = NN4Layer(input_dim, hidden_dim, output_dim).to(device)\n", + "\n", + "# Print the model architecture\n", + "print(\"Model Architecture:\\n\")\n", + "print(model)\n", + "\n", + "# Calculate the total number of trainable parameters\n", + "total_params = sum(p.numel() for p in model.parameters() if p.requires_grad)\n", + "print(f\"\\nTotal trainable parameters: {total_params}\")\n", + "# Define criterion (loss function) - using CrossEntropyLoss as model now outputs logits\n", + "criterion = nn.CrossEntropyLoss()\n", + "# Define optimizer\n", + "optimizer = AdamW(model.parameters(), learning_rate)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Start training for 20 epochs:\n", + "# Run Training\n", + "train_losses = []\n", + "val_losses = []\n", + "val_accuracies = []\n", + "\n", + "print('Starting Training...')\n", + "for epoch in range(num_epochs):\n", + " # Train one epoch\n", + " train_loss = train_one_epoch(model, optimizer, criterion, train_loader, device)\n", + "\n", + " # Validate\n", + " val_loss, val_accuracy = validate(model, criterion, test_loader, device)\n", + "\n", + " train_losses.append(train_loss)\n", + " val_losses.append(val_loss)\n", + " val_accuracies.append(val_accuracy)\n", + "\n", + " print(f'Epoch [{epoch+1}/{num_epochs}], Train Loss: {train_loss:.4f}, Val Loss: {val_loss:.4f}, Val Accuracy: {val_accuracy:.4f}')\n", + "\n", + "print('Training Complete!')\n", + "\n", + "num_epochs = 20\n", + "learning_rate = 0.001\n", + "\n", + "# Define criterion (loss function) - using CrossEntropyLoss as model now outputs logits\n", + "criterion = nn.CrossEntropyLoss()\n", + "# Define optimizer\n", + "optimizer = AdamW(model.parameters(), learning_rate)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "# Plotting results\n", + "plt.figure(figsize=(7, 5))\n", + "\n", + "plt.plot(train_losses, label='Train Loss')\n", + "plt.plot(val_losses, label='Validation Loss')\n", + "plt.title('Loss over Epochs')\n", + "plt.xlabel('Epoch')\n", + "plt.ylabel('Loss')\n", + "plt.legend()\n", + "\n", + "plt.tight_layout()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2 (Bonus): Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/376/Q3.ipynb b/submissions_extracted/376/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..3b975dd55b066454c8e50244ad53eaf298638eab --- /dev/null +++ b/submissions_extracted/376/Q3.ipynb @@ -0,0 +1,362 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import numpy as np\n", + "import pandas as pd\n", + "import matplotlib.pyplot as plt\n", + "import os\n", + "import kagglehub\n", + "\n", + "from sklearn.model_selection import train_test_split, StratifiedKFold, cross_val_score\n", + "from sklearn.preprocessing import StandardScaler, LabelEncoder\n", + "from sklearn.ensemble import RandomForestClassifier\n", + "from sklearn.metrics import classification_report, confusion_matrix, accuracy_score\n", + "\n", + "import warnings\n", + "warnings.filterwarnings('ignore')" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "\n", + "\n", + "# Download latest version\n", + "\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q3-exam-data\")\n", + "\n", + "\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "\n", + "# Load the dataset\n", + "Q3_data_path = os.path.join(path, 'Q3_data.csv')\n", + "df_Q3_data = pd.read_csv(Q3_data_path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "print(f\"Dataset shape: {df_Q3_data.shape}\")\n", + "df_Q3_data.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "# Check data types and structure\n", + "df_Q3_data.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "# Descriptive statistics for numerical columns\n", + "df_Q3_data.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "def check_missing_values(df_Q3_data):\n", + " missing_values = df_Q3_data.isnull().sum()\n", + " print(\"Missing Values per Column:\")\n", + " print(missing_values[missing_values > 0])\n", + " if missing_values.any():\n", + " print(\"\\nHandle Missing Values as needed.\")\n", + " else:\n", + " print(\"\\nNo Missing Values Found.\")\n", + "\n", + "check_missing_values(df_Q3_data)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "def check_duplicates(df_Q3_data):\n", + " duplicates = df_Q3_data.duplicated().sum()\n", + " print(f\"Number of Duplicate Samples: {duplicates}\")\n", + " if duplicates > 0:\n", + " print(\"Dropping Duplicates...\")\n", + " df_Q1_data.drop_duplicates(inplace=True)\n", + " print(\"Duplicates Dropped.\")\n", + " else:\n", + " print(\"No Duplicate Samples Found.\")\n", + "\n", + "check_duplicates(df_Q3_data)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "categorical_cols = df_Q3_data.select_dtypes(include=[\"object\"]).columns\n", + "\n", + "print(\"Categorical Columns:\", list(categorical_cols))" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "def check_target_imbalance(df_Q3_data, target_column):\n", + " print(\"Target Distribution:\")\n", + "\n", + " df_Q3_data[target_column].hist()\n", + " plt.show()\n", + "\n", + "check_target_imbalance(df_Q3_data, \"P_2\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "\n", + "from sklearn.model_selection import train_test_split\n", + "\n", + "X_clf = pd.df_Q3_data({\"Feature_1\": np.random.randn(500)}) # features\n", + "y_clf = (X_clf[\"Feature_1\"] > 0).astype(int) # labels as class 0 or 1 y: 0 if X < 0 else 1\n", + "\n", + "# Use previously generated random data (example: classification data)\n", + "X, y = X_clf.copy(), y_clf.copy() # to make seperation from both copies of data (so original dats doesn't change)\n", + "\n", + "# split ratio (80% train, 20% test)\n", + "X_train, X_test, y_train, y_test = train_test_split(\n", + " X, y,\n", + " test_size=0.2, # 20% for test, remaining 80% for train\n", + " random_state=42, # reproducible output = same results everytime\n", + " shuffle=True, # representative splits = mix up the data first, then split\n", + " stratify=y # preserve class distribution = keep the same class ratio in both train and rest\n", + ")\n", + "# With stratify\n", + "# train 60% class 0, 40% class 1\n", + "# Test: 60% class 0, $0# class 1\n", + "\n", + "# Print shapes\n", + "print(\"X_train shape:\", X_train.shape)\n", + "print(\"X_test shape:\", X_test.shape)\n", + "print(\"y_train shape:\", y_train.shape)\n", + "print(\"y_test shape:\", y_test.shape) # because 1D we didn't place something after the comma" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Import models\n", + "from sklearn.linear_model import LogisticRegression\n", + "from sklearn.neighbors import KNeighborsClassifier\n", + "from sklearn.svm import SVC\n", + "from sklearn.tree import DecisionTreeClassifier\n", + "from sklearn.ensemble import RandomForestClassifier\n", + "from xgboost import XGBClassifier\n", + "from catboost import CatBoostClassifier\n", + "# Task 2,3,4,5: Write your code here:\n", + "# Task 2\n", + "\n", + "from sklearn.model_selection import StratifiedKFold\n", + "from sklearn.metrics import accuracy_score, f1_score\n", + "\n", + "n_splits = 3 # K=3 Folds\n", + "\n", + "skf = StratifiedKFold(n_splits=n_splits, shuffle=True, random_state=42)\n", + "\n", + "# Task 3 CatBoostClassifier\n", + " \"CatBoost\": CatBoostClassifier(\n", + " verbose=0,\n", + " n_estimators=200,\n", + " max_depth=4\n", + " )\n", + "}\n", + "\n", + "# Task 4\n", + "# Calculate evaluation metrics\n", + " accuracy = accuracy_score(y_test, y_pred)\n", + " f1 = f1_score(y_test, y_pred, average='macro') # for multiclass f1 score, you should set the average hyperparameter (\"macro\", \"micro\", \"weighted\")\n", + "\n", + " # Store results\n", + " sr_results['loss'].append(losses)\n", + " sr_results['acc'].append(accuracy)\n", + " sr_results['f1'].append(f1)\n", + "\n", + " # Task 5\n", + " # Print the average of each evaluation metric across folds\n", + " print(f\" Accuracy: {np.mean(results[model_name]['accuracy']):.4f}\")\n", + " print(f\" F1-Score: {np.mean(results[model_name]['f1']):.4f}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Import models\n", + "from sklearn.neighbors import KNeighborsClassifier\n", + "from sklearn.svm import SVC\n", + "from sklearn.tree import DecisionTreeClassifier\n", + "from sklearn.ensemble import RandomForestClassifier\n", + "from xgboost import XGBClassifier\n", + "from catboost import CatBoostClassifier" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "sklearn_models = {\n", + " \"K-Nearest Neighbors\": KNeighborsClassifier(\n", + " n_neighbors=3, # Number of neighbors to consider\n", + " ),\n", + " \"Support Vector Machine\": SVC(\n", + " kernel='rbf', # 'linear', 'poly', 'rbf', 'sigmoid'\n", + " C=0.75 # Regularization parameter\n", + " ),\n", + " \"Decision Tree\": DecisionTreeClassifier(\n", + " max_depth=3 # Maximum depth of tree (prevents overfitting)\n", + " ),\n", + " \"Random Forest\": RandomForestClassifier(\n", + " n_estimators=320, # Number of trees\n", + " max_depth=4\n", + " ),\n", + " \"XGBoost\": XGBClassifier(\n", + " verbosity=0,\n", + " n_estimators=300, # Number of boosting rounds\n", + " max_depth=5,\n", + " learning_rate=0.05 # Step size shrinkage\n", + " ),\n", + " \"CatBoost\": CatBoostClassifier(\n", + " verbose=0,\n", + " n_estimators=320,\n", + " max_depth=4\n", + " )\n", + "}\n", + "# Gather importances from the models (from the last fold)\n", + "importances = {}\n", + "\n", + "importances['Random Forest'] = sklearn_models['Random Forest'].feature_importances_\n", + "importances['XGBoost'] = sklearn_models['XGBoost'].feature_importances_\n", + "importances['CatBoost'] = sklearn_models['CatBoost'].feature_importances_\n", + "\n", + "# Create a 1x3 plot\n", + "fig, axes = plt.subplots(1, 3, figsize=(18, 6))\n", + "axes = axes.flatten()\n", + "features = X.columns\n", + "\n", + "for i, (model_name, imp) in enumerate(importances.items()):\n", + " # Sort features by importance for a cleaner plot\n", + " sorted_idx = np.argsort(imp)\n", + "\n", + " ax = axes[i]\n", + " ax.barh(features[sorted_idx], imp[sorted_idx])\n", + " ax.set_title(f\"{model_name} Feature Importance\")\n", + " ax.set_xlabel(\"Importance Score\")\n", + "\n", + "plt.tight_layout()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "# Sort features by importance for a cleaner plot\n", + " sorted_idx = np.argsort(imp)\n", + "\n", + " ax = axes[i]\n", + " ax.barh(features[sorted_idx], imp[sorted_idx])\n", + " ax.set_title(f\"{model_name} Feature Importance\")\n", + " ax.set_xlabel(\"Importance Score\")\n", + "\n", + "plt.tight_layout()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/377/Q1.ipynb b/submissions_extracted/377/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..3441ccfb29f6b6d79c4d6dac12decc1e35458610 --- /dev/null +++ b/submissions_extracted/377/Q1.ipynb @@ -0,0 +1,421 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q1-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "\n", + "# Core Libraries\n", + "import numpy as np\n", + "import pandas as pd\n", + "import matplotlib.pyplot as plt\n", + "import seaborn as sns\n", + "import warnings\n", + "warnings.filterwarnings('ignore')\n", + "import os\n", + "\n", + "# Scikit-Learn: Data Preprocessing\n", + "from sklearn.model_selection import train_test_split, KFold, StratifiedKFold, cross_val_score\n", + "from sklearn.preprocessing import StandardScaler, MinMaxScaler, LabelEncoder, OneHotEncoder\n", + "\n", + "# Scikit-Learn: Regression Models\n", + "from sklearn.linear_model import LinearRegression, Ridge, Lasso\n", + "from sklearn.tree import DecisionTreeRegressor\n", + "from sklearn.ensemble import RandomForestRegressor\n", + "from sklearn.svm import SVR\n", + "\n", + "# Scikit-Learn: Classification Models\n", + "from sklearn.linear_model import LogisticRegression\n", + "from sklearn.neighbors import KNeighborsClassifier\n", + "from sklearn.tree import DecisionTreeClassifier\n", + "from sklearn.ensemble import RandomForestClassifier\n", + "from sklearn.svm import SVC\n", + "\n", + "# Scikit-Learn: Metrics\n", + "from sklearn.metrics import (\n", + " mean_absolute_error, mean_squared_error, r2_score,\n", + " accuracy_score, precision_score, recall_score, f1_score,\n", + " confusion_matrix, classification_report\n", + ")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "csv_path = os.path.join(path, \"Q1_data.csv\")\n", + "\n", + "df = pd.read_csv(csv_path)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "df.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "df.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "\n", + "def check_target_distribution(df, target_column):\n", + " df[target_column].hist(bins=30, edgecolor='black')\n", + "\n", + " plt.title(f\"Target Distribution ({target_column})\")\n", + " plt.xlabel(target_column)\n", + " plt.ylabel(\"Frequency\")\n", + " plt.grid(False)\n", + "\n", + " plt.show()\n", + "\n", + "check_target_distribution(df, \"Delivery_Time\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "df = df.drop(columns=['Order_ID'])\n", + "df.isnull().sum()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "df_clean =df.dropna(subset=['Delivery_Time'])\n", + "df_clean" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "def check_missing_values(df):\n", + " missing_values = df.isnull().sum()\n", + " print(\"Missing Values per Column:\")\n", + " print(missing_values[missing_values > 0])\n", + " if missing_values.any():\n", + " print(\"\\nHandle Missing Values as needed.\")\n", + " else:\n", + " print(\"\\nNo Missing Values Found.\")\n", + "check_missing_values(df_clean)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "df_clean.isnull().sum()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "for col in ['Weather', 'Traffic_Level']:\n", + " df_clean[col] = df_clean[col].mode()[0]\n", + "df_clean" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "df_clean['Courier_Experience_yrs'] = df_clean['Courier_Experience_yrs'].fillna(df_clean['Courier_Experience_yrs'].mean())\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "def check_duplicates(df):\n", + " duplicates = df.duplicated().sum()\n", + " print(f\"Number of Duplicate Samples: {duplicates}\")\n", + " if duplicates > 0:\n", + " print(\"Dropping Duplicates...\")\n", + " df.drop_duplicates(inplace=True) # changes in original data\n", + " print(\"Duplicates Dropped.\")\n", + " else:\n", + " print(\"No Duplicate Samples Found.\")\n", + "\n", + "check_duplicates(df_clean)\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "categorical_cols = df_clean.select_dtypes(include=[\"object\"]).columns\n", + "\n", + "print(\"Categorical Columns:\", list(categorical_cols))" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "categorical_cols = ['Weather', 'Traffic_Level', 'Time_of_Day', 'Vehicle_Type']\n", + "label_encoders = {}\n", + "for col in categorical_cols:\n", + " le = LabelEncoder()\n", + " df_clean[col] = le.fit_transform(df_clean[col])\n", + " label_encoders[col] = le\n", + "\n", + "# onehot_encoder = OneHotEncoder(sparse_output=False) # Instantiate OneHotEncoder\n", + "# data_onehot_encoded = onehot_encoder.fit_transform(df_clean[categorical_cols]) # Apply fit_transform to the copied\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "features = df_clean.columns.drop(\"Delivery_Time\")\n", + "scaler = StandardScaler()\n", + "df_clean[features] = scaler.fit_transform(df_clean[features])\n", + "df_clean.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 6: Write your code here:\n", + "# slightly right skwed so considered balanced" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "X = df_clean.drop(\"Delivery_Time\", axis=1).astype(float)\n", + "y = df_clean['Delivery_Time'].astype(float)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "models = {\n", + " \"Ridge Regression\": Ridge(alpha=1.0, max_iter=10000),\n", + " \"Random Forest Regressor\": RandomForestRegressor(n_estimators=200),\n", + "}" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "all_results = {}\n", + "\n", + "for name in models:\n", + " all_results[name] = {'mse': [], 'rmse': [], 'r2': []}" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "from sklearn.metrics import mean_squared_error as sklearn_mse, mean_absolute_error, r2_score" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "\n", + "n_splits = 5 # K=5 Folds\n", + "\n", + "# 5-Fold Cross-Validation, shuffled\n", + "kf = KFold(n_splits=n_splits, shuffle=True, random_state=42)\n", + "\n", + "kf = KFold(n_splits=5, shuffle=True, random_state=42)\n", + "\n", + "for fold_idx, (train_index, test_index) in enumerate(kf.split(X)):\n", + " print(f\"\\nFold {fold_idx + 1}/{n_splits}\")\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", + " for model_name, model in models.items():\n", + " print(f\"Training {model_name}...\")\n", + "\n", + " # Train\n", + " model.fit(X_train, y_train)\n", + "\n", + " # Predict\n", + " y_pred = model.predict(X_test)\n", + "\n", + " # Calculate metrics\n", + " mse = sklearn_mse(y_test, y_pred)\n", + " rmse = np.sqrt(mse)\n", + " r2 = r2_score(y_test, y_pred)\n", + "\n", + " # Store results\n", + " all_results[model_name][\"mse\"].append(mse)\n", + " all_results[model_name][\"rmse\"].append(rmse)\n", + " all_results[model_name][\"r2\"].append(r2)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "for model_name in all_results:\n", + " print(f\"\\n{model_name}:\")\n", + " print(f\" MSE: {np.mean(all_results[model_name]['mse']):.4f}\")\n", + " print(f\" RMSE: {np.mean(all_results[model_name]['rmse']):.4f}\")\n", + " print(f\" R2: {np.mean(all_results[model_name]['r2']):.4f}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/377/Q2.ipynb b/submissions_extracted/377/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..fc91da4bde14daf8f26bec3e4e8c9dfec6d6977c --- /dev/null +++ b/submissions_extracted/377/Q2.ipynb @@ -0,0 +1,449 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q2-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import os\n", + "import pandas as pd\n", + "import numpy as np\n", + "from PIL import Image\n", + "from sklearn.model_selection import train_test_split\n", + "import torch\n", + "import torch.nn as nn\n", + "import torch.nn.functional as F\n", + "from torch.optim import Adam, AdamW, SGD\n", + "from torch.utils.data import DataLoader, TensorDataset\n", + "\n", + "import numpy as np\n", + "import pandas as pd\n", + "import matplotlib.pyplot as plt\n", + "\n", + "from sklearn.model_selection import train_test_split\n", + "from sklearn.preprocessing import StandardScaler, LabelEncoder\n", + "from sklearn.datasets import load_breast_cancer, load_iris, load_diabetes\n", + "\n", + "device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n", + "print(f\"Device: {device}\")\n", + "\n", + "# Load Labels\n", + "labels_df = pd.read_csv(os.path.join(path, \"labels.csv\"))\n", + "img_dir = os.path.join(path, \"images\")\n", + "\n", + "images = []\n", + "ages = []\n", + "\n", + "# Load Images and Resize\n", + "print(\"Loading images...\")\n", + "for index, row in labels_df.iterrows():\n", + " img_name = row.iloc[0]\n", + " age = row.iloc[1]\n", + " img_path = os.path.join(img_dir, img_name)\n", + "\n", + " if os.path.exists(img_path):\n", + " img = Image.open(img_path).convert('RGB')\n", + " img_array = np.array(img)\n", + " images.append(img_array)\n", + " ages.append(age)\n", + "\n", + "X = np.array(images)\n", + "y = np.array(ages)\n", + "\n", + "# Transpose image dimensions to match PyTorch format (N, C, H, W)\n", + "X = np.transpose(X, (0, 3, 1, 2))\n", + "\n", + "# Split Data\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n", + "\n", + "print(f\"X_train shape: {X_train.shape}\")\n", + "print(f\"X_test shape: {X_test.shape}\")\n", + "print(f\"y_train shape: {y_train.shape}\")\n", + "print(f\"y_test shape: {y_test.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 1. Convert Numpy arrays to PyTorch Tensors\n", + "\n", + "X_train = torch.tensor(X_train, dtype=torch.float32)\n", + "X_test = torch.tensor(X_test, dtype=torch.float32)\n", + "y_train = torch.tensor(y_train, dtype=torch.long)\n", + "y_test = torch.tensor(y_test, dtype=torch.long)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 2. Create TensorDataset objects\n", + "\n", + "train_dataset = TensorDataset(X_train, y_train)\n", + "test_dataset = TensorDataset(X_test, y_test)\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 3. Create DataLoaders\n", + "\n", + "from torch.utils.data import DataLoader\n", + "\n", + "# DataLoader for training data\n", + "train_loader = DataLoader(\n", + " train_dataset,\n", + " batch_size=32,\n", + " shuffle=True,\n", + " num_workers=2\n", + ")\n", + "# DataLoader for test/validation data\n", + "test_loader = DataLoader(\n", + " test_dataset,\n", + " batch_size=32,\n", + " shuffle=False,\n", + " num_workers=2\n", + ")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 4. Print shape of one batch\n", + "\n", + "# Get the first batch from the training DataLoader\n", + "X_batch, y_batch = next(iter(train_loader))\n", + "print(f\"Training batch input shape: {X_batch.shape}\")\n", + "print(f\"Training batch labels shape: {y_batch.shape}\")\n", + "\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "images, labels = next(iter(train_loader))\n", + "\n", + "# Display the first 6 images in the batch\n", + "plt.figure(figsize=(8, 4))\n", + "\n", + "for i in range(6):\n", + " plt.subplot(2, 3, i + 1)\n", + " plt.imshow(images[i].squeeze().view(), cmap='gray')\n", + " plt.title(f\"Label: {labels[i].item()}\")\n", + " plt.axis('off')\n", + "\n", + "plt.tight_layout()\n", + "plt.show()\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your model class here:\n", + "\n", + "\n", + "class MulticlassNet(nn.Module):\n", + " def __init__(self, input_dim, hidden_dim, num_classes):\n", + " super().__init__()\n", + " self.layer1 = nn.Linear(input_dim, hidden_dim)\n", + " self.layer2 = nn.Linear(hidden_dim, hidden_dim)\n", + " self.layer3 = nn.Linear(hidden_dim, hidden_dim)\n", + " self.layer4 = nn.Linear(hidden_dim, num_classes) # one per class!\n", + " self.relu = nn.ReLU()\n", + " # NO softmax! CrossEntropyLoss handles it!\n", + "\n", + " def forward(self, x):\n", + " x = self.relu(self.layer1(x))\n", + " x = self.relu(self.layer2(x))\n", + " x = self.relu(self.layer3(x))\n", + "\n", + " x = self.layer4(x) # raw logits\n", + " return x" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your training loop here:\n", + "INPUT_DIM = X_train.shape[1]\n", + "HIDDEN_DIM = 64\n", + "NUM_CLASSES = 10 # for multiclass\n", + "LEARNING_RATE = 0.001\n", + "NUM_EPOCHS = 20\n", + "\n", + "\n", + "def train_one_epoch(model, optimizer, criterion, train_loader, device, task):\n", + " model.train() # TRAINING MODE!\n", + " running_loss = 0.0\n", + "\n", + " for X_batch, y_batch in train_loader:\n", + " X_batch = X_batch.view(X_batch.size(0), -1).to(device) # flatten image to a vector\n", + " y_batch = y_batch.to(device)\n", + "\n", + "\n", + " # Forward\n", + " outputs = model(X_batch)\n", + " loss = criterion(outputs, y_batch)\n", + "\n", + " # Backward - THIS ORDER MATTERS!\n", + " optimizer.zero_grad() # 1️⃣ Clear gradients\n", + " loss.backward() # 2️⃣ Compute gradients\n", + " optimizer.step() # 3️⃣ Update weights\n", + "\n", + " running_loss += loss.item()\n", + "\n", + " return running_loss / len(train_loader)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your validation loop here:\n", + "\n", + "def validate(model, criterion, test_loader, device, task):\n", + " model.eval()\n", + " running_loss = 0.0\n", + " correct = 0\n", + " total = 0\n", + "\n", + " with torch.no_grad(): # NO GRADIENTS!\n", + " for X_batch, y_batch in test_loader:\n", + " X_batch = X_batch.to(device)\n", + " y_batch = y_batch.to(device)\n", + " y_batch_loss = y_batch\n", + "\n", + " i_, predicted = torch.max(outputs, dim=1)\n", + " correct += (predicted == y_batch).sum().item()\n", + " outputs = model(X_batch)\n", + " loss = criterion(outputs, y_batch_loss)\n", + " running_loss += loss.item()\n", + "\n", + "\n", + " avg_loss = running_loss / len(test_loader)\n", + " accuracy = correct / total if task != \"regression\" else 0\n", + " return avg_loss, accuracy" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "rain_losses = []\n", + "val_losses = []\n", + "val_accs = []\n", + "\n", + "print(\"Training started...\")\n", + "\n", + "for epoch in range(NUM_EPOCHS):\n", + " train_loss = train_one_epoch(model, optimizer, criterion, train_loader, device, TASK)\n", + " val_loss, val_acc = validate(model, criterion, test_loader, device, TASK)\n", + "\n", + " train_losses.append(train_loss)\n", + " val_losses.append(val_loss)\n", + " val_accs.append(val_acc)\n", + "\n", + " if (epoch + 1) % 10 == 0:\n", + " print(f\"Epoch [{epoch+1:3d}/{NUM_EPOCHS}] \"\n", + " f\"Train Loss: {train_loss:.4f} | \"\n", + " f\"Val Loss: {val_loss:.4f} | \"\n", + " f\"Val Acc: {val_acc:.4f}\")\n", + "\n", + "print(f\"Done! Final Accuracy: {val_accs[-1]:.4f}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Define device, model, loss, optimizer:\n", + "\n", + "TASK = \"multiclass\"\n", + "\n", + "\n", + "INPUT_DIM = 3*36*36\n", + "HIDDEN_DIM = 14\n", + "OUtPUT_DIM = 1\n", + "LEARNING_RATE = 0.001\n", + "NUM_EPOCHS = 20\n", + "\n", + "criterion = nn.CrossEntropyLoss()\n", + "model = MulticlassNet(INPUT_DIM, HIDDEN_DIM, NUM_CLASSES).to(device)\n", + "optimizer = Adam(model.parameters(), lr=LEARNING_RATE)\n", + "\n", + "train_losses = []\n", + "val_losses = []\n", + "val_accs = []\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Start training for 20 epochs:\n", + "# Run Training\n", + "train_losses = []\n", + "val_losses = []\n", + "\n", + "print('Starting Training...')\n", + "for epoch in range(NUM_EPOCHS):\n", + " # Train one epoch\n", + " train_loss = train_one_epoch(model, optimizer, criterion, train_loader, device)\n", + "\n", + " # Validate\n", + " val_loss = validate(model, criterion, test_loader, device)\n", + "\n", + " train_losses.append(train_loss)\n", + " val_losses.append(val_loss)\n", + "\n", + " if (epoch + 1) % 5 == 0:\n", + " print(\n", + " f'Epoch [{epoch+1}/{num_epochs}], '\n", + " f'Train Loss: {train_loss:.4f}, '\n", + " f'Val Loss: {val_loss:.4f}'\n", + " )\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "\n", + "plt.figure(figsize=(12, 4))\n", + "\n", + "plt.subplot(1, 2, 1)\n", + "plt.plot(train_losses, label='Train Loss')\n", + "plt.plot(val_losses, label='Val Loss')\n", + "plt.xlabel('Epoch')\n", + "plt.ylabel('Loss')\n", + "plt.title('Loss Curves')\n", + "plt.legend()\n", + "\n", + "plt.subplot(1, 2, 2)\n", + "plt.plot(val_accs, label='Val Accuracy', color='green')\n", + "plt.xlabel('Epoch')\n", + "plt.ylabel('Accuracy')\n", + "plt.title('Validation Accuracy')\n", + "plt.legend()\n", + "\n", + "plt.tight_layout()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2 (Bonus): Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/377/Q3.ipynb b/submissions_extracted/377/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..805bf1484a23303d8bc4b4e0e0772087839c3cd9 --- /dev/null +++ b/submissions_extracted/377/Q3.ipynb @@ -0,0 +1,162 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "\n", + "\n", + "# Download latest version\n", + "\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q3-exam-data\")\n", + "\n", + "\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "\n", + "# WISH I HAD TIME TO SOLVE" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/378/Q1.ipynb b/submissions_extracted/378/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..3a13d6abcee5c12387fa333b6941f7008698a3a8 --- /dev/null +++ b/submissions_extracted/378/Q1.ipynb @@ -0,0 +1,248 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q1-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "csv_path = path.join(path, \"Advertising.csv\")\n", + "df_deliver= pd.read_csv(csv_path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "df_deliver.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "df_deliver.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "df_deliver.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "plt.figure(figsize=(15, 10))\n", + "plt.hist(df_deliver, bins=50, edgecolor='black')\n", + "plt.title('price per meals')\n", + "plt.xlabel('km')\n", + "plt.ylabel('Frequency')\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "df_deliver = df_deliver.dropna(subset='Order_ID')" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "import pandas as pd\n", + "import numpy as np\n", + "# Create sample data with missing values\n", + "df = pd.DataFrame({})\n", + "print(\"Original Data:\")\n", + "print(df)\n", + "print(\"\\nMissing values:\")\n", + "print(df.isnull().sum())\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "from sklearn.preprocessing import OneHotEncoder\n", + "colors = [['burger'], ['pizza'], ['coffee'], ['icecream']]\n", + "encoder = OneHotEncoder(sparse_output=False)\n", + "encoded = encoder.fit_transform(colors)\n", + "print(\"Original:\", colors)\n", + "print(\"Encoded:\\n\", encoded)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "import numpy as np\n", + "from sklearn.preprocessing import StandardScaler\n", + "data = np.array([[1, 150, 40],\n", + " [2, 100, 60],\n", + " [3, 300, 80]])\n", + "\n", + "scaler = StandardScaler()\n", + "scaler.fit(data)\n", + "scaled = scaler.fit_transform(data)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 6: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "import numpy as np\n", + "\n", + "from sklearn.model_selection import train_test_split\n", + "X = np.array([[1, 2], [3, 4], [5, 6], [7, 8], [9, 10]])\n", + "y = np.array([0, 1, 0, 1, 0])\n", + "# split\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n", + "print(f\"\\nX_train:\\n{X_train}\")\n", + "print(f\"\\nX_test:\\n{X_test}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:\n", + "#fold\n", + "from sklearn.model_selection import train_test_split\n", + "X, y = X_clf.copy(), y_clf.copy()\n", + "kf = KFold(n_splits=5, shuffle=True, random_state=42)\n", + "print(f\"\\nFold {fold_idx + 1}/{n_splits}\")\n", + "for fold, (train_idx, test_idx) in kfold.split(kf.split(X), start=1):\n", + " X_train, X_test = X.iloc[train_idx], X.iloc[test_idx]\n", + " y_train, y_test = y.iloc[train_idx], y.iloc[test_idx]\n", + " # print shapes\n", + " print(f\"Fold {fold}\")\n", + " print(\" X_train shape:\", X_train.shape)\n", + " print(\" X_test shape :\", X_test.shape)\n", + " print(\" y_train shape:\", y_train.shape)\n", + " print(\" y_test shape :\", y_test.shape)\n", + " print(\"-\" * 25)\n", + "#using randomforest\n", + "model = RandomForestClassifier(n_estimators=100, random_state=42)\n", + "model.fit(scaled, y_train)\n", + "print(\"Random Forest:\")\n", + "#evaluate absulote error\n", + "mae = mean_absolute_error(y_true, y_pred)\n", + "print(f\"MAE: {mae:.2f}\")\n", + "\n", + "#average\n", + "average_losses = np.mean(lr_losses, axis=0)\n", + "plt.figure(figsize=(10, 6))\n", + "plt.plot(average_losses, label='Average Loss')\n", + "plt.xlabel('Iteration')\n", + "plt.ylabel('MAE Loss')\n", + "plt.grid(True, alpha=0.3)\n", + "plt.show()\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/378/Q2.ipynb b/submissions_extracted/378/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..a9d85b33a636029bd34109f167e0736f28a411e2 --- /dev/null +++ b/submissions_extracted/378/Q2.ipynb @@ -0,0 +1,314 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q2-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import os\n", + "import pandas as pd\n", + "import numpy as np\n", + "from PIL import Image\n", + "from sklearn.model_selection import train_test_split\n", + "\n", + "# Load Labels\n", + "labels_df = pd.read_csv(os.path.join(path, \"labels.csv\"))\n", + "img_dir = os.path.join(path, \"images\")\n", + "\n", + "images = []\n", + "ages = []\n", + "\n", + "# Load Images and Resize\n", + "print(\"Loading images...\")\n", + "for index, row in labels_df.iterrows():\n", + " img_name = row.iloc[0]\n", + " age = row.iloc[1]\n", + " img_path = os.path.join(img_dir, img_name)\n", + "\n", + " if os.path.exists(img_path):\n", + " img = Image.open(img_path).convert('RGB')\n", + " img_array = np.array(img) / 255.0 # Normalize pixel values to [0, 1]\n", + " images.append(img_array)\n", + " ages.append(age)\n", + "\n", + "X = np.array(images)\n", + "y = np.array(ages)\n", + "\n", + "# Transpose image dimensions to match PyTorch format (N, C, H, W)\n", + "X = np.transpose(X, (0, 3, 1, 2))\n", + "\n", + "# Split Data\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n", + "\n", + "print(f\"X_train shape: {X_train.shape}\")\n", + "print(f\"X_test shape: {X_test.shape}\")\n", + "print(f\"y_train shape: {y_train.shape}\")\n", + "print(f\"y_test shape: {y_test.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 1. Convert Numpy arrays to PyTorch Tensors\n", + "X_train = torch.tensor(X_train, dtype=torch.float32)\n", + "X_test = torch.tensor(X_test, dtype=torch.float32)\n", + "y_train = torch.tensor(y_train, dtype=torch.float32)\n", + "y_test = torch.tensor(y_test, dtype=torch.float32)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 2. Create TensorDataset objects\n", + "import torch\n", + "train_dataset\n", + "# Create tensors\n", + "X = torch.tensor([1.0, 2.0, 3.0])\n", + "Y = torch.randn(3)\n", + "print(\"X:\", X)\n", + "print(\"Y:\", Y)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 3. Create DataLoaders\n", + "# for training data\n", + "train_loader = DataLoader(\n", + " train_dataset,\n", + " batch_size=32,\n", + " shuffle=True)\n", + "# for test data\n", + "test_loader = DataLoader(\n", + " test_dataset,\n", + " batch_size=32,\n", + " shuffle=False)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 4. Print shape of one batch\n", + "X_batch= next(iter(train_loader))\n", + "print(f\"Training batch input shape: {X_batch.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 5. Display sample images\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your model class here:\n", + "import torch.nn as nn\n", + "class NN4Layer(nn.Module):\n", + " def __init__(self, input_dim, hidden_dim, output_dim):\n", + " super(NN4Layer, self).__init__()\n", + " # First layer\n", + " self.layer1 = nn.Linear(input_dim, hidden_dim)\n", + " # Second layer\n", + " self.layer2 = nn.Linear(hidden_dim, hidden_dim)\n", + " # Third layer\n", + " self.layer3 = nn.Linear(hidden_dim, hidden_dim)\n", + " # Output layer\n", + " self.layer4 = nn.Linear(hidden_dim, output_dim)\n", + " # ReLU activation 4 non-linearity\n", + " self.relu = nn.ReLU()\n", + " # Defines how input data flows through the network\n", + " def forward(self, x):\n", + " # First hidden layer\n", + " a1 = self.relu(self.layer1(x))\n", + " # Second hidden layer\n", + " a2 = self.relu(self.layer2(a1))\n", + " # Third hidden layer\n", + " a3 = self.relu(self.layer3(a2))\n", + " # Output layer (raw scores / logits)\n", + " output = self.layer4(a3)\n", + " return output" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your training loop here:\n", + "def train_one_epoch(model, optimizer, criterion, train_loader):\n", + " # Set the model to training mode\n", + " model.train()\n", + " running_loss = 0.0\n", + " for X_batch, y_batch in train_loader:\n", + " # Forward pass (the outputs)\n", + " outputs = model(X_batch)\n", + " loss = criterion(outputs, y_batch)\n", + " # Backward pasS and optimization\n", + " optimizer.zero_grad()\n", + " loss.backward()\n", + " optimizer.step()\n", + " running_loss += loss.item()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your validation loop here:\n", + "def validate(model, criterion, test_loader):\n", + "#evaluate the model\n", + " model.eval()\n", + " running_loss = 0.0\n", + " correct = 0\n", + " total = 0\n", + " with torch.no_grad():\n", + " # Forward pass\n", + " outputs = model(X_batch)\n", + " loss = criterion(outputs, y_batch)\n", + " running_loss += loss.item()\n", + " # Softmax to get probabilities\n", + " probabilities = F.softmax(outputs, dim=1)\n", + " # classes w/ highest probabilities\n", + " predicted = torch.argmax(probabilities, dim=1)\n", + " # Accuracy calculation\n", + " correct += (predicted == y_batch).sum().item()\n", + " total += y_batch.size(0)\n", + " avg_loss = running_loss / len(test_loader)\n", + " accuracy = correct / total\n", + " return avg_loss, accuracy" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Define device, model, loss, optimizer:\n", + "import torch\n", + "import torch.nn as nn\n", + "linear = nn.Linear(in_features=3, out_features=1)\n", + "x = torch.randn(4, 3)\n", + "y = linear(x)\n", + "print(\"Input shape:\", x.shape)\n", + "print(\"Output shape:\", y.shape)\n", + "#loss\n", + "criterion = nn.CrossEntropyLoss()\n", + "#device\n", + "device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n", + "print(f\"Using device: {device}\")\n", + "\n", + "#optimizer\n", + "optimizer = AdamW(model.parameters(), learning_rate)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Start training for 20 epochs:\n", + "num_epochs = 20\n", + "learning_rate = 0.001\n", + "input_dim = X_train.shape[1]\n", + "hidden_dim = 10\n", + "model =NN2Layer(input_dim, hidden_dim).to(device)\n", + "criterion = nn.BCELoss()\n", + "optimizer = AdamW(model.parameters(), lr=learning_rate)\n", + "# Run Training\n", + "train_losses = []\n", + "val_losses = []\n", + "val_accuracies = []\n", + "print('Starting Training...')\n", + "for epoch in range(num_epochs):\n", + " # Train one epoch\n", + " train_loss = train_one_epoch(model, optimizer, criterion, train_loader, device)\n", + " # Validate\n", + " val_loss, val_accuracy = validate(model, criterion, test_loader, device)\n", + " train_losses.append(train_loss)\n", + " val_losses.append(val_loss)\n", + " val_accuracies.append(val_accuracy)\n", + " if (epoch + 1) % 5 == 0:\n", + " print(f'Epoch [{epoch+1}/{num_epochs}], Train Loss: {train_loss:.4f}, Val Loss: {val_loss:.4f}, Val Accuracy: {val_accuracy:.4f}')\n", + "print('Done!')" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "plt.figure(figsize=(7, 5))\n", + "plt.plot(train_losses, label='T Loss')\n", + "plt.plot(val_losses, label='Val Loss')\n", + "plt.title('Loss over Epochs')\n", + "plt.xlabel('Epoch')\n", + "plt.ylabel('Loss')\n", + "plt.legend()\n", + "plt.tight_layout()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2 (Bonus): Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/378/Q3.ipynb b/submissions_extracted/378/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..448b942e43c92afa32e3099e4ddf0f2debca28ad --- /dev/null +++ b/submissions_extracted/378/Q3.ipynb @@ -0,0 +1,166 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "\n", + "\n", + "# Download latest version\n", + "\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q3-exam-data\")\n", + "\n", + "\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "import pandas as pd\n", + "csv_path = path.join(path, \"updated_ai_dataset.csv\")\n", + "df = pd.read_csv(csv_path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "df.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "df.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/379/Q1.ipynb b/submissions_extracted/379/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..d3ca90e56ced2dcd1b41b13ebb736dab951af104 --- /dev/null +++ b/submissions_extracted/379/Q1.ipynb @@ -0,0 +1,281 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "import numpy as np\n", + "import os\n", + "import pandas as pd\n", + "import matplotlib.pyplot as plt\n", + "\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q1-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "Q1_data = os.path.join(path, \"Q1_data.csv\")\n", + "df = pd.read_csv(Q1_data)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "df.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "df.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "def check_target_distribution(df, Delivery_Time):\n", + "\n", + " df[Delivery_Time].hist(bins=30, edgecolor='black')\n", + "\n", + " plt.title(f\"Target Distribution ({Delivery_Time})\")\n", + "\n", + " plt.xlabel(Delivery_Time)\n", + "\n", + "\n", + " plt.ylabel(\"Frequency\")\n", + "\n", + "\n", + " plt.grid(False)\n", + "\n", + " plt.show()\n", + "\n", + "check_target_distribution(df, \"Delivery_Time\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "df = df.drop(columns=\"Order_ID\", axis=1)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "def check_missing_values(df):\n", + "\n", + " missing_values = df.isnull().sum()\n", + "\n", + " print(\"Missing Values per Column:\")\n", + " # Label for clarity\n", + "\n", + " print(missing_values[missing_values > 0])\n", + "\n", + " if missing_values.any():\n", + "\n", + " print(\"\\nHandle Missing Values as needed.\")\n", + " else:\n", + " print(\"\\nNo Missing Values Found.\")\n", + "\n", + "check_missing_values(df)\n", + "\n", + "# Define stat columns\n", + "stat_cols = ['Distance_km'\t,'Weather'\t,'Traffic_Level'\t,'Time_of_Day'\t,'Vehicle_Type'\t,'Preparation_Time_min'\t,'Courier_Experience_yrs','Delivery_Time']\n", + "\n", + "# Drop rows with missing stat values\n", + "df_clean = df.dropna(subset=stat_cols).copy()\n", + "print(f\"Shape after cleaning: {df_clean.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "def check_duplicates(df):\n", + "\n", + " duplicates = df.duplicated().sum()\n", + "\n", + " print(f\"Number of Duplicate Samples: {duplicates}\")\n", + "\n", + " if duplicates > 0:\n", + " print(\"Dropping Duplicates...\")\n", + "\n", + " df.drop_duplicates(inplace=True)\n", + "\n", + " print(\"Duplicates Dropped.\")\n", + " else:\n", + " print(\"No Duplicate Samples Found.\")\n", + "\n", + "\n", + "\n", + "check_duplicates(df)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "from sklearn.preprocessing import LabelEncoder\n", + "\n", + "categorical_cols = ['Weather','Traffic_Level','Time_of_Day','Vehicle_Type']\n", + "for col in categorical_cols:\n", + " le = LabelEncoder()\n", + " df_clean[col] = le.fit_transform(df_clean[col].astype(str))\n", + "\n", + "df_clean.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "df = df_clean\n", + "from sklearn.preprocessing import StandardScaler\n", + "\n", + "numerical_cols = df.select_dtypes(include=[\"int64\", \"float64\"]).columns.drop(\"Delivery_Time\")\n", + "\n", + "scaler = StandardScaler()\n", + "df[numerical_cols] = scaler.fit_transform(df[numerical_cols])\n", + "df.head()\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 6: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "X = df.drop(\"Delivery_Time\", axis=1).astype(float)\n", + "y = df['Delivery_Time'].astype(float)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "from sklearn.model_selection import KFold\n", + "from sklearn.metrics import mean_squared_error as sklearn_mse, mean_absolute_error, r2_score\n", + "# Task 2,3,4,5: Write your code here:\n", + "n_splits = 5 # K=5 Folds\n", + "\n", + "# 5-Fold Cross-Validation, shuffled\n", + "kf = KFold(n_splits=n_splits, shuffle=True, random_state=42)\n", + "\n", + "# Storage for linear regression results for each fold\n", + "lr_losses = []\n", + "lr_mse = []\n", + "lr_rmse = []\n", + "lr_r2 = []\n", + "\n", + "for fold_idx, (train_index, test_index) in enumerate(kf.split(X)):\n", + " print(f\"\\nFold {fold_idx + 1}/{n_splits}\")\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", + "from sklearn.ensemble import RandomForestRegressor\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/379/Q2.ipynb b/submissions_extracted/379/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..8265fb7760e09be1aa8a23818da7adf7dbffa9c8 --- /dev/null +++ b/submissions_extracted/379/Q2.ipynb @@ -0,0 +1,192 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q2-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import os\n", + "import pandas as pd\n", + "import numpy as np\n", + "from PIL import Image\n", + "from sklearn.model_selection import train_test_split\n", + "\n", + "# Load Labels\n", + "labels_df = pd.read_csv(os.path.join(path, \"labels.csv\"))\n", + "img_dir = os.path.join(path, \"images\")\n", + "\n", + "images = []\n", + "ages = []\n", + "\n", + "# Load Images and Resize\n", + "print(\"Loading images...\")\n", + "for index, row in labels_df.iterrows():\n", + " img_name = row.iloc[0]\n", + " age = row.iloc[1]\n", + " img_path = os.path.join(img_dir, img_name)\n", + "\n", + " if os.path.exists(img_path):\n", + " img = Image.open(img_path).convert('RGB')\n", + " img_array = np.array(img) / 255.0 # Normalize pixel values to [0, 1]\n", + " images.append(img_array)\n", + " ages.append(age)\n", + "\n", + "X = np.array(images)\n", + "y = np.array(ages)\n", + "\n", + "# Transpose image dimensions to match PyTorch format (N, C, H, W)\n", + "X = np.transpose(X, (0, 3, 1, 2))\n", + "\n", + "# Split Data\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n", + "\n", + "print(f\"X_train shape: {X_train.shape}\")\n", + "print(f\"X_test shape: {X_test.shape}\")\n", + "print(f\"y_train shape: {y_train.shape}\")\n", + "print(f\"y_test shape: {y_test.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 1. Convert Numpy arrays to PyTorch Tensors\n", + "from torchvision.transforms.functional import to_tensor\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 2. Create TensorDataset objects\n", + "\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 3. Create DataLoaders\n", + "\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 4. Print shape of one batch\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 5. Display sample images\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your model class here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your training loop here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your validation loop here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Define device, model, loss, optimizer:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Start training for 20 epochs:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2 (Bonus): Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/379/Q3.ipynb b/submissions_extracted/379/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..c97832709061629f03a86d1f40306ca8a3e2a744 --- /dev/null +++ b/submissions_extracted/379/Q3.ipynb @@ -0,0 +1,160 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "\n", + "\n", + "# Download latest version\n", + "\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q3-exam-data\")\n", + "\n", + "\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/38/Q1.ipynb b/submissions_extracted/38/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..8deee4ff87b964f3abd1655b8d9604941bfbaf28 --- /dev/null +++ b/submissions_extracted/38/Q1.ipynb @@ -0,0 +1,237 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "import pandas as pd\n", + "import os\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q1-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "csv = os.path.join(path, \"Q1_data.csv\")\n", + "df = pd.read_csv(csv)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "df.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "df.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "import matplotlib.pyplot as plt\n", + "\n", + "plt.figure(figsize=(10, 5))\n", + "plt.hist(df['Delivery_Time'].dropna(), bins=30, edgecolor='black')\n", + "plt.title('Delivery Time')\n", + "plt.xlabel('Preparation Time')\n", + "plt.ylabel('Distance')\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "df_clean = df.drop(\"Order_ID\", axis=1)\n", + "df_clean" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "df_clean = df_clean.dropna()\n", + "df_clean" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "print(\"Checking for duplicate rows\")\n", + "duplicate_rows = df_clean.duplicated().sum()\n", + "if duplicate_rows > 0:\n", + " print(f\"Found {duplicate_rows} duplicate rows. Removing them\")\n", + " df_clean.drop_duplicates(inplace=True)\n", + " print(\"Duplicate rows removed.\")\n", + "else:\n", + " print(\"No duplicate rows found.\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "from sklearn.preprocessing import OneHotEncoder, StandardScaler, LabelEncoder\n", + "from sklearn.model_selection import train_test_split, KFold\n", + "\n", + "X = df.drop('Delivery_Time', axis=1)\n", + "y = df[\"Delivery_Time\"]\n", + "\n", + "label_encoder = LabelEncoder()\n", + "y_encoded = label_encoder.fit_transform(y)\n", + "\n", + "onehot_encoder = OneHotEncoder(handle_unknown='ignore', sparse_output=False)\n", + "X_encoded = pd.DataFrame(onehot_encoder.fit_transform(X), columns=onehot_encoder.get_feature_names_out(X.columns))\n", + "X_encoded" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "scaler = StandardScaler()\n", + "X_train, X_test, y_train, y_test = train_test_split(X_encoded, y_encoded, test_size=0.3, random_state=42)\n", + "\n", + "X_train_scaled = scaler.fit_transform(X_train)\n", + "X_test_scaled = scaler.transform(X_test)\n", + "\n", + "print(f\"\\nScaled ranges - Min: {X_train_scaled.min():.2f}, Max: {X_train_scaled.max():.2f}\")\n", + "pd.DataFrame(X_train_scaled, columns=X_train.columns).head(3)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 6: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "X_train, X_test, y_train, y_test = train_test_split(X_encoded, y_encoded, test_size=0.3, random_state=42)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:\n", + "from sklearn.ensemble import RandomForestRegressor\n", + "\n", + "model = RandomForestRegressor(n_estimators=100, max_depth=20, random_state=42, n_jobs=-1)\n", + "model.fit(X_train_scaled, y_train)\n", + "print(\"Model trained!\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "importance = pd.DataFrame({\n", + " 'feature': \"Delevery_Time\",\n", + " 'importance': model.feature_importances_\n", + "}).sort_values('importance', ascending=False)\n", + "\n", + "plt.figure(figsize=(10, 6))\n", + "plt.barh(importance['feature'], importance['importance'], color='blue')\n", + "plt.xlabel('Importance')\n", + "plt.title('Feature Importance')\n", + "plt.gca().invert_yaxis()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/38/Q2.ipynb b/submissions_extracted/38/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..c8937ff34d658b6340ef5c82e1d71e84083e0ea8 --- /dev/null +++ b/submissions_extracted/38/Q2.ipynb @@ -0,0 +1,192 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q2-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import os\n", + "import pandas as pd\n", + "import numpy as np\n", + "from PIL import Image\n", + "from sklearn.model_selection import train_test_split\n", + "\n", + "# Load Labels\n", + "labels_df = pd.read_csv(os.path.join(path, \"labels.csv\"))\n", + "img_dir = os.path.join(path, \"images\")\n", + "\n", + "images = []\n", + "ages = []\n", + "\n", + "# Load Images and Resize\n", + "print(\"Loading images...\")\n", + "for index, row in labels_df.iterrows():\n", + " img_name = row.iloc[0]\n", + " age = row.iloc[1]\n", + " img_path = os.path.join(img_dir, img_name)\n", + "\n", + " if os.path.exists(img_path):\n", + " img = Image.open(img_path).convert('RGB')\n", + " img_array = np.array(img) / 255.0 # Normalize pixel values to [0, 1]\n", + " images.append(img_array)\n", + " ages.append(age)\n", + "\n", + "X = np.array(images)\n", + "y = np.array(ages)\n", + "\n", + "# Transpose image dimensions to match PyTorch format (N, C, H, W)\n", + "X = np.transpose(X, (0, 3, 1, 2))\n", + "\n", + "# Split Data\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n", + "\n", + "print(f\"X_train shape: {X_train.shape}\")\n", + "print(f\"X_test shape: {X_test.shape}\")\n", + "print(f\"y_train shape: {y_train.shape}\")\n", + "print(f\"y_test shape: {y_test.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 1. Convert Numpy arrays to PyTorch Tensors\n", + "\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 2. Create TensorDataset objects\n", + "\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 3. Create DataLoaders\n", + "\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 4. Print shape of one batch\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 5. Display sample images\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your model class here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your training loop here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your validation loop here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Define device, model, loss, optimizer:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Start training for 20 epochs:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2 (Bonus): Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/38/Q3.ipynb b/submissions_extracted/38/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..f98eb0c8726a72c79aab130a1a05bffdd511f179 --- /dev/null +++ b/submissions_extracted/38/Q3.ipynb @@ -0,0 +1,201 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "\n", + "\n", + "# Download latest version\n", + "\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q3-exam-data\")\n", + "\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "import os\n", + "import pandas as pd\n", + "\n", + "csv = os.path.join(path, \"Q3_data.csv\")\n", + "df = pd.read_csv(csv)\n", + "df" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "df.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "df.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "df_clean = df.dropna()\n", + "df_clean" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "print(\"Checking for duplicate rows\")\n", + "duplicate_rows = df_clean.duplicated().sum()\n", + "if duplicate_rows > 0:\n", + " print(f\"Found {duplicate_rows} duplicate rows. Removing them\")\n", + " df_clean.drop_duplicates(inplace=True)\n", + " print(\"Duplicate rows removed.\")\n", + "else:\n", + " print(\"No duplicate rows found.\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "from sklearn.preprocessing import OneHotEncoder, StandardScaler, LabelEncoder\n", + "from sklearn.model_selection import train_test_split, KFold\n", + "\n", + "X = df.drop('Target', axis=1)\n", + "y = df[\"Target\"]\n", + "\n", + "label_encoder = LabelEncoder()\n", + "y_encoded = label_encoder.fit_transform(y)\n", + "\n", + "onehot_encoder = OneHotEncoder(handle_unknown='ignore', sparse_output=False)\n", + "X_encoded = pd.DataFrame(onehot_encoder.fit_transform(X), columns=onehot_encoder.get_feature_names_out(X.columns))\n", + "X_encoded" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "from sklearn.preprocessing import StandardScaler\n", + "from sklearn.model_selection import train_test_split\n", + "\n", + "scaler = StandardScaler()\n", + "X_train, X_test, y_train, y_test = train_test_split(X_encoded, y_encoded, test_size=0.3, random_state=42)\n", + "\n", + "X_train_scaled = scaler.fit_transform(X_train)\n", + "X_test_scaled = scaler.transform(X_test)\n", + "\n", + "print(f\"\\nScaled ranges - Min: {X_train_scaled.min():.2f}, Max: {X_train_scaled.max():.2f}\")\n", + "pd.DataFrame(X_train_scaled, columns=X_train.columns).head(3)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/380/Q1.ipynb b/submissions_extracted/380/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..fe39e490c3593d96fd1477e0fe8f4d8e2870a630 --- /dev/null +++ b/submissions_extracted/380/Q1.ipynb @@ -0,0 +1,205 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import numpy as np\n", + "import pandas as pd\n", + "import matplotlib.pyplot as plt\n", + "import os\n", + "import kagglehub\n", + "from sklearn.model_selection import train_test_split, KFold\n", + "from sklearn.preprocessing import StandardScaler, LabelEncoder\n", + "from sklearn.ensemble import RandomForestRegressor\n", + "from sklearn.metrics import mean_absolute_error, mean_squared_error\n", + "import warnings\n", + "warnings.filterwarnings('ignore')" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path =kagglehub.dataset_download(\"ANON_OWNER/q1-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: =\n", + "delivery = os.path.join(path, 'Q1_data.csv')\n", + "delivry = os.path.join(path, 'Q1_data.csv')\n", + "df = pd.read_csv(delivery)\n", + "print(f\"Dataset shape: {df.shape}\")\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2:\n", + "df.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3:\n", + "df.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4:\n", + "plt.figure(figsize=(10, 5))\n", + "plt.hist(df['Delivery_Time'].dropna(), bins=50, edgecolor='black')\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1:\n", + "df.drop(columns=['Order_ID'])\n", + "df_clean = df[cols].copy()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2:\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3:\n", + "for col in ['Distance_km', 'Weather', 'Traffic_Level', 'Time_of_Day'], df_clean[col] = df_clean[col].fillna('unknown')" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 6: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/380/Q2.ipynb b/submissions_extracted/380/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..c8937ff34d658b6340ef5c82e1d71e84083e0ea8 --- /dev/null +++ b/submissions_extracted/380/Q2.ipynb @@ -0,0 +1,192 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q2-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import os\n", + "import pandas as pd\n", + "import numpy as np\n", + "from PIL import Image\n", + "from sklearn.model_selection import train_test_split\n", + "\n", + "# Load Labels\n", + "labels_df = pd.read_csv(os.path.join(path, \"labels.csv\"))\n", + "img_dir = os.path.join(path, \"images\")\n", + "\n", + "images = []\n", + "ages = []\n", + "\n", + "# Load Images and Resize\n", + "print(\"Loading images...\")\n", + "for index, row in labels_df.iterrows():\n", + " img_name = row.iloc[0]\n", + " age = row.iloc[1]\n", + " img_path = os.path.join(img_dir, img_name)\n", + "\n", + " if os.path.exists(img_path):\n", + " img = Image.open(img_path).convert('RGB')\n", + " img_array = np.array(img) / 255.0 # Normalize pixel values to [0, 1]\n", + " images.append(img_array)\n", + " ages.append(age)\n", + "\n", + "X = np.array(images)\n", + "y = np.array(ages)\n", + "\n", + "# Transpose image dimensions to match PyTorch format (N, C, H, W)\n", + "X = np.transpose(X, (0, 3, 1, 2))\n", + "\n", + "# Split Data\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n", + "\n", + "print(f\"X_train shape: {X_train.shape}\")\n", + "print(f\"X_test shape: {X_test.shape}\")\n", + "print(f\"y_train shape: {y_train.shape}\")\n", + "print(f\"y_test shape: {y_test.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 1. Convert Numpy arrays to PyTorch Tensors\n", + "\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 2. Create TensorDataset objects\n", + "\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 3. Create DataLoaders\n", + "\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 4. Print shape of one batch\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 5. Display sample images\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your model class here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your training loop here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your validation loop here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Define device, model, loss, optimizer:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Start training for 20 epochs:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2 (Bonus): Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/380/Q3.ipynb b/submissions_extracted/380/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..b03811df2707d68febaff2f842a3fca1bf16d2ea --- /dev/null +++ b/submissions_extracted/380/Q3.ipynb @@ -0,0 +1,183 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import numpy as np\n", + "import pandas as pd\n", + "import matplotlib.pyplot as plt\n", + "import os\n", + "import kagglehub\n", + "from sklearn.model_selection import train_test_split, KFold\n", + "from sklearn.preprocessing import StandardScaler, LabelEncoder\n", + "from sklearn.ensemble import RandomForestRegressor\n", + "from sklearn.metrics import mean_absolute_error, mean_squared_error\n", + "import warnings\n", + "warnings.filterwarnings('ignore')" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "\n", + "\n", + "# Download latest version\n", + "\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q3-exam-data\")\n", + "\n", + "\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "delivery = os.path.join(path, 'Q3_data.csv')\n", + "delivry = os.path.join(path, 'Q3_data.csv')\n", + "df = pd.read_csv(delivery)\n", + "print(f\"Dataset shape: {df.shape}\")\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "df.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/381/Q1.ipynb b/submissions_extracted/381/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..a00c4d133d73b2b35b24c50ac4cb1e14c396fc53 --- /dev/null +++ b/submissions_extracted/381/Q1.ipynb @@ -0,0 +1,221 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q1-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "import os\n", + "import pandas as pd\n", + "# Load the dataset\n", + "data_path = os.path.join(path, 'Q1_data.csv')\n", + "df_data = pd.read_csv(data_path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "print(f\"Dataset shape: {df_data.shape}\")\n", + "df_data.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "df_data.info()\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "df_data.describe()\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "#Plot the target distribution (delivery_time)\n", + "import matplotlib.pyplot as plt\n", + "\n", + "plt.figure(figsize=(10, 5))\n", + "plt.hist(df_data['Delivery_Time'].dropna(), bins=50, edgecolor='black')\n", + "plt.title('Distribution Delivery_Time ')\n", + "plt.xlabel('Delivery_Time')\n", + "plt.ylabel('Frequency')\n", + "plt.show()\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "\n", + "df_data = df_data.drop(columns=\"Order_ID\", axis=1)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "# Analyze missing values\n", + "missing_percentage = (df_data.isnull().sum() / len(df_data)) * 100\n", + "missing_data = pd.DataFrame({\n", + " 'Column': missing_percentage.index,\n", + " 'Missing_Percentage': missing_percentage.values\n", + "})\n", + "missing_data = missing_data[missing_data['Missing_Percentage'] > 0].sort_values('Missing_Percentage', ascending=False)\n", + "\n", + "print(\"Missing Data Analysis:\")\n", + "missing_data.head(10)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "cols = ['Distance_km','Weather','Traffic_Level','Time_of_Day','Vehicle_Type','Preparation_Time_min','Courier_Experience_yrs','Delivery_Time']\n", + "df_clean = df_data[cols].copy()\n", + "print(f\"Before: {df_clean.shape}\")\n", + "df_clean = df_clean.dropna(subset=['Delivery_Time','Weather','Traffic_Level','Time_of_Day','Courier_Experience_yrs'])\n", + "print(f\"After dropping missing values: {df_clean.shape}\")\n", + "\n", + "df_clean.info()\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "from sklearn.model_selection import train_test_split, KFold\n", + "from sklearn.preprocessing import StandardScaler, LabelEncoder" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 6: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/381/Q2.ipynb b/submissions_extracted/381/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..10b4863b340a728463010df7160d34ebe9258c9b --- /dev/null +++ b/submissions_extracted/381/Q2.ipynb @@ -0,0 +1,423 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q2-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import os\n", + "import pandas as pd\n", + "import numpy as np\n", + "from PIL import Image\n", + "from sklearn.model_selection import train_test_split\n", + "\n", + "# Load Labels\n", + "labels_df = pd.read_csv(os.path.join(path, \"labels.csv\"))\n", + "img_dir = os.path.join(path, \"images\")\n", + "\n", + "images = []\n", + "ages = []\n", + "\n", + "# Load Images and Resize\n", + "print(\"Loading images...\")\n", + "for index, row in labels_df.iterrows():\n", + " img_name = row.iloc[0]\n", + " age = row.iloc[1]\n", + " img_path = os.path.join(img_dir, img_name)\n", + "\n", + " if os.path.exists(img_path):\n", + " img = Image.open(img_path).convert('RGB')\n", + " img_array = np.array(img) / 255.0 # Normalize pixel values to [0, 1]\n", + " images.append(img_array)\n", + " ages.append(age)\n", + "\n", + "X = np.array(images)\n", + "y = np.array(ages)\n", + "\n", + "# Transpose image dimensions to match PyTorch format (N, C, H, W)\n", + "X = np.transpose(X, (0, 3, 1, 2))\n", + "\n", + "# Split Data\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n", + "\n", + "print(f\"X_train shape: {X_train.shape}\")\n", + "print(f\"X_test shape: {X_test.shape}\")\n", + "print(f\"y_train shape: {y_train.shape}\")\n", + "print(f\"y_test shape: {y_test.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 1. Convert Numpy arrays to PyTorch Tensors\n", + "from sklearn.datasets import load_breast_cancer\n", + "from sklearn.model_selection import train_test_split\n", + "from sklearn.preprocessing import StandardScaler\n", + "from torch.utils.data import TensorDataset\n", + "from torch.utils.data import DataLoader\n", + "import torch\n", + "\n", + "# load data\n", + "data = load_breast_cancer()\n", + "X = data.data\n", + "y = data.target\n", + "\n", + "# Split the dataset into training and testing sets\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42, stratify=y)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 2. Create TensorDataset objects\n", + "\n", + "# Standardize the data\n", + "scaler = StandardScaler()\n", + "X_train = scaler.fit_transform(X_train)\n", + "X_test = scaler.transform(X_test)\n", + "\n", + "# transform to tensors\n", + "X_train = torch.tensor(X_train, dtype=torch.float32)\n", + "X_test = torch.tensor(X_test, dtype=torch.float32)\n", + "y_train = torch.tensor(y_train, dtype=torch.float32)\n", + "y_test = torch.tensor(y_test, dtype=torch.float32)\n", + "\n", + "\n", + "# TensorDataset pairs input features (X) with their corresponding labels (y)\n", + "# Each item in the dataset is returned as (X[i], y[i])\n", + "train_dataset = TensorDataset(X_train, y_train)\n", + "test_dataset = TensorDataset(X_test, y_test)\n", + "\n", + "# Access a single sample from the dataset\n", + "# This helps verify the shape of one data sample\n", + "first_sample, _ = train_dataset[0]\n", + "print(f\"Shape of one sample: {first_sample.shape}\")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 3. Create DataLoaders\n", + "\n", + "from torch.utils.data import DataLoader\n", + "\n", + "# DataLoader for training data\n", + "train_loader = DataLoader(\n", + " train_dataset,\n", + " batch_size=32,\n", + " shuffle=True,\n", + " num_workers=2\n", + ")\n", + "# DataLoader for test/validation data\n", + "test_loader = DataLoader(\n", + " test_dataset,\n", + " batch_size=32,\n", + " shuffle=False,\n", + " num_workers=2\n", + ")\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 4. Print shape of one batch\n", + "\n", + "# Get the first batch from the training DataLoader\n", + "X_batch, y_batch = next(iter(train_loader))\n", + "print(f\"Training batch input shape: {X_batch.shape}\")\n", + "print(f\"Training batch labels shape: {y_batch.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 5. Display sample images\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your model class here:\n", + "import torch.nn as nn\n", + "class NN4Layer(nn.Module):\n", + "\n", + " def __init__(self, input_dim, hidden_dim, output_dim):\n", + " super(NN4Layer, self).__init__()\n", + "\n", + " # First linear layer: input features -> hidden layer\n", + " self.layer1 = nn.Linear(input_dim, hidden_dim)\n", + "\n", + " # Second linear layer: hidden layer -> hidden layer\n", + " self.layer2 = nn.Linear(hidden_dim, hidden_dim)\n", + "\n", + " # Output layer: hidden layer -> number of classes (logits)\n", + " self.layer3 = nn.Linear(hidden_dim, output_dim)\n", + "\n", + " self.layer4 = nn.linear(hidden_dim, output_dim)\n", + "\n", + " # ReLU activation for non-linearity\n", + " self.relu = nn.ReLU()\n", + "\n", + " # Defines how input data flows through the network\n", + " def forward(self, x):\n", + " # First hidden layer\n", + " z1 = self.layer1(x)\n", + " a1 = self.relu(z1)\n", + "\n", + " # Second hidden layer\n", + " z2 = self.layer2(a1)\n", + " a2 = self.relu(z2)\n", + "\n", + " z3 = self.layer3(a2)\n", + " a3 = self.relu(z3)\n", + "\n", + " # Output layer (raw scores / logits)\n", + " output = self.layer4(a3) # there is something missing here, remember? :)\n", + "\n", + " return output\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your training loop here:\n", + "def train_one_epoch(model, optimizer, criterion, train_loader, device):\n", + " # Set the model to training mode\n", + " model.train()\n", + "\n", + " running_loss = 0.0\n", + "\n", + " for X_batch, y_batch in train_loader:\n", + " # Move batch to the selected device\n", + " X_batch = X_batch.to(device)\n", + " y_batch = y_batch.view(-1, 1).to(device)\n", + "\n", + " # Forward pass\n", + " outputs = model(X_batch)\n", + " loss = criterion(outputs, y_batch)\n", + "\n", + " # Backward pass & optimization\n", + " optimizer.zero_grad() # Clear previous gradients\n", + " loss.backward() # Compute gradients\n", + " optimizer.step() # Update model parameters\n", + "\n", + " running_loss += loss.item()\n", + "\n", + " # Average loss over all batches\n", + " avg_loss = running_loss / len(train_loader)\n", + "\n", + " return avg_loss" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your validation loop here:\n", + "def validate(model, criterion, test_loader, device):\n", + " # Set the model to evaluation mode\n", + " model.eval()\n", + "\n", + " running_loss = 0.0\n", + " correct = 0\n", + " total = 0\n", + "\n", + " with torch.no_grad(): # Disable gradient computation\n", + " for X_batch, y_batch in test_loader:\n", + " # Move batch to the selected device\n", + " X_batch = X_batch.to(device)\n", + " y_batch = y_batch.view(-1, 1).to(device)\n", + "\n", + " # Forward pass\n", + " outputs = model(X_batch)\n", + " loss = criterion(outputs, y_batch)\n", + " running_loss += loss.item()\n", + "\n", + " # Binary predictions\n", + " predicted = (outputs > 0.5).float()\n", + "\n", + " # Accuracy calculation\n", + " correct += (predicted == y_batch).sum().item()\n", + " total += y_batch.size(0)\n", + "\n", + " avg_loss = running_loss / len(test_loader)\n", + " accuracy = correct / total\n", + "\n", + " return avg_loss, accuracy" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Define device, model, loss, optimizer:\n", + "import torch\n", + "import torch.nn as nn\n", + "\n", + "# Create a linear layer: 3 input features -> 1 output\n", + "linear = nn.Linear(in_features=3, out_features=1)\n", + "\n", + "# Example input: batch of 4 samples, each with 3 features\n", + "x = torch.randn(4, 3)\n", + "\n", + "# Forward through the layer\n", + "y = linear(x)\n", + "\n", + "print(\"Input shape:\", x.shape) # torch.Size([4, 3])\n", + "print(\"Output shape:\", y.shape) # torch.Size([4, 1])\n", + "# Automatically select CPU or GPU\n", + "device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n", + "\n", + "# Create a tensor and move it to GPU\n", + "x_gpu = x.to(device)\n", + "print(x_gpu.device) # Output: cuda:0 (if GPU is available) or cpu\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import torch\n", + "import torch.nn as nn\n", + "from torch.optim import Adam\n", + "import matplotlib.pyplot as plt\n", + "from sklearn.datasets import load_breast_cancer\n", + "from sklearn.model_selection import train_test_split\n", + "from sklearn.preprocessing import StandardScaler\n", + "from torch.utils.data import TensorDataset\n", + "from torch.utils.data import DataLoader" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Start training for 20 epochs:\n", + "\n", + "# Device configuration\n", + "device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\n", + "print(f\"Using device: {device}\")\n", + "\n", + "num_epochs = 20\n", + "learning_rate = 0.001\n", + "\n", + "# Model, Criterion, Optimizer\n", + "input_dim = X_train.shape[1]\n", + "hidden_dim = 10\n", + "model =NN4Layer(input_dim, hidden_dim,output_dim=2).to(device)\n", + "criterion = nn.BCELoss()\n", + "optimizer = Adam(model.parameters(), lr=learning_rate)\n", + "\n", + "\n", + "# Run Training\n", + "train_losses = []\n", + "val_losses = []\n", + "val_accuracies = []\n", + "\n", + "print('Starting Training...')\n", + "for epoch in range(num_epochs):\n", + " # Train one epoch\n", + " train_loss = train_one_epoch(model, optimizer, criterion, train_loader, device)\n", + "\n", + " # Validate\n", + " val_loss, val_accuracy = validate(model, criterion, test_loader, device)\n", + "\n", + " train_losses.append(train_loss)\n", + " val_losses.append(val_loss)\n", + " val_accuracies.append(val_accuracy)\n", + "\n", + " if (epoch + 1) % 5 == 0:\n", + " print(f'Epoch [{epoch+1}/{num_epochs}], Train Loss: {train_loss:.4f}, Val Loss: {val_loss:.4f}, Val Accuracy: {val_accuracy:.4f}')\n", + "\n", + "print('Training Complete!')" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "# Plotting results\n", + "plt.figure(figsize=(7, 5))\n", + "\n", + "plt.plot(train_losses, label='Train Loss')\n", + "plt.plot(val_losses, label='Validation Loss')\n", + "plt.title('Loss over Epochs')\n", + "plt.xlabel('Epoch')\n", + "plt.ylabel('Loss')\n", + "plt.legend()\n", + "\n", + "plt.tight_layout()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2 (Bonus): Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/381/Q3.ipynb b/submissions_extracted/381/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..9775947f583f61688302f412143a61473f34b2bb --- /dev/null +++ b/submissions_extracted/381/Q3.ipynb @@ -0,0 +1,189 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "\n", + "\n", + "# Download latest version\n", + "\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q3-exam-data\")\n", + "\n", + "\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "import os\n", + "import pandas as pd\n", + "# Load the dataset\n", + "data_path = os.path.join(path, 'Q3_data.csv')\n", + "df_data = pd.read_csv(data_path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "print(f\"Dataset shape: {df_data.shape}\")\n", + "df_data.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "df_data.info()\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "df_data.describe()\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "# Analyze missing values\n", + "missing_percentage = (df_data.isnull().sum() / len(df_data)) * 100\n", + "missing_data = pd.DataFrame({\n", + " 'Column': missing_percentage.index,\n", + " 'Missing_Percentage': missing_percentage.values\n", + "})\n", + "missing_data = missing_data[missing_data['Missing_Percentage'] > 0].sort_values('Missing_Percentage', ascending=False)\n", + "\n", + "print(\"Missing Data Analysis:\")\n", + "missing_data.head(10)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "df_data.dropna(subset=['D_87','D_88','B_39','D_110','D_111','D_108','B_42','D_73','D_135','D_136'])\n", + "\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "from sklearn.preprocessing import StandardScaler\n", + "\n", + "numerical_cols = df_data.select_dtypes(include=[\"int64\", \"float64\"]).columns.drop(\"\") # DON'T SCALE THE TARGET\n", + "\n", + "scaler = StandardScaler()\n", + "df_data[numerical_cols] = scaler.fit_transform(df_data[numerical_cols])\n", + "df_data.head()\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/382/Q1.ipynb b/submissions_extracted/382/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..40f11315c04a2f0c91a2ad344e42bcdd2bf76793 --- /dev/null +++ b/submissions_extracted/382/Q1.ipynb @@ -0,0 +1,227 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "import numpy as np\n", + "import pandas as pd\n", + "import matplotlib.pyplot as plt\n", + "import os\n", + "from sklearn.model_selection import train_test_split, StratifiedKFold, cross_val_score\n", + "from sklearn.preprocessing import StandardScaler, LabelEncoder\n", + "from sklearn.ensemble import RandomForestClassifier\n", + "from sklearn.metrics import classification_report, confusion_matrix, accuracy_score\n", + "from sklearn.preprocessing import OneHotEncoder\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q1-exam-data\")\n", + "\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "delivery_path=os.path.join(path,\"Q1_data.csv\")\n", + "df_delivery=pd.read_csv(delivery_path)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "df_delivery.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "df_delivery.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "df_delivery.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "plt.figure(figsize=(10,5))\n", + "plt.hist(df_delivery[\"Delivery_Time\"].dropna(),bins=50,edgecolor='black')\n", + "plt.title('Delivery Time Distribution')\n", + "plt.xlabel('Delivery Time')\n", + "plt.ylabel('Frequancy')\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "missing_percentage=(df_delivery.isnull().sum()/len(df_delivery))*100\n", + "missing_values=pd.DataFrame({'Column':missing_percentage.index,\"Missing_percentage\":missing_percentage.values})\n", + "missing_values=missing_values[missing_values['Missing_percentage'] > 0].sort_values(\"Missing_percentage\",ascending=False)\n", + "missing_values.head()\n", + "subset1=['Weather','Traffic_Level','Time_of_Day','Courier_Experience_yrs']\n", + "\n", + "df_clean=df_delivery.dropna(subset=subset1)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "duplicate=df_clean.duplicated().sum()\n", + "print(duplicate)\n", + "df_clean.drop_duplicates(inplace=True)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "categorical=df_clean.select_dtypes(include=['object']).columns\n", + "print(list(categorical))\n", + "for col in list(categorical):\n", + " le=LabelEncoder()\n", + " df_clean[col]=le.fit_transform(df_clean[col].astype(str))\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "scaler= StandardScaler()\n", + "df_clean=scaler.fit_transform(df_clean)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 6: Write your code here:\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "features=['Vehicle_Type','Preparation_Time_min']\n", + "X=df_clean[features]\n", + "y=df_clean['Delivery_Time']\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "fig, axes = plt.subplots(1, 2, figsize=(15, 6))\n", + "axes = axes.flatten()\n", + "features = X.columns\n", + "for i, (model_name, coef) in enumerate(coeffs.items()):\n", + "\n", + " absolute_coef = np.abs(coef)\n", + " sorted_idx = np.argsort(absolute_coef)\n", + " ax = axes[i]\n", + " ax.barh(features[sorted_idx], coef[sorted_idx])\n", + " ax.set_title(f\"{model_name} Coefficients\")\n", + " ax.set_xlabel(\"Coefficient Value (Impact)\")\n", + " plt.tight_layout()\n", + " plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/382/Q2.ipynb b/submissions_extracted/382/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..127fe6f16a625018e6f7760995e391b876c631a6 --- /dev/null +++ b/submissions_extracted/382/Q2.ipynb @@ -0,0 +1,310 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q2-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import os\n", + "import pandas as pd\n", + "import numpy as np\n", + "from PIL import Image\n", + "from sklearn.model_selection import train_test_split\n", + "import torch\n", + "import torch.nn as nn\n", + "from torch.optim import Adam\n", + "from torch.utils.data import DataLoader\n", + "from torchvision.datasets import MNIST\n", + "from torchvision.transforms import ToTensor, Compose, Normalize\n", + "from sklearn.decomposition import PCA\n", + "from sklearn.manifold import TSNE\n", + "from sklearn.cluster import KMeans\n", + "import matplotlib.pyplot as plt\n", + "import numpy as np\n", + "from collections import Counter\n", + "from torch.utils.data import TensorDataset\n", + "import torch.nn.functional as F\n", + "from torch.optim import AdamW\n", + "\n", + "# Load Labels\n", + "labels_df = pd.read_csv(os.path.join(path, \"labels.csv\"))\n", + "img_dir = os.path.join(path, \"images\")\n", + "\n", + "images = []\n", + "ages = []\n", + "\n", + "# Load Images and Resize\n", + "print(\"Loading images...\")\n", + "for index, row in labels_df.iterrows():\n", + " img_name = row.iloc[0]\n", + " age = row.iloc[1]\n", + " img_path = os.path.join(img_dir, img_name)\n", + "\n", + " if os.path.exists(img_path):\n", + " img = Image.open(img_path).convert('RGB')\n", + " img_array = np.array(img) / 255.0 # Normalize pixel values to [0, 1]\n", + " images.append(img_array)\n", + " ages.append(age)\n", + "\n", + "X = np.array(images)\n", + "y = np.array(ages)\n", + "\n", + "# Transpose image dimensions to match PyTorch format (N, C, H, W)\n", + "X = np.transpose(X, (0, 3, 1, 2))\n", + "\n", + "# Split Data\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n", + "\n", + "print(f\"X_train shape: {X_train.shape}\")\n", + "print(f\"X_test shape: {X_test.shape}\")\n", + "print(f\"y_train shape: {y_train.shape}\")\n", + "print(f\"y_test shape: {y_test.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 1. Convert Numpy arrays to PyTorch Tensors\n", + "X_train = torch.tensor(X_train, dtype=torch.float32).flatten()\n", + "X_test = torch.tensor(X_test, dtype=torch.float32)\n", + "y_train = torch.tensor(y_train, dtype=torch.float32)\n", + "y_test = torch.tensor(y_test, dtype=torch.float32)\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 2. Create TensorDataset objects\n", + "train_dataset=TensorDataset(X_train,y_train)\n", + "test_dataset=TensorDataset(X_test,y_test)\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 3. Create DataLoaders\n", + "\n", + "train_loader = DataLoader(\n", + "train_dataset,\n", + "batch_size=32,\n", + "shuffle=True,\n", + "num_workers=2)\n", + "test_loader = DataLoader(\n", + "test_dataset,\n", + "batch_size=32,\n", + "shuffle=False,)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 4. Print shape of one batch\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 5. Display sample images\n", + "images,labels=next(iter(train_dataset))\n", + "plt.figure(figsize=(20,4))\n", + "for i in range(2):\n", + " plt.subplot(2, 3, i + 1)\n", + " plt.imshow(images[i].squeeze(), cmap='gray')\n", + " plt.axis('off')\n", + " plt.tight_layout()\n", + " plt.show()\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your model class here:\n", + "class NN4Layer(nn.Module):\n", + " def __init__(self, input_dim, hidden_dim, output_dim):\n", + " super(NN4Layer, self).__init__()\n", + "\n", + " self.layer1 = nn.Linear(input_dim, hidden_dim)\n", + "\n", + " self.layer2 = nn.Linear(hidden_dim, hidden_dim)\n", + "\n", + " self.layer3 = nn.Linear(hidden_dim, hidden_dim)\n", + "\n", + " self.layer4=nn.Linear(hidden_dim,output_dim)\n", + "\n", + " self.relu = nn.ReLU()\n", + "\n", + " def forward(self, x):\n", + "\n", + " z1 = self.layer1(x)\n", + " a1 = self.relu(z1)\n", + "\n", + " z2 = self.layer2(a1)\n", + " a2 = self.relu(z2)\n", + " z3=self.layer3(a2)\n", + " a3=self.relu(z3)\n", + " output = self.layer4(a3)\n", + " return output" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your training loop here:\n", + "def train_one_epoch(model, optimizer, criterion, train_loader, device):\n", + " model.train()\n", + " running_loss = 0.0\n", + " for X_batch, y_batch in train_loader:\n", + "\n", + " X_batch = X_batch.view(X_batch.size(0), -1).to(device)\n", + " y_batch = y_batch.to(device)\n", + "\n", + " outputs = model(X_batch)\n", + " loss = criterion(outputs, y_batch)\n", + " optimizer.zero_grad()\n", + " loss.backward()\n", + " optimizer.step()\n", + " running_loss += loss.item()\n", + "" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your validation loop here:\n", + "def validate(model, criterion, test_loader, device):\n", + " model.eval()\n", + " running_loss = 0.0\n", + "\n", + " with torch.no_grad():\n", + " for X_batch, y_batch in test_loader:\n", + "\n", + " X_batch = X_batch.view(X_batch.size(0), -1).to(device)\n", + " y_batch = y_batch.to(device)\n", + "\n", + " outputs = model(X_batch.viewsview(images.size(0), -1))\n", + " loss = criterion(outputs, y_batch)\n", + " running_loss += loss.item()\n", + "\n", + "\n", + "" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Define device, model, loss, optimizer:\n", + "device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n", + "input_dim=2000\n", + "hidden_dim=14\n", + "output_dim=101\n", + "model = NN4Layer(input_dim, hidden_dim, output_dim).to(device)\n", + "loss=nn.MSELoss()\n", + "num_epochs=20\n", + "learning_rate=0.01\n", + "optimizer=AdamW(model.parameters(),learning_rate)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Start training for 20 epochs:\n", + "train_losses=[]\n", + "test_losses=[]\n", + "print('Starting Training...')\n", + "for epoch in range(num_epochs):\n", + "\n", + " train_loss = train_one_epoch(model, optimizer, loss, train_loader, device)\n", + "\n", + " val_loss, val_accuracy = validate(model, loss, test_loader, device)\n", + " train_losses.append(train_loss)\n", + " test_losses.append(val_loss)\n", + " print(f'Epoch [{epoch+1}/{num_epochs}], Train Loss: {train_loss:.4f}, Val Loss: {val_loss:.4f}')" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "plt.figure(figsize=(10, 5))\n", + "plt.plot(train_losses, 'b-o')\n", + "plt.xlabel('Epoch')\n", + "plt.ylabel('MSE Loss')\n", + "plt.title('Autoencoder Training Loss')\n", + "plt.grid(True, alpha=0.3)\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2 (Bonus): Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/382/Q3.ipynb b/submissions_extracted/382/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..56e29d0343425d034c7ca049d1d31a67ef34c11e --- /dev/null +++ b/submissions_extracted/382/Q3.ipynb @@ -0,0 +1,251 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "import pandas as pd\n", + "import numpy as np\n", + "import matplotlib.pyplot as plt\n", + "import seaborn as sns\n", + "import os\n", + "\n", + "\n", + "\n", + "# Download latest version\n", + "\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q3-exam-data\")\n", + "\n", + "\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "cvs_path=os.path.join(path,'Q3_data.csv')\n", + "df_card=pd.read_csv(cvs_path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "df_card.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "df_card.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "df_card.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "df_card['Target'] = df_card['Target'].map({'Default': 1, 'No Default': 0})\n", + "missing_values = df_card.dropna()\n", + "\n", + "\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "duplicates = df_card.duplicated().sum()\n", + "print(f\"Number of Duplicate Samples: {duplicates}\")\n", + "if duplicates > 0:\n", + " print(\"Dropping Duplicates...\")\n", + " df_card.drop_duplicates(inplace=True)\n", + " print(\"Duplicates Dropped.\")\n", + "else:\n", + " print(\"No Duplicate Samples Found.\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "categorical_cols = df_card.select_dtypes(include=[\"object\"]).columns\n", + "print(\"Categorical Columns:\", list(categorical_cols))" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "from sklearn.preprocessing import StandardScaler\n", + "numerical_cols = df_card.select_dtypes(include=[\"int64\", \"float64\"]).columns.drop(\"Target\")\n", + "scaler = StandardScaler()\n", + "df_card[numerical_cols] = scaler.fit_transform(df_card[numerical_cols])\n", + "df_card.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "print(\"Target Distribution:\")\n", + "print(df_card['Target'].value_counts(normalize=True))\n", + "sns.countplot(x=df_card['Target'])\n", + "plt.title(\"Target Distribution\")\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "X = df_card.drop(\"Target\", axis=1).astype(float)\n", + "y = df_card['Target'].astype(float)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:\n", + "from tqdm import tqdm\n", + "def sigmoid(z):\n", + " return 1 / (1 + np.exp(-z))\n", + "def binary_cross_entropy(y, y_hat):\n", + " epsilon = 1e-15 # Very small number to prevent log(0)\n", + " y_hat = np.clip(y_hat, epsilon, 1 - epsilon) # np.clip(value, min, max)\n", + " loss = -1/len(y) * np.sum(y * np.log(y_hat) + (1 - y) * np.log(1 - y_hat))\n", + " return loss\n", + "def gradient_descent(X, y, learning_rate, n_iters=500):\n", + " m, n = X.shape # m rows, n columns (dimensions)\n", + " theta = np.zeros(n) # initialize a zeros weight vector with n dimensions\n", + " losses = []\n", + " for _ in tqdm(range(n_iters), desc=\"Training Logistic Regression\"):\n", + " z = np.dot(X, theta)\n", + " y_hat = sigmoid(z)\n", + " gradient = np.dot(X.T, (y_hat - y)) / m\n", + " theta -= learning_rate * gradient\n", + " loss = binary_cross_entropy(y, y_hat)\n", + " losses.append(loss)\n", + " return theta, losses\n", + "from sklearn.model_selection import StratifiedKFold\n", + "from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score\n", + "n_splits = 5\n", + "skf = StratifiedKFold(n_splits=n_splits, shuffle=True, random_state=42)\n", + "lr_losses = []\n", + "lr_accuracy = []\n", + "lr_f1 = []\n", + "for fold_idx, (train_index, test_index) in enumerate(skf.split(X, y)):\n", + " print(f\"\\nFold {fold_idx + 1}/{n_splits}\")\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", + " theta, losses = gradient_descent(X_train, y_train, learning_rate=0.5, n_iters=500)\n", + "\n", + " y_pred_proba = sigmoid(np.dot(X_test, theta))\n", + " y_pred = (y_pred_proba >= 0.5).astype(int)\n", + "\n", + " accuracy = accuracy_score(y_test, y_pred)\n", + "\n", + " f1 = f1_score(y_test, y_pred, zero_division=0)\n", + "\n", + " lr_losses.append(losses)\n", + " lr_accuracy.append(accuracy)\n", + "\n", + " lr_f1.append(f1)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "avg_loss = np.mean(lr_losses, axis=0)\n", + "plt.figure(figsize=(10, 6))\n", + "plt.plot(avg_loss, label='Logistic Regression Loss', color='purple')\n", + "plt.title('Average Logistic Regression Loss Curve (Across 5 Folds)')\n", + "plt.xlabel('Iteration')\n", + "plt.ylabel('Binary Cross-Entropy Loss')\n", + "plt.legend()\n", + "plt.grid(True, alpha=0.3)\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/383/Q1.ipynb b/submissions_extracted/383/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..ab589c34aad18e3190cf190541b4cc8406fc1bbc --- /dev/null +++ b/submissions_extracted/383/Q1.ipynb @@ -0,0 +1,355 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import pandas as pd\n", + "import numpy as np\n", + "import matplotlib.pyplot as plt\n", + "import seaborn as sns\n", + "import kagglehub\n", + "import os\n", + "from sklearn.preprocessing import LabelEncoder,StandardScaler\n", + "from sklearn.model_selection import train_test_split,KFold\n", + "from sklearn.ensemble import RandomForestRegressor\n", + "\n", + "from sklearn.metrics import mean_absolute_error\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q1-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "#/kaggle/input/q1-exam-data/Q1_data.csv\n", + "csv_path = os.path.join(path, \"Q1_data.csv\")\n", + "df = pd.read_csv(csv_path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "\n", + "df.head(10)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "df.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "df.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "def check_target_distribution(df, target_column):\n", + " df[target_column].hist(bins=30, edgecolor='black')\n", + " plt.title(f\"Target Distribution ({target_column})\")\n", + " plt.xlabel(target_column)\n", + " plt.ylabel(\"Frequency\")\n", + " plt.grid(False)\n", + " plt.show()\n", + "\n", + "check_target_distribution(df, \"Delivery_Time\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "df = df.drop(columns=\"Order_ID\", axis=1)\n", + "df" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "#calculting the missing percentage so that i thing what i do with them\n", + "missing_percentage = (df.isnull().sum() / len(df)) * 100\n", + "\n", + "missing_data = pd.DataFrame({\n", + " 'Column': missing_percentage.index,\n", + " 'Missing_Percentage': missing_percentage.values\n", + "})\n", + "missing_data = missing_data[missing_data['Missing_Percentage'] > 0].sort_values('Missing_Percentage', ascending=False)\n", + "print(\"Missing Data Analysis:\")\n", + "missing_data.head(10)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "df_clean = df.copy() #first lets copy\n", + "df_clean = df_clean.dropna(subset=[\"Delivery_Time\"]) #drop the na smaples in target\n", + "\n", + "columns_to_mode = ['Weather','Traffic_Level','Time_of_Day','Courier_Experience_yrs']\n", + "\n", + "for col in columns_to_mode:\n", + " df_clean[col]=df_clean[col].fillna(df_clean[col].mode()[0]) #i want descret numbers\n", + "\n", + "\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "df_clean.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "def check_duplicates(df_clean):\n", + " # duplicated().sum(): Counts identical rows.\n", + " duplicates = df_clean.duplicated().sum()\n", + " print(f\"Number of Duplicate Samples: {duplicates}\")\n", + "\n", + " if duplicates > 0:\n", + " print(\"Dropping Duplicates...\")\n", + " # inplace=True: Modifies the actual DataFrame, doesn't return a copy.\n", + " df_clean.drop_duplicates(inplace=True)\n", + " print(\"Duplicates Dropped.\")\n", + " else:\n", + " print(\"No Duplicate Samples Found.\")\n", + "\n", + "check_duplicates(df)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "df_clean.shape" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "catogerical = ['Weather', 'Traffic_Level', 'Time_of_Day', 'Vehicle_Type']\n", + "le = LabelEncoder()\n", + "for col in catogerical:\n", + " df_clean[col]=le.fit_transform(df_clean[col])\n", + "df_clean.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "#i want to do scale on the train only\n", + "X = df_clean.drop('Delivery_Time',axis=1)\n", + "y= df_clean['Delivery_Time']\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "standard_scaler = StandardScaler()\n", + "X_train_scaled = standard_scaler.fit_transform(X_train)\n", + "X_test_scaled = standard_scaler.transform(X_test)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 6: Write your code here:\n", + "# even if its imbalance, we dont care it is regression\n", + "target=df_clean['Delivery_Time'].value_counts()\n", + "target" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "# i did it above becaus i want to do the scalte on the train only so no data leake\n", + "#i used kfold only becuse it is regression" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:\n", + "model = RandomForestRegressor(n_estimators=100, max_depth=20, random_state=42, n_jobs=-1)\n", + "\n", + "model.fit(X_train_scaled, y_train)\n", + "print(\"Model trained!\")\n", + "\n", + "y_pred = model.predict(X_test_scaled)\n", + "mae = mean_absolute_error(y_test, y_pred)\n", + "print(f\"MAE: ${mae:,.2f}\")\n", + "\n", + "\n", + "\n", + "kfold = KFold(n_splits=3, shuffle=True, random_state=42)\n", + "mae_scores = []\n", + "for train_idx, val_idx in kfold.split(X_train_scaled):\n", + " # Slice the arrays\n", + " X_fold_train, X_fold_val = X_train_scaled[train_idx], X_train_scaled[val_idx]\n", + " y_fold_train, y_fold_val = y_train.iloc[train_idx], y_train.iloc[val_idx]\n", + "\n", + " # Train and predict\n", + " model.fit(X_fold_train, y_fold_train)\n", + " y_fold_pred = model.predict(X_fold_val)\n", + "\n", + " # Calculate metrics for this specific fold\n", + " mae_scores.append(mean_absolute_error(y_fold_val, y_fold_pred))\n", + "mae_scores = np.array(mae_scores)\n", + "print(f\"5-Fold CV Results:\")\n", + "print(f\"MAE: ${mae_scores.mean():,.2f}\")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "\n", + "feature_cols=['Distance_km','Weather','Traffic_Level','Time_of_Day','Vehicle_Type','Preparation_Time_min','Courier_Experience_yrs']\n", + "feature_importance = pd.DataFrame({\n", + " 'feature': feature_cols,\n", + " 'importance': model.feature_importances_\n", + "}).sort_values('importance', ascending=False)\n", + "\n", + "plt.figure(figsize=(10, 6))\n", + "plt.barh(feature_importance['feature'], feature_importance['importance'])\n", + "plt.xlabel('Importance')\n", + "plt.title('Feature Importance')\n", + "plt.gca().invert_yaxis()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "plt.figure(figsize=(10, 5))\n", + "plt.hist(y_pred, bins=50, edgecolor='black')\n", + "plt.title('predicted Distribution')\n", + "plt.xlabel('time in mins')\n", + "plt.ylabel('Frequency')\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/383/Q2.ipynb b/submissions_extracted/383/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..56e092ce492cee790f3a535fb9ccd13fc8a9072a --- /dev/null +++ b/submissions_extracted/383/Q2.ipynb @@ -0,0 +1,366 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import torch\n", + "import torch.nn as nn\n", + "from torchvision.datasets import MNIST\n", + "from torch.utils.data import DataLoader,TensorDataset\n", + "from torch.optim import AdamW\n", + "from torchvision.transforms.functional import to_tensor\n", + "import torch.nn.functional as F\n", + "import matplotlib.pyplot as plt" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q2-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import os\n", + "import pandas as pd\n", + "import numpy as np\n", + "from PIL import Image\n", + "from sklearn.model_selection import train_test_split\n", + "\n", + "# Load Labels\n", + "labels_df = pd.read_csv(os.path.join(path, \"labels.csv\"))\n", + "img_dir = os.path.join(path, \"images\")\n", + "\n", + "images = []\n", + "ages = []\n", + "\n", + "# Load Images and Resize\n", + "print(\"Loading images...\")\n", + "for index, row in labels_df.iterrows():\n", + " img_name = row.iloc[0]\n", + " age = row.iloc[1]\n", + " img_path = os.path.join(img_dir, img_name)\n", + "\n", + " if os.path.exists(img_path):\n", + " img = Image.open(img_path).convert('RGB')\n", + " img_array = np.array(img) / 255.0 # Normalize pixel values to [0, 1]\n", + " images.append(img_array)\n", + " ages.append(age)\n", + "\n", + "X = np.array(images)\n", + "y = np.array(ages)\n", + "\n", + "# Transpose image dimensions to match PyTorch format (N, C, H, W)\n", + "X = np.transpose(X, (0, 3, 1, 2))\n", + "\n", + "# Split Data\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n", + "\n", + "print(f\"X_train shape: {X_train.shape}\")\n", + "print(f\"X_test shape: {X_test.shape}\")\n", + "print(f\"y_train shape: {y_train.shape}\")\n", + "print(f\"y_test shape: {y_test.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 1. Convert Numpy arrays to PyTorch Tensors\n", + "# Float for inputs, Long for classification targets, Float for regression targets\n", + "X_train_tensor = torch.tensor(X_train, dtype=torch.float32)\n", + "y_train_tensor = torch.tensor(y_train, dtype=torch.float32)\n", + "\n", + "X_test_tensor = torch.tensor(X_test, dtype=torch.float32)\n", + "y_test_tensor = torch.tensor(y_test, dtype=torch.float32)\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 2. Create TensorDataset objects\n", + "train_dataset = TensorDataset(X_train_tensor, y_train_tensor)\n", + "test_dataset = TensorDataset(X_test_tensor, y_test_tensor)\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 3. Create DataLoaders\n", + "train_loader = DataLoader(train_dataset, batch_size=64, shuffle=True)\n", + "test_loader = DataLoader(test_dataset, batch_size=64, shuffle=False)\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 4. Print shape of one batch\n", + "\n", + "X_batch, y_batch = next(iter(train_loader))\n", + "print(f\"Training batch input shape: {X_batch.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 5. Display sample images\n", + "# Get one batch of images and labels\n", + "images, labels = next(iter(train_loader))\n", + "\n", + "# Display the first 6 images in the batch\n", + "plt.figure(figsize=(8, 4))\n", + "\n", + "for i in range(6):\n", + " plt.subplot(2, 3, i + 1)\n", + " # .squeeze() removes the channel dimension (1, 28, 28) -> (28, 28) for matplotlib\n", + " img = images[i].permute(1, 2, 0)\n", + " plt.imshow(img)\n", + " plt.title(f\"Label: {labels[i].item()}\")\n", + " plt.axis('off')\n", + "\n", + "plt.tight_layout()\n", + "plt.show()\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your model class here:\n", + "class NN4Layer(nn.Module):\n", + "\n", + " def __init__(self, input_dim, hidden_dim, output_dim):\n", + " super(NN4Layer, self).__init__()\n", + "\n", + " self.layer1 = nn.Linear(input_dim, hidden_dim)\n", + "\n", + " self.layer2 = nn.Linear(hidden_dim, hidden_dim)\n", + "\n", + " self.layer3 = nn.Linear(hidden_dim, hidden_dim)\n", + "\n", + " self.layer4 = nn.Linear(hidden_dim, output_dim)\n", + "\n", + "\n", + "\n", + " # activation function for non-linearity\n", + " self.relu = nn.ReLU()\n", + "\n", + " # Defines how input data flows through the network\n", + " def forward(self, x):\n", + " z1 = self.layer1(x)\n", + " a1 = self.relu(z1)\n", + "\n", + " z2 = self.layer2(a1)\n", + " a2 = self.relu(z2)\n", + "\n", + " z3 = self.layer3(a2)\n", + " a3 = self.relu(z3)\n", + "\n", + " # Layer 4 TODO\n", + " z4 = self.layer4(a3)\n", + "\n", + "\n", + "\n", + "\n", + " # TODO: are we missing output activation function? (hint: Loss Function)\n", + "\n", + " return z4" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your training loop here:\n", + "def train_one_epoch(model, optimizer, criterion, train_loader, device):\n", + " # Set the model to training mode\n", + " model.train()\n", + " running_loss = 0.0\n", + "\n", + " for X_batch, y_batch in train_loader:\n", + " X_batch =X_batch.view(X_batch.size(0), -1).to(device)\n", + " y_batch = y_batch.to(device)\n", + "\n", + " outputs = model(X_batch)\n", + " loss = criterion(outputs, y_batch)\n", + "\n", + "\n", + " optimizer.zero_grad()\n", + " loss.backward()\n", + " optimizer.step()\n", + "\n", + " running_loss += loss.item()\n", + "\n", + " avg_loss = running_loss / len(train_loader)\n", + " return avg_loss" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your validatio\n", + "def validate(model, criterion, test_loader, device):\n", + " # Set the model to evaluation mode\n", + "\n", + " model.eval()\n", + " running_loss = 0.0\n", + " with torch.no_grad():\n", + " for X_batch, y_batch in test_loader:\n", + " # Move data to device\n", + " X_batch = X_batch.view(X_batch.size(0), -1).to(device)\n", + " y_batch = y_batch.to(device)\n", + "\n", + " outputs = model(X_batch)\n", + " loss = criterion(outputs, y_batch)\n", + " running_loss += loss.item()\n", + " avg_loss = running_loss / len(test_loader)\n", + " return avg_loss" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Define device, model, loss, optimizer:\n", + "device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n", + "input_dim = 3*36*36\n", + "hidden_dim = 64\n", + "output_dim = 1\n", + "\n", + "\n", + "num_epochs = 20\n", + "learning_rate = 0.001\n", + "\n", + "model=NN4Layer(input_dim, hidden_dim, output_dim).to(device)\n", + "optimizer = AdamW(model.parameters(), learning_rate)\n", + "criterion = nn.MSELoss()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "print(\"Model Architecture:\\n\")\n", + "print(model)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Start training for 20 epochs:\n", + "train_losses = []\n", + "val_losses = []\n", + "val_accuracies = []\n", + "\n", + "print('Starting Training...')\n", + "for epoch in range(num_epochs):\n", + " # Train one epoch\n", + " train_loss = train_one_epoch(model, optimizer, criterion, train_loader, device)\n", + "\n", + " # Validate\n", + " val_loss = validate(model, criterion, test_loader, device)\n", + "\n", + " train_losses.append(train_loss)\n", + " val_losses.append(val_loss)\n", + "\n", + "\n", + " print(f'Epoch [{epoch+1}/{num_epochs}], Train Loss: {train_loss:.4f}')\n", + "\n", + "print('Training Complete!')" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "plt.figure(figsize=(7, 5))\n", + "\n", + "plt.plot(train_losses, label='Train Loss')\n", + "plt.plot(val_losses, label='Validation Loss')\n", + "plt.title('Loss over Epochs')\n", + "plt.xlabel('Epoch')\n", + "plt.ylabel('Loss')\n", + "plt.legend()\n", + "\n", + "plt.tight_layout()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2 (Bonus): Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/383/Q3.ipynb b/submissions_extracted/383/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..ecf0813000a9a5de915428cd04842b3013b6e2b9 --- /dev/null +++ b/submissions_extracted/383/Q3.ipynb @@ -0,0 +1,273 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "from IPython.display import clear_output\n", + "\n", + "%pip install kagglehub catboost xgboost tqdm -q\n", + "clear_output()\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import pandas as pd\n", + "import numpy as np\n", + "import matplotlib.pyplot as plt\n", + "import seaborn as sns\n", + "import kagglehub\n", + "import os\n", + "from tqdm import tqdm\n", + "from sklearn.preprocessing import StandardScaler\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "\n", + "\n", + "# Download latest version\n", + "\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q3-exam-data\")\n", + "\n", + "\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "csv_path = os.path.join(path, \"Q3_data.csv\")\n", + "\n", + "df = pd.read_csv(csv_path)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "df.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "df.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "# Do we have missing values?\n", + "missing_percentage = (df.isnull().sum() / len(df)) * 100\n", + "\n", + "missing_data = pd.DataFrame({\n", + " 'Column': missing_percentage.index,\n", + " 'Missing_Percentage': missing_percentage.values\n", + "})\n", + "missing_data = missing_data[missing_data['Missing_Percentage'] > 0].sort_values('Missing_Percentage', ascending=False)\n", + "print(\"Missing Data Analysis:\")\n", + "missing_data.head(10)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "df_clean = df.copy()\n", + "df_clean = df_clean.drop(columns=['D_87','D_88','B_39','D_110','D_111','D_108','B_42','D_73','D_135','D_136']) #drop the na smaples in target\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "def check_duplicates(df_clean):\n", + " duplicates = df_clean.duplicated().sum()\n", + " print(f\"Number of Duplicate Samples: {duplicates}\")\n", + " if duplicates > 0:\n", + " print(\"Dropping Duplicates...\")\n", + " df_clean.drop_duplicates(inplace=True)\n", + " print(\"Duplicates Dropped.\")\n", + " else:\n", + " print(\"No Duplicate Samples Found.\")\n", + "\n", + "check_duplicates(df_clean)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "categorical_cols = df_clean.select_dtypes(include=[\"object\"]).columns\n", + "\n", + "print(\"Categorical Columns:\", list(categorical_cols))" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "numerical_cols = df_clean.select_dtypes(include=[\"int64\", \"float64\"]).columns.drop(\"Target\") # DON'T SCALE THE TARGET\n", + "\n", + "# StandardScaler: (x - mean) / std (Z-score normalization)\n", + "scaler = StandardScaler()\n", + "df_clean[numerical_cols] = scaler.fit_transform(df_clean[numerical_cols])\n", + "df_clean.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "target=df_clean['Target'].value_counts()\n", + "target" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "X = df.drop(\"Target\", axis=1)\n", + "y = df['Target']" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:\n", + "from sklearn.model_selection import StratifiedKFold\n", + "from catboost import CatBoostClassifier\n", + "\n", + "n_splits = 5\n", + "skf = StratifiedKFold(n_splits=n_splits, shuffle=True, random_state=42)\n", + "\n", + "\n", + "for fold_idx, (train_index, test_index) in enumerate(skf.split(X, y)):\n", + " print(f\"\\nFold {fold_idx + 1}/{n_splits}\")\n", + "\n", + " # 1. Split data\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=CatBoostClassifier(\n", + " verbose=0, # Silence training log\n", + " n_estimators=320,\n", + " max_depth=4\n", + " )\n", + "\n", + " model.fit(X_train, y_train)\n", + " y_pred = model.predict(X_test)\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "majority_class = y.value_counts().idxmax()\n", + "baseline_pred = [majority_class] * len(y)\n", + "baseline_accuracy = accuracy_score(y, baseline_pred)\n", + "baseline_f1 = f1_score(y, baseline_pred, average='weighted', zero_division=0)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/384/Q1.ipynb b/submissions_extracted/384/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..0d7481b2990f07029a489fc94c7f83eadeb4d856 --- /dev/null +++ b/submissions_extracted/384/Q1.ipynb @@ -0,0 +1,459 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q1-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import os\n", + "# Task 1: Write your code here:\n", + "import pandas as pd\n", + "import numpy as np\n", + "import matplotlib.pyplot as plt\n", + "import seaborn as sns\n", + "import kagglehub\n", + "import os\n", + "from tqdm import tqdm\n", + "csv_path = os.path.join(path, \"Q1_data.csv\")\n", + "\n", + "df = pd.read_csv(csv_path)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "df.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "df.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "plt.figure(figsize=(10, 5))\n", + "plt.hist(df['Delivery_Time'].dropna(), bins=50, edgecolor='black')\n", + "plt.title('Delivery_Time Distribution')\n", + "plt.xlabel('Delivery_Time')\n", + "plt.ylabel('Frequency')\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "df = df.drop(columns=\"Order_ID\", axis=1)\n", + "df.head()\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "def check_missing_values(df):\n", + " missing_values = df.isnull().sum()\n", + " print(\"Missing Values per Column:\")\n", + " print(missing_values[missing_values > 0])\n", + " if missing_values.any():\n", + " print(\"\\nHandle Missing Values as needed.\")\n", + " else:\n", + " print(\"\\nNo Missing Values Found.\")\n", + "\n", + "check_missing_values(df)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "cols = ['Distance_km', 'Weather', 'Traffic_Level', 'Time_of_Day', 'Vehicle_Type', 'Preparation_Time_min', 'Courier_Experience_yrs', 'Delivery_Time']\n", + "df_clean = df[cols].copy()\n", + "\n", + "# Drop rows where target missing - can't predict without them\n", + "print(f\"Before: {df_clean.shape}\")\n", + "df_clean = df_clean.dropna(subset=['Delivery_Time'])\n", + "print(f\"After dropping missing : {df_clean.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "check_missing_values(df_clean)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# # Fill categorical columns with 'unknown' - missing likely means \"not specified\"\n", + "for col in ['Weather', 'Traffic_Level', 'Time_of_Day''Time_of_Day', 'Vehicle_Type']:\n", + " df_clean[col] = df_clean[col].fillna('unknown')\n", + "\n", + "#Fill Courier_Experience_yrs with mean\n", + "df_clean['Courier_Experience_yrs'] = df_clean['Courier_Experience_yrs'].fillna(df_clean['Courier_Experience_yrs'].mean())\n", + "\n", + "print(\"Missing values remaining:\", df_clean.isnull().sum().sum())" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "# 4. Do we have duplicate samples?\n", + "def check_duplicates(df):\n", + " duplicates = df.duplicated().sum()\n", + " print(f\"Number of Duplicate Samples: {duplicates}\")\n", + " if duplicates > 0:\n", + " print(\"Dropping Duplicates...\")\n", + " df.drop_duplicates(inplace=True)\n", + " print(\"Duplicates Dropped.\")\n", + " else:\n", + " print(\"No Duplicate Samples Found.\")\n", + "\n", + "check_duplicates(df)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "# 4. Do we have duplicate samples?\n", + "def check_duplicates(df_clean):\n", + " duplicates = df_clean.duplicated().sum()\n", + " print(f\"Number of Duplicate Samples: {duplicates}\")\n", + " if duplicates > 0:\n", + " print(\"Dropping Duplicates...\")\n", + " df_clean.drop_duplicates(inplace=True)\n", + " print(\"Duplicates Dropped.\")\n", + " else:\n", + " print(\"No Duplicate Samples Found.\")\n", + "\n", + "check_duplicates(df_clean)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "from sklearn.preprocessing import OneHotEncoder #import OneHotEncoder\n", + "\n", + "catog = ['Weather', 'Traffic_Level', 'Time_of_Day', 'Vehicle_Type']\n", + "#categories = pd.DataFrame(catog)\n", + "catog\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "from sklearn.preprocessing import LabelEncoder #import LabelEncoder\n", + "\n", + "print('data before encoding:\\n', catog) #show before encoding\n", + "\n", + "label_encoder = LabelEncoder() # Instantiate LabelEncoder\n", + "data_label_encoded = label_encoder.fit_transform(catog) # Apply fit_transform to the column\n", + "\n", + "print('\\nData after encoding:\\n', data_label_encoded) #show after encoding" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "from sklearn.preprocessing import LabelEncoder\n", + "# 3. Do we have categorical columns?\n", + "categorical_cols = df.select_dtypes(include=[\"object\"]).columns\n", + "\n", + "print(\"Categorical Columns:\", list(categorical_cols))\n", + "label_encoders = {}\n", + "for col in categorical_cols:\n", + " le = LabelEncoder()\n", + " df[col] = le.fit_transform(df[col])\n", + " label_encoders[col] = le\n", + "\n", + "df" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "\n", + "# onehot_encoder = OneHotEncoder(sparse_output=False) # Instantiate OneHotEncoder\n", + "# data_onehot_encoded = onehot_encoder.fit_transform(cols) # Apply fit_transform to the copied\n", + "\n", + "# print('\\nData after encoding:\\n', data_onehot_encoded) #show after encoding" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "from sklearn.preprocessing import StandardScaler\n", + "\n", + "numerical_cols = df.select_dtypes(include=[\"int64\", \"float64\"]).columns.drop(\"Delivery_Time\") #we shouldnt SCALE THE TARGET\n", + "\n", + "scaler = StandardScaler()\n", + "df[numerical_cols] = scaler.fit_transform(df[numerical_cols])\n", + "df.head()\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 6: Write your code here:\n", + "# 1. Is the target imbalanced?\n", + "def check_target_imbalance(df, target_column):\n", + " print(\"Target Distribution:\")\n", + "\n", + " df[target_column].hist()\n", + " plt.show()\n", + "\n", + "check_target_imbalance(df, \"Delivery_Time\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "from sklearn.linear_model import Ridge, Lasso\n", + "from sklearn.svm import SVR\n", + "from sklearn.tree import DecisionTreeRegressor\n", + "from sklearn.ensemble import RandomForestRegressor\n", + "from lightgbm import LGBMRegressor\n", + "from sklearn.metrics import mean_absolute_error, mean_squared_error\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "X = df.drop(\"Delivery_Time\", axis=1).astype(float)\n", + "y = df['Delivery_Time'].astype(float)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n", + "print(f\"Train: {X_train.shape}, Test: {X_test.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "from sklearn.model_selection import StratifiedKFold\n", + "from sklearn.model_selection import train_test_split\n", + "\n", + "n_splits = 3 # K\n", + "\n", + "# Stratified 5-Fold Cross-Validation, shuffled\n", + "skf = StratifiedKFold(n_splits=n_splits, shuffle=True, random_state=42)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "for fold_idx, (train_index, test_index) in enumerate(skf.split(X, y)):\n", + " print(f\"\\nFold {fold_idx + 1}/{n_splits}\")\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]" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Train Random Forest Regressor\n", + "model = RandomForestRegressor(n_estimators=100, max_depth=20, random_state=42, n_jobs=-1)\n", + "model.fit(X_train, y_train)\n", + "print(\"Model trained!\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Predict and evaluate\n", + "y_pred = model.predict(X_test)\n", + "\n", + "mae = mean_absolute_error(y_test, y_pred)\n", + "\n", + "print(f\"MAE: ${mae:,.2f}\")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "print(\"Linear Regression Results\")\n", + "print(f\" Average MSE: {np.mean(mae):.4f}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "coeffs = {}\n", + "\n", + "coeffs['Lasso'] = model.coef_\n", + "coeffs['Ridge'] = model.coef_\n", + "\n", + "fig, axes = plt.subplots(1, 2, figsize=(15, 6))\n", + "axes = axes.flatten()\n", + "features = X.columns\n", + "\n", + "for i, (model_name, coef) in enumerate(coeffs.items()):\n", + " # Sort features by absolute coefficient value\n", + " absolute_coef = np.abs(coef)\n", + " sorted_idx = np.argsort(absolute_coef)\n", + "\n", + " ax = axes[i]\n", + " ax.barh(features[sorted_idx], coef[sorted_idx])\n", + " ax.set_title(f\"{model_name} Coefficients\")\n", + " ax.set_xlabel(\"Coefficient Value (Impact)\")\n", + "\n", + "plt.tight_layout()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "# Plot for Linear Regression Predictions vs. Ground Truth\n", + "plt.figure(figsize=(6, 4))\n", + "plt.scatter(y_test, y_pred, alpha=0.7)\n", + "plt.plot([min(y_test), max(y_test)], [min(y_test), max(y_test)], 'r--', linewidth=2)\n", + "plt.xlabel(\"Actual y_test (Ground Truth)\")\n", + "plt.ylabel(\"Predicted y_pred (Linear Regression)\")\n", + "plt.title(\"Predictions vs. Ground Truth\")\n", + "plt.grid(True)\n", + "\n", + "plt.tight_layout()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/384/Q2.ipynb b/submissions_extracted/384/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..ac35b59075ce5361a431d5fb754fd4bc5fb73fa3 --- /dev/null +++ b/submissions_extracted/384/Q2.ipynb @@ -0,0 +1,362 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q2-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import os\n", + "import pandas as pd\n", + "import numpy as np\n", + "from PIL import Image\n", + "from sklearn.model_selection import train_test_split\n", + "\n", + "# Load Labels\n", + "labels_df = pd.read_csv(os.path.join(path, \"labels.csv\"))\n", + "img_dir = os.path.join(path, \"images\")\n", + "\n", + "images = []\n", + "ages = []\n", + "\n", + "# Load Images and Resize\n", + "print(\"Loading images...\")\n", + "for index, row in labels_df.iterrows():\n", + " img_name = row.iloc[0]\n", + " age = row.iloc[1]\n", + " img_path = os.path.join(img_dir, img_name)\n", + "\n", + " if os.path.exists(img_path):\n", + " img = Image.open(img_path).convert('RGB')\n", + " img_array = np.array(img) / 255.0 # Normalize pixel values to [0, 1]\n", + " images.append(img_array)\n", + " ages.append(age)\n", + "\n", + "X = np.array(images)\n", + "y = np.array(ages)\n", + "\n", + "# Transpose image dimensions to match PyTorch format (N, C, H, W)\n", + "X = np.transpose(X, (0, 3, 1, 2))\n", + "\n", + "# Split Data\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n", + "\n", + "print(f\"X_train shape: {X_train.shape}\")\n", + "print(f\"X_test shape: {X_test.shape}\")\n", + "print(f\"y_train shape: {y_train.shape}\")\n", + "print(f\"y_test shape: {y_test.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 1. Convert Numpy arrays to PyTorch Tensors\n", + "# transform to tensors so we can use the libarary\n", + "from sklearn.model_selection import train_test_split\n", + "from sklearn.preprocessing import StandardScaler\n", + "from torch.utils.data import TensorDataset\n", + "from torch.utils.data import DataLoader\n", + "import torch\n", + "X_train = torch.tensor(X_train, dtype=torch.float32)\n", + "X_test = torch.tensor(X_test, dtype=torch.float32)\n", + "y_train = torch.tensor(y_train, dtype=torch.float32)\n", + "y_test = torch.tensor(y_test, dtype=torch.float32)\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 2. Create TensorDataset objects\n", + "\n", + "train_dataset = TensorDataset(X_train, y_train)\n", + "test_dataset = TensorDataset(X_test, y_test)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 3. Create DataLoaders\n", + "train_loader = DataLoader(train_dataset, batch_size=32, shuffle=True)\n", + "test_loader = DataLoader(test_dataset, batch_size=32, shuffle=False)\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 4. Print shape of one batch\n", + "first_sample, _ = train_dataset[0]\n", + "print(f\"Shape of one sample: {first_sample.shape}\")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 5. Display sample images\n", + "from torchvision.datasets import CIFAR10\n", + "from torchvision.transforms.functional import to_tensor\n", + "from torch.utils.data import DataLoader\n", + "import matplotlib.pyplot as plt\n", + "import torch.nn as nn\n", + "import torch.nn.functional as F\n", + "import torch\n", + "from torch.optim import AdamW\n", + "# Get one batch of images and labels\n", + "images, labels = next(iter(train_loader))\n", + "\n", + "# Display the first 6 images in the batch\n", + "plt.figure(figsize=(8, 4))\n", + "\n", + "for i in range(6):\n", + " plt.subplot(2, 3, i + 1)\n", + "\n", + " # Convert from (C, H, W) to (H, W, C) for matplotlib\n", + " img = images[i].permute(1, 2, 0)\n", + "\n", + " plt.imshow(img)\n", + " plt.title(f\"Label: {labels[i].item()}\")\n", + " plt.axis('off')\n", + "\n", + "plt.tight_layout()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "class NN3Layer(nn.Module):\n", + " def __init__(self, input_dim, hidden_dim):\n", + " super(NN3Layer, self).__init__()\n", + "\n", + " # First linear layer: input features -> hidden layer\n", + " self.layer1 = nn.Linear(input_dim, hidden_dim)\n", + "\n", + " # Second linear layer: hidden layer -> hidden layer\n", + " self.layer2 = nn.Linear(hidden_dim, hidden_dim)\n", + "\n", + " # Output layer: hidden layer -> single continuous value\n", + " self.layer3 = nn.Linear(hidden_dim, 1)\n", + "\n", + " # ReLU activation for non-linearity in hidden layers\n", + " self.relu = nn.ReLU()\n", + "\n", + " # Defines how input data flows through the network\n", + " def forward(self, x):\n", + " # First hidden layer\n", + " a1 = self.relu(self.layer1(x))\n", + "\n", + " # Second hidden layer\n", + " a2 = self.relu(self.layer2(a1))\n", + "\n", + " # Output layer (regression output)\n", + " output = self.layer3(a2)\n", + "\n", + " return output" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your training loop here:\n", + "def train_one_epoch(model, optimizer, criterion, train_loader, device):\n", + " # Set the model to training mode\n", + " model.train()\n", + "\n", + " running_loss = 0.0\n", + "\n", + " for X_batch, y_batch in train_loader:\n", + " # Move batch to the selected device\n", + " X_batch = X_batch.view(-1, 1).to(device) # shape: (batch_size, num_features)\n", + " y_batch = y_batch.to(device) # shape: (batch_size, 1)\n", + "\n", + " # Forward pass (continuous output)\n", + " outputs = model(X_batch) # shape: (batch_size, 1)\n", + " loss = criterion(outputs, y_batch)\n", + "\n", + " # Backward pass & optimization\n", + " optimizer.zero_grad() # Clear previous gradients\n", + " loss.backward() # Compute gradients\n", + " optimizer.step() # Update model parameters\n", + "\n", + " running_loss += loss.item()\n", + "\n", + " # Average loss over all batches\n", + " avg_loss = running_loss / len(train_loader)\n", + "\n", + " return avg_loss" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your validation loop here:\n", + "def validate(model, criterion, test_loader, device):\n", + " # Set the model to evaluation mode\n", + " model.eval()\n", + "\n", + " running_loss = 0.0\n", + "\n", + " with torch.no_grad():\n", + " for X_batch, y_batch in test_loader:\n", + " # Move data to device\n", + " X_batch = X_batch.to(device) # shape: (batch_size, num_features)\n", + " y_batch = y_batch.view(-1, 1).to(device) # shape: (batch_size, 1)\n", + "\n", + " # Forward pass (continuous output)\n", + " outputs = model(X_batch) # shape: (batch_size, 1)\n", + " loss = criterion(outputs, y_batch)\n", + "\n", + " running_loss += loss.item()\n", + "\n", + " # Average loss over all batches\n", + " avg_loss = running_loss / len(test_loader)\n", + "\n", + " return avg_loss" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Define device, model, loss, optimizer:\n", + "# Device setup\n", + "device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n", + "# Hyperparameters (feel free to experiment!)\n", + "num_epochs = 20\n", + "learning_rate = 0.001\n", + "# Define criterion (loss function)\n", + "# Model parameters\n", + "input_dim = X_train.shape[1] # Number of tabular features\n", + "hidden_dim = 64 # Design choice\n", + "\n", + "# Instantiate regression model\n", + "model = NN3Layer(input_dim, hidden_dim).to(device)\n", + "\n", + "# Print the model architecture\n", + "print(\"Model Architecture:\\n\")\n", + "print(model)\n", + "\n", + "# Calculate the total number of trainable parameters\n", + "total_params = sum(p.numel() for p in model.parameters() if p.requires_grad)\n", + "print(f\"\\nTotal trainable parameters: {total_params}\")\n", + "criterion = nn.MSELoss()\n", + "# Define optimizer\n", + "optimizer = AdamW(model.parameters(), learning_rate)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Start training for 20 epochs:\n", + "# Run Training\n", + "train_losses = []\n", + "val_losses = []\n", + "\n", + "print('Starting Training...')\n", + "for epoch in range(num_epochs):\n", + " # Train one epoch\n", + " train_loss = train_one_epoch(model, optimizer, criterion, train_loader, device)\n", + "\n", + " # Validate\n", + " val_loss = validate(model, criterion, test_loader, device)\n", + "\n", + " train_losses.append(train_loss)\n", + " val_losses.append(val_loss)\n", + "\n", + " if (epoch + 1) % 5 == 0:\n", + " print(\n", + " f'Epoch [{epoch+1}/{num_epochs}], '\n", + " f'Train Loss: {train_loss:.4f}, '\n", + " f'Val Loss: {val_loss:.4f}'\n", + " )\n", + "\n", + "print('Training Complete!')" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "# Plotting results\n", + "plt.figure(figsize=(7, 5))\n", + "\n", + "plt.plot(train_losses, label='Train Loss')\n", + "plt.plot(val_losses, label='Validation Loss')\n", + "plt.title('Loss over Epochs')\n", + "plt.xlabel('Epoch')\n", + "plt.ylabel('Loss (MSE)')\n", + "plt.legend()\n", + "\n", + "plt.tight_layout()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2 (Bonus): Write your code here:\n" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/384/Q3.ipynb b/submissions_extracted/384/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..fae53bcde26fc85615489ca60b777510413e4911 --- /dev/null +++ b/submissions_extracted/384/Q3.ipynb @@ -0,0 +1,329 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "\n", + "\n", + "# Download latest version\n", + "\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q3-exam-data\")\n", + "\n", + "\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "import os\n", + "# Task 1: Write your code here:\n", + "import pandas as pd\n", + "import numpy as np\n", + "import matplotlib.pyplot as plt\n", + "import seaborn as sns\n", + "import kagglehub\n", + "import os\n", + "from tqdm import tqdm\n", + "csv_path = os.path.join(path, \"Q3_data.csv\")\n", + "\n", + "df = pd.read_csv(csv_path)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "df.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "df.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "# 2. Do we have missing values?\n", + "def check_missing_values(df):\n", + " missing_values = df.isnull().sum()\n", + " print(\"Missing Values per Column:\")\n", + " print(missing_values[missing_values > 0])\n", + " if missing_values.any():\n", + " print(\"\\nHandle Missing Values as needed.\")\n", + " else:\n", + " print(\"\\nNo Missing Values Found.\")\n", + "\n", + "check_missing_values(df)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "for i in range(189):\n", + " df[i] = df[i].fillna(df[i].mean())\n", + "\n", + "print(\"Missing values remaining:\", df.isnull().sum().sum())" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "# 4. Do we have duplicate samples?\n", + "def check_duplicates(df):\n", + " duplicates = df.duplicated().sum()\n", + " print(f\"Number of Duplicate Samples: {duplicates}\")\n", + " if duplicates > 0:\n", + " print(\"Dropping Duplicates...\")\n", + " df.drop_duplicates(inplace=True)\n", + " print(\"Duplicates Dropped.\")\n", + " else:\n", + " print(\"No Duplicate Samples Found.\")\n", + "\n", + "check_duplicates(df)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "from sklearn.preprocessing import LabelEncoder\n", + "# 3. Do we have categorical columns?\n", + "categorical_cols = df.select_dtypes(include=[\"object\"]).columns\n", + "\n", + "print(\"Categorical Columns:\", list(categorical_cols))\n", + "label_encoders = {}\n", + "for col in categorical_cols:\n", + " le = LabelEncoder()\n", + " df[col] = le.fit_transform(df[col])\n", + " label_encoders[col] = le\n", + "\n", + "df" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "# Standardize features using StandardScaler\n", + "from sklearn.preprocessing import StandardScaler\n", + "numerical_cols = df.select_dtypes(include=[\"int64\", \"float64\"])\n", + "scaler = StandardScaler()\n", + "df[numerical_cols] = scaler.fit_transform(df[numerical_cols])\n", + "df" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "# 1. Is the target imbalanced?\n", + "def check_target_imbalance(df, target_column):\n", + " print(\"Target Distribution:\")\n", + "\n", + " df[target_column].hist() # Yeah you can just do this :)\n", + " plt.show()\n", + "\n", + "check_target_imbalance(df, \"Delivery_Time\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "pip install catboost" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Import models\n", + "from sklearn.neighbors import KNeighborsClassifier\n", + "from sklearn.svm import SVC\n", + "from sklearn.tree import DecisionTreeClassifier\n", + "from sklearn.ensemble import RandomForestClassifier\n", + "from xgboost import XGBClassifier\n", + "from catboost import CatBoostClassifier\n", + "from sklearn.model_selection import train_test_split\n", + "\n", + "models = CatBoostClassifier(\n", + " verbose=0,\n", + " n_estimators=320,\n", + " max_depth=4\n", + " )\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Import tree-based model for classification (Decision Tree Classifier)\n", + "from sklearn.tree import DecisionTreeClassifier\n", + "\n", + "# Use previously generated random classification data\n", + "X, y = df.copy(), df.copy()\n", + "\n", + "# Split ratio (80% train, 20% test)\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y,test_size=0.2,random_state=42,shuffle=True)\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "n_splits = 5 # K\n", + "from sklearn.model_selection import StratifiedKFold\n", + "from sklearn.metrics import mean_absolute_error, mean_squared_error,accuracy_score\n", + "\n", + "# Stratified 5-Fold Cross-Validation, shuffled\n", + "skf = StratifiedKFold(n_splits=n_splits, shuffle=True, random_state=42)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "for fold_idx, (train_index, test_index) in enumerate(skf.split(X, y)):\n", + " print(f\"\\nFold {fold_idx + 1}/{n_splits}\")\n", + "\n", + " # 1. Split data\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", + "# Train Decision Tree Classifier\n", + " model = CatBoostClassifier(\n", + " verbose=0,\n", + " n_estimators=320,\n", + " max_depth=4) #\n", + " model.fit(X_train, y_train) # train\n", + " y_pred = model.predict(X_test) # validate\n", + "\n", + " # 3. Save metrics for that model in this fold\n", + " accuracy = accuracy_score(y_test, y_pred)\n", + " precision = precision_score(y_test, y_pred, zero_division=0)\n", + " recall = recall_score(y_test, y_pred, zero_division=0)\n", + " f1 = f1_score(y_test, y_pred, zero_division=0)\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "coeffs = {}\n", + "\n", + "coeffs['Lasso'] = models['LASSO Regression'].coef_\n", + "coeffs['Ridge'] = models['Ridge Regression'].coef_\n", + "\n", + "fig, axes = plt.subplots(1, 2, figsize=(15, 6))\n", + "axes = axes.flatten()\n", + "features = X.columns\n", + "\n", + "for i, (model_name, coef) in enumerate(coeffs.items()):\n", + " # Sort features by absolute coefficient value\n", + " absolute_coef = np.abs(coef)\n", + " sorted_idx = np.argsort(absolute_coef)\n", + "\n", + " ax = axes[i]\n", + " ax.barh(features[sorted_idx], coef[sorted_idx])\n", + " ax.set_title(f\"{model_name} Coefficients\")\n", + " ax.set_xlabel(\"Coefficient Value (Impact)\")\n", + "\n", + "plt.tight_layout()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/385/Q1.ipynb b/submissions_extracted/385/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..25b3133a00105b444a4f7aea5cebd8354f66ddda --- /dev/null +++ b/submissions_extracted/385/Q1.ipynb @@ -0,0 +1,295 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q1-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import numpy as np\n", + "import pandas as pd\n", + "import matplotlib.pyplot as plt\n", + "import os\n", + "\n", + "from sklearn.model_selection import train_test_split, StratifiedKFold, cross_val_score\n", + "from sklearn.preprocessing import StandardScaler, LabelEncoder, OneHotEncoder\n", + "from sklearn.ensemble import RandomForestClassifier\n", + "from sklearn.metrics import classification_report, confusion_matrix, accuracy_score\n", + "\n", + "import warnings\n", + "warnings.filterwarnings('ignore')\n", + "\n", + "\n", + "import seaborn as sns\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "dataset = os.path.join(path, 'Q1_data.csv')\n", + "df = pd.read_csv(dataset)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "df.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "df.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "plt.figure(figsize=(10, 5))\n", + "plt.hist(df['Delivery_Time'].dropna(), edgecolor='black')\n", + "plt.title('Graph')\n", + "plt.xlabel('Delivery Time')\n", + "plt.ylabel('Frequency')\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "df = df.drop(columns=['Order_ID'])" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "cols = df.columns\n", + "df_clean = df[cols].copy()\n", + "df_clean = df_clean.dropna()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "df_clean.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "def check_duplicates(df):\n", + " duplicates = df.duplicated().sum()\n", + " print(f\"Number of Duplicate Samples: {duplicates}\")\n", + " if duplicates > 0:\n", + " print(\"Dropping Duplicates...\")\n", + " df.drop_duplicates(inplace=True)\n", + " print(\"Duplicates Dropped.\")\n", + " else:\n", + " print(\"No Duplicate Samples Found.\")\n", + "\n", + "check_duplicates(df_clean)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "le = LabelEncoder()\n", + "cols = df_clean.select_dtypes(include='object').columns.to_list()\n", + "for i in cols:\n", + " df_clean[i] = le.fit_transform(df_clean[i])" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "X = df_clean.drop(columns = ['Delivery_Time'])\n", + "y = df_clean[\"Delivery_Time\"]" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "scaler = StandardScaler()\n", + "X = pd.DataFrame(scaler.fit_transform(X[X.columns]))" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "def check_target_imbalance(df, target_column):\n", + " print(\"Target Distribution:\")\n", + " print(df[target_column].value_counts(normalize=True))\n", + " sns.countplot(x=df[target_column])\n", + " plt.title(\"Target Distribution\")\n", + " plt.show()\n", + "\n", + "for i in df_clean.columns:\n", + " check_target_imbalance(df_clean, i)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "from sklearn.model_selection import StratifiedKFold\n", + "\n", + "# Show full dataset class distribution\n", + "full_ratio = (y.value_counts(normalize=True) * 100).sort_index()\n", + "print(\"Full Dataset Class Distribution\")\n", + "print(\" y class percentages:\", {k: f\"{v:.2f}%\" for k, v in full_ratio.items()})\n", + "print(\"-\" * 40)\n", + "\n", + "# Define Stratified K-Fold\n", + "skf = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)\n", + "\n", + "print(\"Stratified K-Fold Cross Validation\\n\" + \"-\"*40)\n", + "\n", + "for fold, (train_idx, test_idx) in enumerate(skf.split(X, y), start=1):\n", + " # indexing for each fold\n", + " X_train, X_test = X.iloc[train_idx], X.iloc[test_idx]\n", + " y_train, y_test = y.iloc[train_idx], y.iloc[test_idx]\n", + "\n", + " print(f\"Fold {fold}\")\n", + " print(\" X_train shape:\", X_train.shape)\n", + " print(\" X_test shape :\", X_test.shape)\n", + " print(\" y_train shape:\", y_train.shape)\n", + " print(\" y_test shape :\", y_test.shape)\n", + "\n", + " # showing class distribution\n", + " train_ratio = (y_train.value_counts(normalize=True) * 100).sort_index()\n", + " test_ratio = (y_test.value_counts(normalize=True) * 100).sort_index()\n", + "\n", + " print(\" y_train class percentages:\", {k: f\"{v:.2f}%\" for k, v in train_ratio.items()})\n", + " print(\" y_test class percentages :\", {k: f\"{v:.2f}%\" for k, v in test_ratio.items()})\n", + "\n", + " print(\"-\" * 40)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "from sklearn.ensemble import RandomForestRegressor\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2)\n", + "model = RandomForestRegressor(n_estimators=100, max_depth=20, random_state=42, n_jobs=-1)\n", + "model.fit(X_train, y_train)\n", + "print(\"Model trained!\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "from sklearn.metrics import mean_absolute_error\n", + "y_pred = model.predict(X_test)\n", + "\n", + "mae = mean_absolute_error(y_test, y_pred)\n", + "\n", + "print(f\"MAE: {mae:,.2f}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/385/Q2.ipynb b/submissions_extracted/385/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..73f78822b67e0095d6e0c37a116d0cdc83eee4de --- /dev/null +++ b/submissions_extracted/385/Q2.ipynb @@ -0,0 +1,340 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# PLEASE NOTE THAT I AM EXTREMELY SHORT ON TIME BECAUSE OF QUESTION 3 TOT" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q2-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import os\n", + "import pandas as pd\n", + "import numpy as np\n", + "from PIL import Image\n", + "from sklearn.model_selection import train_test_split\n", + "\n", + "# Load Labels\n", + "labels_df = pd.read_csv(os.path.join(path, \"labels.csv\"))\n", + "img_dir = os.path.join(path, \"images\")\n", + "\n", + "images = []\n", + "ages = []\n", + "\n", + "# Load Images and Resize\n", + "print(\"Loading images...\")\n", + "for index, row in labels_df.iterrows():\n", + " img_name = row.iloc[0]\n", + " age = row.iloc[1]\n", + " img_path = os.path.join(img_dir, img_name)\n", + "\n", + " if os.path.exists(img_path):\n", + " img = Image.open(img_path).convert('RGB')\n", + " img_array = np.array(img) / 255.0 # Normalize pixel values to [0, 1]\n", + " images.append(img_array)\n", + " ages.append(age)\n", + "\n", + "X = np.array(images)\n", + "y = np.array(ages)\n", + "\n", + "# Transpose image dimensions to match PyTorch format (N, C, H, W)\n", + "X = np.transpose(X, (0, 3, 1, 2))\n", + "\n", + "# Split Data\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n", + "\n", + "print(f\"X_train shape: {X_train.shape}\")\n", + "print(f\"X_test shape: {X_test.shape}\")\n", + "print(f\"y_train shape: {y_train.shape}\")\n", + "print(f\"y_test shape: {y_test.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Import required libraries\n", + "import torch\n", + "import torch.nn as nn\n", + "from torch.optim import AdamW\n", + "import matplotlib.pyplot as plt\n", + "from torch.utils.data import DataLoader, TensorDataset\n", + "from sklearn.model_selection import train_test_split\n", + "from sklearn.preprocessing import StandardScaler, LabelEncoder\n", + "from sklearn.metrics import mean_absolute_error, mean_squared_error, r2_score" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 1. Convert Numpy arrays to PyTorch Tensors\n", + "X_train = torch.tensor(X_train, dtype=torch.float32)\n", + "X_test = torch.tensor(X_test, dtype=torch.float32)\n", + "y_train = torch.tensor(y_train, dtype=torch.float32)\n", + "y_test = torch.tensor(y_test, dtype=torch.float32)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 2. Create TensorDataset objects\n", + "train_dataset = TensorDataset(X_train, y_train)\n", + "test_dataset = TensorDataset(X_test, y_test)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 3. Create DataLoaders\n", + "train_loader = DataLoader(train_dataset, batch_size=32, shuffle=True)\n", + "test_loader = DataLoader(test_dataset, batch_size=32, shuffle=False)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 4. Print shape of one batch\n", + "X_batch, y_batch = next(iter(train_loader))\n", + "print(f\"Training batch input shape: {X_batch.shape}\")\n", + "print(f\"Training batch labels shape: {y_batch.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 5. Display sample images\n", + "images, labels = next(iter(train_loader))\n", + "plt.figure(figsize=(8, 4))\n", + "for i in range(6):\n", + " plt.subplot(2, 3, i + 1)\n", + " # Convert from (C, H, W) to (H, W, C) for matplotlib\n", + " img = images[i].permute(1, 2, 0)\n", + " plt.imshow(img)\n", + " plt.title(f\"Label: {labels[i].item()}\")\n", + " plt.axis('off')\n", + "\n", + "plt.tight_layout()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your model class here:\n", + "class NN4Layer(nn.Module):\n", + " def __init__(self, input_dim, hidden_dim):\n", + " super(NN4Layer, self).__init__()\n", + " self.layer1 = nn.Linear(input_dim, hidden_dim)\n", + " self.layer2 = nn.Linear(hidden_dim, hidden_dim)\n", + " self.layer3 = nn.Linear(hidden_dim, hidden_dim)\n", + " self.layer4 = nn.Linear(hidden_dim, 1)\n", + " self.relu = nn.ReLU()\n", + "\n", + " def forward(self, x):\n", + " a1 = self.relu(self.layer1(x))\n", + " a2 = self.relu(self.layer2(a1))\n", + " a3 = self.relu(self.layer3(a2))\n", + " output = self.layer4(a3)\n", + "\n", + " return output" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your training loop here:\n", + "def train_one_epoch(model, optimizer, criterion, train_loader, device):\n", + " model.train()\n", + "\n", + " running_loss = 0.0\n", + "\n", + " for X_batch, y_batch in train_loader:\n", + " X_batch = X_batch.view(X_batch.size(0), -1).to(device)\n", + " y_batch = y_batch.to(device)\n", + "\n", + " outputs = model(X_batch)\n", + " loss = criterion(outputs, y_batch)\n", + "\n", + " optimizer.zero_grad()\n", + " loss.backward()\n", + " optimizer.step()\n", + "\n", + " running_loss += loss.item()\n", + " avg_loss = running_loss / len(train_loader)\n", + "\n", + " return avg_loss" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your validation loop here:\n", + "def validate(model, criterion, test_loader, device):\n", + " model.eval()\n", + "\n", + " running_loss = 0.0\n", + "\n", + " with torch.no_grad():\n", + " for X_batch, y_batch in test_loader:\n", + " X_batch = X_batch.view(X_batch.size(0), -1).to(device)\n", + " y_batch = y_batch.to(device)\n", + "\n", + " outputs = model(X_batch)\n", + " loss = criterion(outputs, y_batch)\n", + "\n", + " running_loss += loss.item()\n", + "\n", + " avg_loss = running_loss / len(test_loader)\n", + "\n", + " return avg_loss" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Define device, model, loss, optimizer:\n", + "device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n", + "\n", + "input_dim = 3 * 36 * 36\n", + "hidden_dim = 256\n", + "\n", + "# Instantiate regression model\n", + "model = NN4Layer(input_dim, hidden_dim).to(device)\n", + "\n", + "# Print the model architecture\n", + "print(\"Model Architecture:\\n\")\n", + "print(model)\n", + "\n", + "num_epochs = 20\n", + "learning_rate = 0.0001\n", + "\n", + "# Define criterion (loss function)\n", + "criterion = nn.MSELoss()\n", + "# Define optimizer\n", + "optimizer = AdamW(model.parameters(), learning_rate)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Start training for 20 epochs:\n", + "\n", + "train_losses = []\n", + "val_losses = []\n", + "\n", + "print('Starting Training...')\n", + "for epoch in range(num_epochs):\n", + " # Train one epoch\n", + " train_loss = train_one_epoch(model, optimizer, criterion, train_loader, device)\n", + "\n", + " # Validate\n", + " val_loss = validate(model, criterion, test_loader, device)\n", + "\n", + " train_losses.append(train_loss)\n", + " val_losses.append(val_loss)\n", + "\n", + " if (epoch + 1) % 5 == 0:\n", + " print(\n", + " f'Epoch [{epoch+1}/{num_epochs}], '\n", + " f'Train Loss: {train_loss:.4f}, '\n", + " f'Val Loss: {val_loss:.4f}'\n", + " )\n", + "\n", + "print('Training Complete!')" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "plt.figure(figsize=(7, 5))\n", + "\n", + "plt.plot(train_losses, label='Train Loss')\n", + "plt.plot(val_losses, label='Validation Loss')\n", + "plt.title('Loss over Epochs')\n", + "plt.xlabel('Epoch')\n", + "plt.ylabel('Loss')\n", + "plt.legend()\n", + "\n", + "plt.tight_layout()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2 (Bonus): Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/385/Q3.ipynb b/submissions_extracted/385/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..8c6166c4d5a95911f56de519624d10db2ced93fa --- /dev/null +++ b/submissions_extracted/385/Q3.ipynb @@ -0,0 +1,308 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q3-exam-data\")\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "%pip install catboost xgboost tqdm -q" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Importing libraries\n", + "import pandas as pd\n", + "import numpy as np\n", + "# The Cat\n", + "from catboost import CatBoostClassifier, Pool\n", + "# sklearn stuff\n", + "from sklearn.model_selection import StratifiedKFold\n", + "from sklearn.metrics import f1_score, accuracy_score, classification_report, confusion_matrix, precision_score, recall_score\n", + "from sklearn.model_selection import train_test_split, StratifiedKFold, cross_val_score\n", + "from sklearn.preprocessing import StandardScaler, LabelEncoder\n", + "from sklearn.ensemble import RandomForestClassifier\n", + "# drawing and stuff\n", + "import matplotlib.pyplot as plt\n", + "# basic\n", + "import os\n", + "import warnings\n", + "warnings.filterwarnings('ignore')" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "path = os.path.join(path, 'Q3_data.csv')\n", + "data = pd.read_csv(path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "data.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "data.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "data.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "\n", + "# I took numbers and categorical cols over here\n", + "numerical_cols = data.select_dtypes(include=[np.number]).columns\n", + "categorical_cols = data.select_dtypes(include=['object', 'category']).columns\n", + "\n", + "# replace empty numerical stuff with median in nums\n", + "for col in numerical_cols:\n", + " if data[col].isnull().sum() > 0:\n", + " data[col] = data[col].fillna(data[col].median())\n", + "\n", + "# categorical with mode\n", + "for col in categorical_cols:\n", + " if data[col].isnull().sum() > 0:\n", + " data[col] = data[col].fillna(data[col].mode()[0])" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "initial_rows = len(data)\n", + "data = data.drop_duplicates()\n", + "removed = initial_rows - len(data)\n", + "print(f\"Dupes: {removed}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "if len(categorical_cols) > 0:\n", + " data = pd.get_dummies(data, columns=categorical_cols.tolist(), drop_first=True)\n", + "else:\n", + " print(\"empty... O-O\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "if 'Target' in data.columns:\n", + " target = data['Target']\n", + " features = data.drop('Target', axis=1)\n", + " scaler = StandardScaler()\n", + " features_scaled = scaler.fit_transform(features)\n", + " data_scaled = pd.DataFrame(features_scaled, columns=features.columns)\n", + " data_scaled['Target'] = target.values\n", + "else:\n", + " scaler = StandardScaler()\n", + " data_scaled = pd.DataFrame(scaler.fit_transform(data), columns=data.columns)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "if 'Target' in data_scaled.columns:\n", + " target_counts = data_scaled['Target'].value_counts()\n", + " ratio = target_counts[0] / target_counts[1] if len(target_counts) > 1 else 0\n", + " print(f\"Class distribution: {dict(target_counts)}\")\n", + " print(f\"Ratio Class 0/Class 1: {ratio:.2f}\")\n", + " if ratio > 4 or ratio < 0.25:\n", + " print(\"Crazyyy imbalance\")\n", + " else:\n", + " print(\"Good to go!\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "X = data_scaled.drop('Target', axis=1)\n", + "y = data_scaled['Target']" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:\n", + "n_splits = 5\n", + "skf = StratifiedKFold(n_splits=n_splits, shuffle=True, random_state=42)\n", + "\n", + "# Storing our data\n", + "f1_scores = []\n", + "accuracy_scores = []\n", + "models = []\n", + "\n", + "# CatBoost parameters\n", + "catboost_params = {\n", + " 'iterations': 1000,\n", + " 'learning_rate': 0.05,\n", + " 'depth': 6,\n", + " 'l2_leaf_reg': 3,\n", + " 'border_count': 128,\n", + " 'loss_function': 'Logloss',\n", + " 'eval_metric': 'F1',\n", + " 'task_type': 'CPU',\n", + " 'random_seed': 42,\n", + " 'silent': True,\n", + " 'auto_class_weights': 'Balanced',\n", + " 'early_stopping_rounds': 50\n", + "}\n", + "\n", + "for fold, (train_idx, val_idx) in enumerate(skf.split(X, y), 1):\n", + "\n", + " # Split data\n", + " X_train, X_val = X.iloc[train_idx], X.iloc[val_idx]\n", + " y_train, y_val = y.iloc[train_idx], y.iloc[val_idx]\n", + "\n", + " print(f\"Train size: {len(X_train)} (Default: {y_train.sum()}, {y_train.mean()*100:.1f}%)\")\n", + " print(f\"Validation size: {len(X_val)} (Default: {y_val.sum()}, {y_val.mean()*100:.1f}%)\")\n", + "\n", + " # Creating CatBoost Pool objects\n", + " train_pool = Pool(X_train, y_train)\n", + " val_pool = Pool(X_val, y_val)\n", + "\n", + " # Train the CatBoost model\n", + " model = CatBoostClassifier(**catboost_params)\n", + " model.fit(train_pool, eval_set=val_pool, use_best_model=True, plot=False)\n", + "\n", + " # Make predictions\n", + " y_pred = model.predict(X_val)\n", + " y_pred_proba = model.predict_proba(X_val)[:, 1]\n", + "\n", + " # Calculate metrics\n", + " fold_f1 = f1_score(y_val, y_pred)\n", + " fold_accuracy = accuracy_score(y_val, y_pred)\n", + "\n", + " f1_scores.append(fold_f1)\n", + " accuracy_scores.append(fold_accuracy)\n", + " models.append(model)\n", + "\n", + " print(f\"F1 Score: {fold_f1:.4f}\")\n", + " print(f\"Accuracy: {fold_accuracy:.4f}\")\n", + "\n", + " # Additional metrics for better insight\n", + " fold_precision = precision_score(y_val, y_pred)\n", + " fold_recall = recall_score(y_val, y_pred)\n", + " print(f\"Precision: {fold_precision:.4f}\")\n", + " print(f\"Recall: {fold_recall:.4f}\")\n", + "\n", + "print(f\"Average F1 Score: {np.mean(f1_scores):.4f}\")\n", + "print(f\"Standard deviation: {np.std(f1_scores):.4f}\")\n", + "print(f\"Range: [{min(f1_scores):.4f}, {max(f1_scores):.4f}]\")\n", + "print(f\"Average Accuracy: {np.mean(accuracy_scores):.4f}\")\n", + "print(f\"Standard deviation: {np.std(accuracy_scores):.4f}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# first collecting feature importance from all the models\n", + "feature_importances = []\n", + "for i, model in enumerate(models):\n", + " importances = model.get_feature_importance()\n", + " feature_importances.append(importances)\n", + "\n", + "# Average importance across them folds\n", + "avg_importances = np.mean(feature_importances, axis=0)\n", + "feature_importance_df = pd.DataFrame({\n", + " 'Feature': X.columns,\n", + " 'Importance': avg_importances\n", + "}).sort_values('Importance', ascending=False)\n", + "\n", + "# This is OUR GOLDEN FEATURE!!\n", + "golden_feature = feature_importance_df.iloc[0]\n", + "print(f\"The Golden Feature is: '{golden_feature}'\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# I HAVE NO TIME TOT !!" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/386/Q1.ipynb b/submissions_extracted/386/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..94bc79c70f049a491adf6fbeeed01a9ddb438c57 --- /dev/null +++ b/submissions_extracted/386/Q1.ipynb @@ -0,0 +1,335 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "import numpy as np\n", + "import pandas as pd\n", + "import matplotlib.pyplot as plt\n", + "import os\n", + "from sklearn.impute import SimpleImputer\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q1-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "food_delivery_path = os.path.join(path, 'Q1_data.csv')\n", + "df_food_delivery = pd.read_csv(food_delivery_path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "df_food_delivery.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "df_food_delivery.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "df_food_delivery.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "# delivery_time distribution (target variable)\n", + "plt.figure(figsize=(10, 5))\n", + "plt.hist(df_food_delivery['Delivery_Time'].dropna(), bins=15, edgecolor='black')\n", + "plt.title('Delivery Time Distribution')\n", + "plt.xlabel('Delivery Time')\n", + "plt.ylabel('Frequency')\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "df_food_delivery.drop(columns=['Order_ID'])" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "# Missing values\n", + "print(\"Missing values:\")\n", + "print(df_food_delivery.isnull().sum())\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "num_cols = df_food_delivery.select_dtypes(include=['number']).columns\n", + "cat_cols = df_food_delivery.select_dtypes(include=['object', 'category']).columns\n", + "\n", + "num_imputer = SimpleImputer(strategy='median')\n", + "cat_imputer = SimpleImputer(strategy='most_frequent')\n", + "\n", + "# use .copy() to keep original df safe\n", + "df_clean = df_food_delivery.copy()\n", + "\n", + "# Fill Missing Values\n", + "df_clean[num_cols] = num_imputer.fit_transform(df_food_delivery[num_cols])\n", + "df_clean[cat_cols] = cat_imputer.fit_transform(df_food_delivery[cat_cols])\n", + "\n", + "print(f\"Missing values after cleaning: {df_clean.isnull().sum().sum()}\")\n", + "print(df_clean.isnull().sum())" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "from numpy._core.defchararray import index\n", + "# Task 3: Write your code here:\n", + "# Duplicate Check\n", + "\n", + "def check_duplicates(df):\n", + " duplicates = df.duplicated().sum()\n", + " print(f\"Number of Duplicate Samples: {duplicates}\")\n", + " if duplicates > 0:\n", + " print(\"Dropping Duplicates...\")\n", + " df.drop_duplicates(inplace=True)\n", + " print(\"Duplicates Dropped.\")\n", + " else:\n", + " print(\"No Duplicate Samples Found.\")\n", + "\n", + "check_duplicates(df_clean)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "from sklearn.preprocessing import OneHotEncoder #import OneHotEncoder\n", + "\n", + "print('data before encoding:\\n', cat_cols) #show before encoding\n", + "\n", + "onehot_encoder = OneHotEncoder(handle_unknown='ignore') # Instantiate OneHotEncoder\n", + "data_onehot_encoded = onehot_encoder.fit_transform() # Apply fit_transform to the copied\n", + "\n", + "print('\\nData after encoding:\\n', data_onehot_encoded) #show after encoding" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "from sklearn.preprocessing import StandardScaler #import StandardScaler\n", + "\n", + "print('data before scaling:\\n', df_clean) #show before scaling\n", + "standard_scaler = StandardScaler() # Instantiate StandardScaler\n", + "data_standard_scaled = standard_scaler.fit_transform(df_clean) # Apply fit_transform\n", + "\n", + "print('\\nData after scaling:\\n', data_standard_scaled) #show after scaling" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 6: Write your code here:\n", + "import seaborn as sns\n", + "\n", + "TARGET_COL = 'Delivery_Time'\n", + "\n", + "plt.figure(figsize=(8, 5))\n", + "if df_clean[TARGET_COL].dtype == 'object' or df_clean[TARGET_COL].nunique() < 10:\n", + " # Classification Problem\n", + " sns.countplot(x=TARGET_COL, data=df_clean, palette='viridis')\n", + " plt.title(f\"Target Distribution: {TARGET_COL} (Classification)\")\n", + " plt.ylabel(\"Count\")\n", + "else:\n", + " # Regression Problem\n", + " sns.histplot(df_clean[TARGET_COL], kde=True, color='blue')\n", + " plt.title(f\"Target Distribution: {TARGET_COL} (Regression)\")\n", + " plt.xlabel(\"Value\")\n", + "plt.show()\n", + "\n", + "# balanced" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "from sklearn.model_selection import train_test_split\n", + "\n", + "# --- 1. Separate Features (X) and Target (y) ---\n", + "X = df_clean.drop(columns=[TARGET_COL])\n", + "y = df_clean[TARGET_COL]\n", + "\n", + "# --- 2. Split Data ---\n", + "# Logic: If Classification -> Use Stratify. If Regression -> No Stratify.\n", + "is_classification = (y.dtype == 'object') or (y.nunique() < 20)\n", + "\n", + "if is_classification:\n", + " print(\"Detected Classification Task -> Using Stratified Split\")\n", + " X_train, X_test, y_train, y_test = train_test_split(\n", + " X, y, test_size=0.2, random_state=42, stratify=y\n", + " )\n", + "else:\n", + " print(\"Detected Regression Task -> Using Random Split\")\n", + " X_train, X_test, y_train, y_test = train_test_split(\n", + " X, y, test_size=0.2, random_state=42\n", + " )\n", + "\n", + "print(f\"Train Shape: {X_train.shape}\")\n", + "print(f\"Test Shape: {X_test.shape}\")\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:\n", + "from sklearn.ensemble import RandomForestRegressor\n", + "from sklearn.model_selection import train_test_split, StratifiedKFold, KFold\n", + "from sklearn.metrics import (mean_absolute_error, mean_squared_error, r2_score,\n", + " accuracy_score, precision_score, recall_score, f1_score,\n", + " classification_report, confusion_matrix)\n", + "\n", + "scaler = StandardScaler()\n", + "X_train_scaled = scaler.fit_transform(X_train)\n", + "X_test_scaled = scaler.transform(X_test)\n", + "\n", + "model = {}\n", + "model['Random Forest'] = RandomForestRegressor(n_estimators=100, random_state=42)\n", + "\n", + "kfold = KFold(n_splits=5, shuffle=True, random_state=42)\n", + "\n", + "mae_scores = []\n", + "rmse_scores = []\n", + "\n", + "for train_idx, val_idx in kfold.split(X_train_scaled):\n", + " X_fold_train, X_fold_val = X_train_scaled[train_idx], X_train_scaled[val_idx]\n", + " y_fold_train, y_fold_val = y_train.iloc[train_idx], y_train.iloc[val_idx]\n", + "\n", + " # Train and predict\n", + " model.fit(X_fold_train, y_fold_train)\n", + " y_fold_pred = model.predict(X_fold_val)\n", + "\n", + " # Calculate metrics\n", + " mae_scores.append(mean_absolute_error(y_fold_val, y_fold_pred))\n", + "\n", + "mae_scores = np.array(mae_scores)\n", + "\n", + "print(f\"5-Fold CV Results:\")\n", + "print(f\"MAE: ${mae_scores.mean():,.2f}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "importance = pd.DataFrame({\n", + " 'feature': num_cols + cat_cols,\n", + " 'importance': model.feature_importances_\n", + "}).sort_values('importance', ascending=False)\n", + "\n", + "plt.figure(figsize=(10, 6))\n", + "plt.barh(importance['feature'], importance['importance'], color='purple')\n", + "plt.xlabel('Importance')\n", + "plt.title('Feature Importance')\n", + "plt.gca().invert_yaxis()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "\n", + "sns.histplot(df_clean['Delivery_Time'], kde=True, color='skyblue')\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/386/Q2.ipynb b/submissions_extracted/386/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..28039955b3d7b19e9d0ce7f8ef892a5eedeb4c26 --- /dev/null +++ b/submissions_extracted/386/Q2.ipynb @@ -0,0 +1,299 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q2-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import os\n", + "import pandas as pd\n", + "import numpy as np\n", + "from PIL import Image\n", + "from sklearn.model_selection import train_test_split\n", + "\n", + "# Load Labels\n", + "labels_df = pd.read_csv(os.path.join(path, \"labels.csv\"))\n", + "img_dir = os.path.join(path, \"images\")\n", + "\n", + "images = []\n", + "ages = []\n", + "\n", + "# Load Images and Resize\n", + "print(\"Loading images...\")\n", + "for index, row in labels_df.iterrows():\n", + " img_name = row.iloc[0]\n", + " age = row.iloc[1]\n", + " img_path = os.path.join(img_dir, img_name)\n", + "\n", + " if os.path.exists(img_path):\n", + " img = Image.open(img_path).convert('RGB')\n", + " img_array = np.array(img) / 255.0 # Normalize pixel values to [0, 1]\n", + " images.append(img_array)\n", + " ages.append(age)\n", + "\n", + "X = np.array(images)\n", + "y = np.array(ages)\n", + "\n", + "# Transpose image dimensions to match PyTorch format (N, C, H, W)\n", + "X = np.transpose(X, (0, 3, 1, 2))\n", + "\n", + "# Split Data\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n", + "\n", + "print(f\"X_train shape: {X_train.shape}\")\n", + "print(f\"X_test shape: {X_test.shape}\")\n", + "print(f\"y_train shape: {y_train.shape}\")\n", + "print(f\"y_test shape: {y_test.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 1. Convert Numpy arrays to PyTorch Tensors\n", + "\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 2. Create TensorDataset objects\n", + "\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 3. Create DataLoaders\n", + "\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 4. Print shape of one batch\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 5. Display sample images\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your model class here:\n", + "class NN3Layer(nn.Module):\n", + "\n", + " def __init__(self, input_dim, hidden_dim, output_dim):\n", + " super(NN3Layer, self).__init__()\n", + "\n", + " # First linear layer: input features -> hidden layer\n", + " self.layer1 = nn.Linear(input_dim, hidden_dim)\n", + "\n", + " # Second linear layer: hidden layer -> hidden layer\n", + " self.layer2 = nn.Linear(hidden_dim, hidden_dim)\n", + "\n", + " # Output layer: hidden layer -> number of classes (logits)\n", + " self.layer3 = nn.Linear(hidden_dim, output_dim)\n", + "\n", + " # ReLU activation for non-linearity\n", + " self.relu = nn.ReLU()\n", + "\n", + " # Defines how input data flows through the network\n", + " def forward(self, x):\n", + " # First hidden layer\n", + " z1 = self.layer1(x)\n", + " a1 = self.relu(z1)\n", + "\n", + " # Second hidden layer\n", + " z2 = self.layer2(a1)\n", + " a2 = self.relu(z2)\n", + "\n", + " # Output layer (raw scores / logits)\n", + " output = self.layer3(a2) # there is something missing here, remember? :)\n", + "\n", + " return output\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your training loop here:\n", + "def train_one_epoch(model, optimizer, criterion, train_loader, device):\n", + " # Set the model to training mode\n", + " model.train()\n", + "\n", + " running_loss = 0.0\n", + "\n", + " for X_batch, y_batch in train_loader:\n", + " # Move batch to the selected device\n", + " X_batch = X_batch.view(X_batch.size(0), -1).to(device)\n", + " y_batch = y_batch.to(device)\n", + "\n", + " # Forward pass\n", + " # TODO: make predictions\n", + " outputs = # \n", + " # TODO: compute loss\n", + " loss = # \n", + "\n", + " # Backward pass & optimization\n", + " optimizer.zero_grad() # Clear previous gradients\n", + " loss.backward() # Compute gradients\n", + " optimizer.step() # Update model parameters\n", + "\n", + " running_loss += loss.item()\n", + "\n", + " # Average loss over all batches\n", + " avg_loss = running_loss / len(train_loader)\n", + "\n", + " return avg_loss" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your validation loop here:\n", + "def validate(model, criterion, test_loader, device):\n", + " # Set the model to evaluation mode\n", + " model.eval()\n", + "\n", + " running_loss = 0.0\n", + " correct = 0\n", + " total = 0\n", + "\n", + " with torch.no_grad():\n", + " for X_batch, y_batch in test_loader:\n", + " # Move data to device\n", + " X_batch = X_batch.view(X_batch.size(0), -1).to(device)\n", + " y_batch = y_batch.to(device)\n", + "\n", + " # Forward pass\n", + " # TODO: make predictions\n", + " outputs = # \n", + " # TODO: compute loss\n", + " loss = # \n", + " running_loss += loss.item()\n", + "\n", + " # TODO: Apply Softmax to get probabilities\n", + " probabilities = F.softmax(# , dim=1)\n", + "\n", + " # TODO: Multiclass predictions\n", + " predicted = torch.argmax(# , dim=1)\n", + "\n", + " # Accuracy calculation\n", + " correct += (predicted == y_batch).sum().item()\n", + " total += y_batch.size(0)\n", + "\n", + " avg_loss = running_loss / len(test_loader)\n", + " # TODO: how do we calculate accuracy?\n", + " accuracy = # \n", + "\n", + " return avg_loss, accuracy\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Define device, model, loss, optimizer:\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Start training for 20 epochs:\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + " Plotting results\n", + "plt.figure(figsize=(7, 5))\n", + "\n", + "plt.plot(train_losses, label='Train Loss')\n", + "plt.plot(val_losses, label='Validation Loss')\n", + "plt.title('Loss over Epochs')\n", + "plt.xlabel('Epoch')\n", + "plt.ylabel('Loss')\n", + "plt.legend()\n", + "\n", + "plt.tight_layout()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2 (Bonus): Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/386/Q3.ipynb b/submissions_extracted/386/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..87d31bc5aa321b2d7e186db649ce5af2b7b4b659 --- /dev/null +++ b/submissions_extracted/386/Q3.ipynb @@ -0,0 +1,303 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "import numpy as np\n", + "import pandas as pd\n", + "import matplotlib.pyplot as plt\n", + "import os\n", + "from sklearn.impute import SimpleImputer\n", + "\n", + "# Download latest version\n", + "\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q3-exam-data\")\n", + "\n", + "\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "Q3_data_path = os.path.join(path, 'Q3_data.csv')\n", + "df_Q3_data = pd.read_csv(Q3_data_path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "df_Q3_data.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "df_Q3_data.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "df_Q3_data.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "# Missing values\n", + "print(\"Missing values:\")\n", + "print(df_Q3_data.isnull().sum())\n", + "\n", + "num_cols = df_Q3_data.select_dtypes(include=['number']).columns\n", + "\n", + "num_imputer = SimpleImputer(strategy='median')\n", + "\n", + "# use .copy() to keep original df safe\n", + "df_clean = df_Q3_data.copy()\n", + "\n", + "# Fill Missing Values\n", + "df_clean[num_cols] = num_imputer.fit_transform(df_Q3_data[num_cols])\n", + "\n", + "print(f\"Missing values after cleaning: {df_clean.isnull().sum().sum()}\")\n", + "print(df_clean.isnull().sum())" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "# Duplicate Check\n", + "\n", + "def check_duplicates(df):\n", + " duplicates = df.duplicated().sum()\n", + " print(f\"Number of Duplicate Samples: {duplicates}\")\n", + " if duplicates > 0:\n", + " print(\"Dropping Duplicates...\")\n", + " df.drop_duplicates(inplace=True)\n", + " print(\"Duplicates Dropped.\")\n", + " else:\n", + " print(\"No Duplicate Samples Found.\")\n", + "\n", + "check_duplicates(df_Q3_data)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "# there are no categorical variables, there is no need" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "from sklearn.preprocessing import StandardScaler #import StandardScaler\n", + "\n", + "print('data before scaling:\\n', df_Q3_data) #show before scaling\n", + "standard_scaler = StandardScaler() # Instantiate StandardScaler\n", + "data_standard_scaled = standard_scaler.fit_transform(df_Q3_data) # Apply fit_transform\n", + "\n", + "print('\\nData after scaling:\\n', data_standard_scaled) #show after scaling" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "import seaborn as sns\n", + "\n", + "TARGET_COL = 'Target'\n", + "\n", + "plt.figure(figsize=(8, 5))\n", + "if df_clean[TARGET_COL].dtype == 'object' or df_clean[TARGET_COL].nunique() < 10:\n", + " # Classification Problem\n", + " sns.countplot(x=TARGET_COL, data=df_clean, palette='viridis')\n", + " plt.title(f\"Target Distribution: {TARGET_COL} (Classification)\")\n", + " plt.ylabel(\"Count\")\n", + "else:\n", + " # Regression Problem\n", + " sns.histplot(df_clean[TARGET_COL], kde=True, color='blue')\n", + " plt.title(f\"Target Distribution: {TARGET_COL} (Regression)\")\n", + " plt.xlabel(\"Value\")\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "from sklearn.model_selection import train_test_split\n", + "\n", + "# --- 1. Separate Features (X) and Target (y) ---\n", + "X = df_Q3_data.drop(columns=[TARGET_COL])\n", + "y = df_Q3_data[TARGET_COL]\n", + "\n", + "# --- 2. Split Data ---\n", + "# Logic: If Classification -> Use Stratify. If Regression -> No Stratify.\n", + "is_classification = (y.dtype == 'object') or (y.nunique() < 20)\n", + "\n", + "if is_classification:\n", + " print(\"Detected Classification Task -> Using Stratified Split\")\n", + " X_train, X_test, y_train, y_test = train_test_split(\n", + " X, y, test_size=0.2, random_state=42, stratify=y\n", + " )\n", + "else:\n", + " print(\"Detected Regression Task -> Using Random Split\")\n", + " X_train, X_test, y_train, y_test = train_test_split(\n", + " X, y, test_size=0.2, random_state=42\n", + " )\n", + "\n", + "print(f\"Train Shape: {X_train.shape}\")\n", + "print(f\"Test Shape: {X_test.shape}\")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:\n", + "!pip install catboost\n", + "from catboost import CatBoostClassifier, CatBoostRegressor\n", + "from sklearn.model_selection import train_test_split, StratifiedKFold, KFold\n", + "from sklearn.metrics import (mean_absolute_error, mean_squared_error, r2_score,\n", + " accuracy_score, precision_score, recall_score, f1_score,\n", + " classification_report, confusion_matrix)\n", + "\n", + "scaler = StandardScaler()\n", + "X_train_scaled = scaler.fit_transform(X_train)\n", + "X_test_scaled = scaler.transform(X_test)\n", + "\n", + "model = {}\n", + "model['CatBoost'] = CatBoostRegressor(verbose=0, random_state=42) # verbose=0 silences output\n", + "\n", + "kfold = KFold(n_splits=5, shuffle=True, random_state=42)\n", + "\n", + "mae_scores = []\n", + "rmse_scores = []\n", + "\n", + "for train_idx, val_idx in kfold.split(X_train_scaled):\n", + " X_fold_train, X_fold_val = X_train_scaled[train_idx], X_train_scaled[val_idx]\n", + " y_fold_train, y_fold_val = y_train.iloc[train_idx], y_train.iloc[val_idx]\n", + "\n", + " # Train and predict\n", + " model.fit(X_fold_train, y_fold_train)\n", + " y_fold_pred = model.predict(X_fold_val)\n", + "\n", + " # Calculate metrics\n", + " mae_scores.append(mean_absolute_error(y_fold_val, y_fold_pred))\n", + "\n", + "mae_scores = np.array(mae_scores)\n", + "\n", + "print(f\"5-Fold CV Results:\")\n", + "print(f\"MAE: ${mae_scores.mean():,.2f}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Predictions and metrics\n", + "y_pred = model.predict(X_test_scaled)\n", + "\n", + "print(f\"Accuracy: {accuracy_score(y_test, y_pred):.4f}\\n\")\n", + "print(classification_report(y_test, y_pred, target_names=['Target']))" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "\n", + "feature_importance = pd.DataFrame({\n", + " 'feature': feature_cols,\n", + " 'importance': model.feature_importances_\n", + "}).sort_values('importance', ascending=False)\n", + "\n", + "plt.figure(figsize=(10, 6))\n", + "plt.barh(feature_importance['feature'], feature_importance['importance'])\n", + "plt.xlabel('Importance')\n", + "plt.title('Feature Importance')\n", + "plt.gca().invert_yaxis()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/387/Q1.ipynb b/submissions_extracted/387/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..489c96719cdc4de8780af4fa9f518a4fe6f5c933 --- /dev/null +++ b/submissions_extracted/387/Q1.ipynb @@ -0,0 +1,414 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import pandas as pd\n", + "import numpy as np\n", + "import matplotlib.pyplot as plt\n", + "import seaborn as sns\n", + "import kagglehub\n", + "import os\n", + "from tqdm import tqdm\n", + "\n", + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q1-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "csv_path = \"<<<< From side bar \"\n", + "df = pd.read_csv('/kaggle/input/q1-exam-data/Q1_data.csv')\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "df.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "df.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "# Price distribution (target variable)\n", + "plt.figure(figsize=(10, 5))\n", + "plt.hist(df_delivery['Delivery_Time'].dropna(), bins=50, edgecolor='black')\n", + "plt.title('Delivery_Time')\n", + "plt.xlabel('distance')\n", + "plt.ylabel('Time')\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "df_clean = df.drop(\"Order_ID\", axis = 1)\n", + "df_clean.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "def check_missing_values(df):\n", + " missing_values = df.isnull().sum()\n", + " print(\"Missing Values per Column:\")\n", + " print(missing_values[missing_values > 0])\n", + " if missing_values.any():\n", + " print(\"\\nHandle Missing Values as needed.\")\n", + " else:\n", + " print(\"\\nNo Missing Values Found.\")\n", + "\n", + "check_missing_values(df_clean)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "# 4. Do we have duplicate samples?\n", + "def check_duplicates(df):\n", + " duplicates = df.duplicated().sum()\n", + " print(f\"Number of Duplicate Samples: {duplicates}\")\n", + " if duplicates > 0:\n", + " print(\"Dropping Duplicates...\")\n", + " df.drop_duplicates(inplace=True)\n", + " print(\"Duplicates Dropped.\")\n", + " else:\n", + " print(\"No Duplicate Samples Found.\")\n", + "\n", + "check_duplicates(df_clean)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "# 3. Do we have categorical columns?\n", + "from sklearn.preprocessing import LabelEncoder\n", + "\n", + "categorical_cols = df_clean.select_dtypes(include=[\"object\"]).columns\n", + "\n", + "print(\"Categorical Columns:\", list(categorical_cols))\n", + "\n", + "# Encoder\n", + "from sklearn.preprocessing import LabelEncoder\n", + "\n", + "label_encoders = {}\n", + "for col in categorical_cols:\n", + " le = LabelEncoder()\n", + " df_clean[col] = le.fit_transform(df_clean[col])\n", + " label_encoders[col] = le" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# to fill mode\n", + "def fill_with_mode(df, columns):\n", + " df_clean = df.copy()\n", + " for col in columns:\n", + " if col in df_clean.columns:\n", + " mode_value = df_clean[col].mode()\n", + " if len(mode_value) > 0:\n", + " df_clean[col] = df_clean[col].fillna(mode_value[0])\n", + " return df_clean\n", + "# Use\n", + "cols_to_fill_mode = ['Weather', 'Traffic_Level', 'Time_of_Day', 'Vehicle_Type']\n", + "df_clean = fill_with_mode(df_clean, cols_to_fill_mode)\n", + "df_clean.info()\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "def fill_with_mode(df, columns):\n", + " df_clean = df.copy()\n", + " for col in columns:\n", + " if col in df_clean.columns:\n", + " mode_value = df_clean[col].mode()\n", + " if len(mode_value) > 0:\n", + " df_clean[col] = df_clean[col].fillna(mode_value[0])\n", + " return df_clean\n", + "# Use\n", + "cols_to_fill_mode = ['Courier_Experience_yrs', 'Delivery_Time']\n", + "df_clean = fill_with_mode(df_clean, cols_to_fill_mode)\n", + "df_clean.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "from sklearn.preprocessing import StandardScaler # can be StandardScaler\n", + "\n", + "features = df_clean.columns.drop(\"Delivery_Time\") # DON'T SCALE THE TARGET\n", + "\n", + "scaler = StandardScaler() # can be StandardScaler()\n", + "df_clean[features] = scaler.fit_transform(df_clean[features])" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 6: Write your code here:\n", + "def check_target_distribution(df, target_column):\n", + " df[target_column].hist(bins=30, edgecolor='black')\n", + "\n", + " plt.title(f\"Target Distribution ({target_column})\")\n", + " plt.xlabel(target_column)\n", + " plt.ylabel(\"Frequency\")\n", + " plt.grid(False)\n", + "\n", + " plt.show()\n", + "\n", + "check_target_distribution(df_clean, 'Delivery_Time')" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "X = df_clean.drop(\"Delivery_Time\", axis=1).astype(float)\n", + "y = df_clean['Delivery_Time'].astype(float)\n", + "\n", + "from sklearn.model_selection import KFold\n", + "n_splits = 5 # K=5 Folds\n", + "# 5-Fold Cross-Validation, shuffled\n", + "kf = KFold(n_splits=n_splits, shuffle=True, random_state=42)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:\n", + "from sklearn.ensemble import RandomForestRegressor\n", + "from sklearn.metrics import mean_absolute_error\n", + "\n", + "\n", + "model = RandomForestRegressor(n_estimators=200)\n", + "from sklearn.metrics import mean_absolute_error\n", + "\n", + "mae_results = []\n", + "\n", + "\n", + "\n", + "kf = KFold(n_splits=5, shuffle=True, random_state=42)\n", + "\n", + "for fold_idx, (train_index, test_index) in enumerate(kf.split(X)):\n", + " print(f\"\\nFold {fold_idx + 1}/{n_splits}\")\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", + "\n", + " # Train\n", + " model.fit(X_train, y_train)\n", + "\n", + " # Predict\n", + " y_pred = model.predict(X_test)\n", + "\n", + " # Calculate metrics\n", + " mae = mean_absolute_error(y_test, y_pred)\n", + "\n", + " # Store results\n", + " mae_results.append(mae)\n", + " # all_results[model_name][\"rmse\"].append(rmse)\n", + "\n", + "print(f\" MAE: {np.mean(mae_results):.4f}\")\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "feature_cols = ['Distance_km', 'Weather', 'Traffic_Level', 'Time_of_Day',\n", + " 'Vehicle_Type', 'Preparation_Time_min', 'Courier_Experience_yrs']\n", + "\n", + "feature_importance = pd.DataFrame({\n", + " 'feature': feature_cols,\n", + " 'importance': model.feature_importances_\n", + "}).sort_values('importance', ascending=False)\n", + "\n", + "plt.figure(figsize=(10, 6))\n", + "plt.barh(feature_importance['feature'], feature_importance['importance'])\n", + "plt.xlabel('Importance')\n", + "plt.title('Feature Importance')\n", + "plt.gca().invert_yaxis()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "# Plot Predictions vs Ground Truth\n", + "plt.figure(figsize=(6, 4))\n", + "plt.scatter(y_test, y_pred, alpha=0.6)\n", + "plt.plot(\n", + " [y_test.min(), y_test.max()],\n", + " [y_test.min(), y_test.max()],\n", + " \"r--\",\n", + " linewidth=2\n", + ")\n", + "\n", + "plt.xlabel(\"Actual Exam Scores (Ground Truth)\")\n", + "plt.ylabel(\"Predicted Exam Scores\")\n", + "plt.title(\"Linear Regression: Predictions vs Ground Truth\")\n", + "plt.grid(True)\n", + "\n", + "plt.tight_layout()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:\n", + "from sklearn.tree import DecisionTreeRegressor\n", + "%pip install catboost\n", + "from catboost import CatBoostRegressor\n", + "\n", + "models = {\n", + " \"Random Forest Regressor\": RandomForestRegressor(n_estimators=200),\n", + " \"CatBoost\": CatBoostRegressor(verbose=0)\n", + "}\n", + "from sklearn.metrics import mean_squared_error as sklearn_mse, mean_absolute_error, r2_score\n", + "from sklearn.metrics import mean_absolute_error\n", + "\n", + "mae_results = []\n", + "# R train\n", + "# Storage for results\n", + "all_results = {}\n", + "\n", + "for name in models:\n", + " all_results[name] = {'mse': []}\n", + "\n", + "kf = KFold(n_splits=5, shuffle=True, random_state=42)\n", + "\n", + "for fold_idx, (train_index, test_index) in enumerate(kf.split(X)):\n", + " print(f\"\\nFold {fold_idx + 1}/{n_splits}\")\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", + " for model_name, model in models.items():\n", + " print(f\"Training {model_name}...\")\n", + "\n", + " # Train\n", + " model.fit(X_train, y_train)\n", + "\n", + " # Predict\n", + " y_pred = model.predict(X_test)\n", + "\n", + " # Calculate metrics\n", + " mae = mean_absolute_error(y_test, y_pred)\n", + "\n", + " mae_results.append(mae)\n", + "\n", + "\n", + "print(f\" MAE: {np.mean(mae_results):.4f}\")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/387/Q2.ipynb b/submissions_extracted/387/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..266149c390aa2f0019b8982200e4b45811073762 --- /dev/null +++ b/submissions_extracted/387/Q2.ipynb @@ -0,0 +1,426 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "import pandas as pd\n", + "import numpy as np\n", + "import torch\n", + "import torch.nn as nn\n", + "from torch.optim import AdamW\n", + "import matplotlib.pyplot as plt\n", + "from torch.utils.data import DataLoader, TensorDataset\n", + "from sklearn.model_selection import train_test_split\n", + "from sklearn.preprocessing import StandardScaler, LabelEncoder\n", + "from sklearn.metrics import mean_absolute_error, mean_squared_error, r2_score\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q2-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import os\n", + "import pandas as pd\n", + "import numpy as np\n", + "from PIL import Image\n", + "from sklearn.model_selection import train_test_split\n", + "\n", + "# Load Labels\n", + "labels_df = pd.read_csv(os.path.join(path, \"labels.csv\"))\n", + "img_dir = os.path.join(path, \"images\")\n", + "\n", + "images = []\n", + "ages = []\n", + "\n", + "# Load Images and Resize\n", + "print(\"Loading images...\")\n", + "for index, row in labels_df.iterrows():\n", + " img_name = row.iloc[0]\n", + " age = row.iloc[1]\n", + " img_path = os.path.join(img_dir, img_name)\n", + "\n", + " if os.path.exists(img_path):\n", + " img = Image.open(img_path).convert('RGB')\n", + " img_array = np.array(img) / 255.0 # Normalize pixel values to [0, 1]\n", + " images.append(img_array)\n", + " ages.append(age)\n", + "\n", + "X = np.array(images)\n", + "y = np.array(ages)\n", + "\n", + "# Transpose image dimensions to match PyTorch format (N, C, H, W)\n", + "X = np.transpose(X, (0, 3, 1, 2))\n", + "\n", + "# Split Data\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n", + "\n", + "print(f\"X_train shape: {X_train.shape}\")\n", + "print(f\"X_test shape: {X_test.shape}\")\n", + "print(f\"y_train shape: {y_train.shape}\")\n", + "print(f\"y_test shape: {y_test.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 1. Convert Numpy arrays to PyTorch Tensors\n", + "import torch\n", + "X_train = torch.tensor(X_train, dtype=torch.float32)\n", + "X_test = torch.tensor(X_test, dtype=torch.float32)\n", + "y_train = torch.tensor(y_train, dtype=torch.float32)\n", + "y_test = torch.tensor(y_test, dtype=torch.float32)\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 2. Create TensorDataset objects\n", + "train_dataset = TensorDataset(X_train, y_train)\n", + "test_dataset = TensorDataset(X_test, y_test)\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 3. Create DataLoaders\n", + "\n", + "train_loader = DataLoader(train_dataset, batch_size=32, shuffle=True)\n", + "test_loader = DataLoader(test_dataset, batch_size=32, shuffle=False)\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 4. Print shape of one batch\n", + "print(\"Train dataset:\", len(train_dataset))\n", + "print(\"Test dataset:\", len(test_dataset))\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Get the first batch from the training DataLoader\n", + "X_batch, y_batch = next(iter(train_loader))\n", + "print(f\"Training batch input shape: {X_batch.shape}\")\n", + "print(f\"Training batch labels shape: {y_batch.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 5. Display sample images\n", + "\n", + "# Get one batch of images and labels\n", + "images, labels = next(iter(train_loader))\n", + "\n", + "# Display the first 6 images in the batch\n", + "plt.figure(figsize=(8, 4))\n", + "\n", + "for i in range(6):\n", + " plt.subplot(2, 3, i + 1)\n", + "\n", + " img = images[i].permute(1, 2, 0)\n", + " plt.imshow(img)\n", + " plt.title(f\"Label: {labels[i].item()}\")\n", + " plt.axis('off')\n", + "plt.tight_layout()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "class NN4Layer(nn.Module):\n", + " def __init__(self, input_dim, hidden_dim):\n", + " super(NN4Layer, self).__init__()\n", + "\n", + " # First linear layer: input features -> hidden layer\n", + " self.layer1 = nn.Linear(input_dim, hidden_dim)\n", + "\n", + " # Second linear layer: hidden layer -> hidden layer\n", + " self.layer2 = nn.Linear(hidden_dim, hidden_dim)\n", + "\n", + " # Third linear layer: hidden layer -> hidden layer\n", + " self.layer3 = nn.Linear(hidden_dim, hidden_dim)\n", + "\n", + " # Output layer: hidden layer -> single continuous value\n", + " self.layer4 = nn.Linear(hidden_dim, 1)\n", + "\n", + " # ReLU activation for non-linearity in hidden layers\n", + " self.relu = nn.ReLU()\n", + "\n", + " # Defines how input data flows through the network\n", + " def forward(self, x):\n", + " # First hidden layer\n", + " a1 = self.relu(self.layer1(x))\n", + "\n", + " # Second hidden layer\n", + " a2 = self.relu(self.layer2(a1))\n", + "\n", + " # Second hidden layer\n", + " a3 = self.relu(self.layer2(a2))\n", + "\n", + " # Output layer (regression output)\n", + " output = self.layer3(a3)\n", + "\n", + " return output" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your training loop here:\n", + "def train_one_epoch(model, optimizer, criterion, train_loader, device):\n", + " # Set the model to training mode\n", + " model.train()\n", + "\n", + " running_loss = 0.0\n", + "\n", + " for X_batch, y_batch in train_loader:\n", + " # Move batch to the selected device\n", + " X_batch = X_batch.view(X_batch.size(0), -1).to(device) # shape: (batch_size, num_features)\n", + " y_batch = y_batch.view(-1, 1).to(device) # shape: (batch_size, 1)\n", + "\n", + " # Forward pass (continuous output)\n", + " outputs = model(X_batch) # shape: (batch_size, 1)\n", + " loss = criterion(outputs, y_batch)\n", + "\n", + " # Backward pass & optimization\n", + " optimizer.zero_grad() # Clear previous gradients\n", + " loss.backward() # Compute gradients\n", + " optimizer.step() # Update model parameters\n", + "\n", + " running_loss += loss.item()\n", + "\n", + " # Average loss over all batches\n", + " avg_loss = running_loss / len(train_loader)\n", + "\n", + " return avg_loss" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your validation loop here:\n", + "\n", + "\n", + "def validate(model, criterion, test_loader, device):\n", + " # Set the model to evaluation mode\n", + " model.eval()\n", + "\n", + " running_loss = 0.0\n", + "\n", + " with torch.no_grad():\n", + " for X_batch, y_batch in test_loader:\n", + " # Move data to device\n", + " X_batch = X_batch.view(X_batch.size(0), -1).to(device) # shape: (batch_size, num_features)\n", + " y_batch = y_batch.view(-1, 1).to(device) # shape: (batch_size, 1)\n", + "\n", + " # Forward pass (continuous output)\n", + " outputs = model(X_batch) # shape: (batch_size, 1)\n", + " loss = criterion(outputs, y_batch)\n", + "\n", + " running_loss += loss.item()\n", + "\n", + " # Average loss over all batches\n", + " avg_loss = running_loss / len(test_loader)\n", + "\n", + " return avg_loss" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Define device, model, loss, optimizer:\n", + "# TODO: Set up the device (use GPU if available, otherwise CPU)\n", + "device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n", + "\n", + "input_dim = 3*36*36 # RGB and 32 * 32 size\n", + "hidden_dim = 15\n", + "model = NN4Layer(input_dim, hidden_dim).to(device)\n", + "\n", + "print(\"Model Architecture:\\n\")\n", + "print(model)\n", + "\n", + "# Calculate the total number of trainable parameters\n", + "total_params = sum(p.numel() for p in model.parameters() if p.requires_grad)\n", + "print(f\"\\nTotal trainable parameters: {total_params}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Define criterion (loss function)\n", + "criterion = nn.MSELoss()\n", + "# Hyperparameters (feel free to experiment!)\n", + "num_epochs = 20\n", + "learning_rate = 0.001\n", + "# Define optimizer\n", + "optimizer = AdamW(model.parameters(), learning_rate)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Run Training\n", + "train_losses = []\n", + "val_losses = []\n", + "\n", + "print('Starting Training...')\n", + "for epoch in range(num_epochs):\n", + " # Train one epoch\n", + " train_loss = train_one_epoch(model, optimizer, criterion, train_loader, device)\n", + "\n", + " # Validate\n", + " val_loss = validate(model, criterion, test_loader, device)\n", + "\n", + " train_losses.append(train_loss)\n", + " val_losses.append(val_loss)\n", + "\n", + " if (epoch + 1) % 5 == 0:\n", + " print(\n", + " f'Epoch [{epoch+1}/{num_epochs}], '\n", + " f'Train Loss: {train_loss:.4f}, '\n", + " f'Val Loss: {val_loss:.4f}'\n", + " )\n", + "\n", + "print('Training Complete!')" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "\n", + "# Plotting results\n", + "plt.figure(figsize=(7, 5))\n", + "\n", + "plt.plot(train_losses, label='Train Loss')\n", + "plt.plot(val_losses, label='Validation Loss')\n", + "plt.title('Loss over Epochs')\n", + "plt.xlabel('Epoch')\n", + "plt.ylabel('Loss')\n", + "plt.legend()\n", + "\n", + "plt.tight_layout()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2 (Bonus): Write your code here:\n", + "model.eval()\n", + "# Get one batch from the test DataLoader\n", + "images, labels = next(iter(test_loader))\n", + "# Move images to device\n", + "images = images.to(device)\n", + "labels = labels.to(device)\n", + "\n", + "with torch.no_grad():\n", + " # Flatten images before passing to the model\n", + " outputs = model(images.view(images.size(0), -1))\n", + " predictions = torch.argmax(outputs, dim=1)\n", + "\n", + "# Move tensors back to CPU for plotting\n", + "images = images.cpu()\n", + "labels = labels.cpu()\n", + "predictions = predictions.cpu()\n", + "\n", + "# Plot first 6 predictions\n", + "plt.figure(figsize=(8, 4))\n", + "for i in range(6):\n", + " plt.subplot(2, 3, i + 1)\n", + " plt.imshow(images[i].view(36,36), cmap='gray')\n", + " plt.title(f\"True: {labels[i]} | Pred: {predictions[i]}\")\n", + " plt.axis('off')\n", + "\n", + "plt.tight_layout()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/387/Q3.ipynb b/submissions_extracted/387/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..d3a5d6f9046aad77ff4a43dee4cb9b102ad9dfdd --- /dev/null +++ b/submissions_extracted/387/Q3.ipynb @@ -0,0 +1,309 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "import numpy as np\n", + "import pandas as pd\n", + "import matplotlib.pyplot as plt\n", + "import os\n", + "import kagglehub\n", + "\n", + "from sklearn.model_selection import train_test_split, StratifiedKFold, cross_val_score\n", + "from sklearn.preprocessing import StandardScaler, LabelEncoder\n", + "from sklearn.ensemble import RandomForestClassifier\n", + "from sklearn.metrics import classification_report, confusion_matrix, accuracy_score\n", + "\n", + "import warnings\n", + "warnings.filterwarnings('ignore')\n", + "\n", + "\n", + "# Download latest version\n", + "\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q3-exam-data\")\n", + "\n", + "\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "# Load the CSV file\n", + "golden_feature_path = os.path.join(path, 'Q3_data.csv')\n", + "df = pd.read_csv(golden_feature_path)\n", + "\n", + "print(f\"Shape: {golden_feature.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "# Display dataset information using info()\n", + "df.info()\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "# Show statistical description using describe()\n", + "df.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "# Handle missing values appropriately\n", + "missing_percentage = (df.isnull().sum() / len(df)) * 100\n", + "missing_data = pd.DataFrame({\n", + " 'Column': missing_percentage.index,\n", + " 'Missing_Percentage': missing_percentage.values\n", + "})\n", + "missing_data = missing_data[missing_data['Missing_Percentage'] > 0].sort_values('Missing_Percentage', ascending=False)\n", + "\n", + "print(\"Missing Data Analysis:\")\n", + "missing_data.head(26)\n", + "\n", + "print(\"Note that all over 50% fill with nan, my recmomdation is to drop the above columns list\")\n", + "df_clean=df.dropna(axis=1)\n", + "print(\"check after drop\")\n", + "# Task 1: Write your code here:\n", + "missing_percentage = (df_clean.isnull().sum() / len(df_clean)) * 100\n", + "missing_data = pd.DataFrame({\n", + " 'Column': missing_percentage.index,\n", + " 'Missing_Percentage': missing_percentage.values\n", + "})\n", + "missing_data = missing_data[missing_data['Missing_Percentage'] > 0].sort_values('Missing_Percentage', ascending=False)\n", + "\n", + "print(\"Missing Data Analysis:\")\n", + "missing_data.head(5)\n", + "print(\"empty list\")\n", + "print(df_clean.shape)\n", + "\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "# Check and remove duplicates if any exist\n", + "def check_duplicates(df):\n", + " duplicates = df.duplicated().sum()\n", + " print(f\"Number of Duplicate Samples: {duplicates}\")\n", + " if duplicates > 0:\n", + " print(\"Dropping Duplicates...\")\n", + " df.drop_duplicates(inplace=True)\n", + " print(\"Duplicates Dropped.\")\n", + " else:\n", + " print(\"No Duplicate Samples Found.\")\n", + "\n", + "check_duplicates(df_clean)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "# 3. Do we have categorical columns?\n", + "categorical_cols = df.select_dtypes(include=[\"object\"]).columns\n", + "print(\"Do we have categorical columns?\")\n", + "print(\"Categorical Columns:\", list(categorical_cols))" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "from sklearn.preprocessing import StandardScaler\n", + "\n", + "# Pick only the numerical columns, NOT the target\n", + "numerical_cols = df_clean.select_dtypes(include=[\"number\"]).columns.drop(\"Target\")\n", + "\n", + "scaler = StandardScaler()\n", + "\n", + "# scale the `numerical_cols`\n", + "df_clean[numerical_cols] = scaler.fit_transform(df[numerical_cols])\n", + "df_clean.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "fig, axes = plt.subplots(1, 3, figsize=(18, 5))\n", + "\n", + "# We use 'axes[0]' for the first slot\n", + "axes[0].hist(df_clean['Target'], bins=50, edgecolor='black', color='skyblue')\n", + "axes[0].set_title('Target Distribution (look imbalanced)')\n", + "axes[0].set_xlabel('Target')\n", + "axes[0].set_ylabel('Frequency')\n", + "\n", + "# We use 'axes[1]' for the second slot\n", + "axes[1].hist(df['P_2'], bins=50, edgecolor='black', color='salmon')\n", + "axes[1].set_title('P_2 Distribution')\n", + "axes[1].set_xlabel('P_2')\n", + "axes[1].set_ylabel('Frequency')\n", + "\n", + "# We use 'axes[2]' for the third slot\n", + "axes[2].hist(df['D_87'], bins=30, edgecolor='black', color='lightgreen')\n", + "axes[2].set_title('D_87 Distribution (almost all NAN)')\n", + "axes[2].set_xlabel('D_87')\n", + "axes[2].set_ylabel('Frequency')\n", + "\n", + "# 3. Final Layout Adjustment\n", + "plt.tight_layout() # This stops the titles from overlapping\n", + "plt.show()\n", + "print(\"Rule of thumb: If class distributions are not equal, then our data is imbalanced. \")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "X = df_clean.drop(\"Target\", axis=1).astype(float)\n", + "y = df_clean['Target'].astype(float)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:\n", + "# Task 2,3,4,5: Write your code here:\n", + "n_splits = 5 # K=5 Folds\n", + "\n", + "# Stratified 5-Fold Cross-Validation, shuffled\n", + "skf = StratifiedKFold(n_splits=n_splits, shuffle=True, random_state=42)\n", + "\n", + "all_results = {}\n", + "\n", + "for name in sklearn_models:\n", + " all_results[name] = {'accuracy': [], 'precision': [], 'recall': [], 'f1': []}\n", + "\n", + "for fold_idx, (train_index, test_index) in enumerate(skf.split(X, y)):\n", + " print(f\"\\nFold {fold_idx + 1}/{n_splits}\")\n", + "\n", + " # 1. Split data\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", + " # 2. Train & Validate sklearn models\n", + " for model_name, model in sklearn_models.items():\n", + " print(f\"Training {model_name}...\")\n", + " model.fit(X_train, y_train) # train\n", + " y_pred = model.predict(X_test) # validate\n", + "\n", + " # 3. Save metrics for that model in this fold\n", + " accuracy = accuracy_score(y_test, y_pred)\n", + " precision = precision_score(y_test, y_pred, zero_division=0)\n", + " recall = recall_score(y_test, y_pred, zero_division=0)\n", + " f1 = f1_score(y_test, y_pred, zero_division=0)\n", + "\n", + " all_results[model_name]['accuracy'].append(accuracy)\n", + " all_results[model_name]['precision'].append(precision)\n", + " all_results[model_name]['recall'].append(recall)\n", + " all_results[model_name]['f1'].append(f1)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "# i dind't know what i missed before!!\n", + "feature_cols = df_clean.drop(columns=['Target']).columns.tolist()\n", + "importance = pd.DataFrame({\n", + " 'feature': feature_cols,\n", + " 'importance': model.feature_importances_\n", + "}).sort_values('importance', ascending=False)\n", + "\n", + "plt.figure(figsize=(15, 15))\n", + "plt.barh(importance['feature'], importance['importance'], color='purple')\n", + "plt.xlabel('Importance')\n", + "plt.title('Feature Importance')\n", + "plt.gca().invert_yaxis()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/388/Q1.ipynb b/submissions_extracted/388/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..3ea1ec1ed4587cc32251b7050c7d7afeacee75c2 --- /dev/null +++ b/submissions_extracted/388/Q1.ipynb @@ -0,0 +1,499 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q1-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import pandas as pd\n", + "import numpy as np\n", + "import matplotlib.pyplot as plt\n", + "import seaborn as sns\n", + "import kagglehub\n", + "import os\n", + "from tqdm import tqdm\n", + "\n", + "%matplotlib inline" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "#Read the dataset Q1_data.csv using read_csv()\n", + "csv_path = os.path.join(path, \"Q1_data.csv\")\n", + "\n", + "df = pd.read_csv(csv_path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "#Inspect the first few rows using head()\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "#Display dataset information using info()\n", + "df.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "#Show statistical description using describe()\n", + "df.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "#Plot the target distribution (delivery_time)\n", + "\n", + "def check_target_distribution(df, target_column):\n", + " df[target_column].hist(bins=30, edgecolor='black')\n", + "\n", + " plt.title(f\"Target Distribution ({target_column})\")\n", + " plt.xlabel(target_column)\n", + " plt.ylabel(\"Frequency\")\n", + " plt.grid(False)\n", + "\n", + " plt.show()\n", + "\n", + "check_target_distribution(df, \"Delivery_Time\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "#Drop the 'Order_ID' column from the data\n", + "\n", + "\n", + "\n", + "target_column = \"Order_ID\"\n", + "X = df.drop(target_column, axis=1)\n", + "y = df[target_column]\n", + "\n", + "df.columns.drop\n", + "\n", + "df.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "#Handle missing values appropriately\n", + "#(Hint: I guess you want to have a closer look at the columns with missing values :) )\n", + "\n", + "print(\"Missing values:\")\n", + "print(df.isnull().sum())" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "stat_cols = ['Distance_km', 'Vehicle_Type', 'Preparation_Time_min', \"Order_ID\"]\n", + "\n", + "df_clean = df.dropna(subset=stat_cols).copy()\n", + "print(f\"Shape after cleaning: {df_clean.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "#Check and remove duplicates if any exist\n", + "\n", + "def check_duplicates(df):\n", + " duplicates = df.duplicated().sum()\n", + " print(f\"Number of Duplicate Samples: {duplicates}\")\n", + " if duplicates > 0:\n", + " print(\"Dropping Duplicates...\")\n", + " df.drop_duplicates(inplace=True)\n", + " print(\"Duplicates Dropped.\")\n", + " else:\n", + " print(\"No Duplicate Samples Found.\")\n", + "\n", + "check_duplicates(df)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "#Encode categorical variables if needed (Bonus if used One Hot Encoding)\n", + "\n", + "from sklearn.preprocessing import OneHotEncoder #import OneHotEncoder\n", + "\n", + "print('data before encoding:\\n', df) #show before encoding\n", + "\n", + "onehot_encoder = OneHotEncoder(sparse_output=False) # Instantiate OneHotEncoder\n", + "data_onehot_encoded = onehot_encoder.fit_transform(df) # Apply fit_transform to the copied\n", + "\n", + "print('\\nData after encoding:\\n', data_onehot_encoded) #show after encoding" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "#Apply feature scaling for all features (Use StandardScaler)\n", + "\n", + "\n", + "from sklearn.preprocessing import StandardScaler #import StandardScaler\n", + "\n", + "print('data before scaling:\\n', df) #show before scaling\n", + "standard_scaler = StandardScaler() # Instantiate StandardScaler\n", + "df = standard_scaler.fit_transform(df) # Apply fit_transform\n", + "\n", + "print('\\nData after scaling:\\n', df) #show after scaling" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 6: Write your code here:\n", + "#Check for target imbalance and state\n", + "#if it is imbalanced or not (keep this cell empty if not needed)\n", + "\n", + "def check_target_imbalance(df, target_column):\n", + " print(\"Target Distribution:\")\n", + " print(df[target_column].value_counts(normalize=True))\n", + " sns.countplot(x=df[target_column])\n", + " plt.title(\"Target Distribution\")\n", + " plt.show()\n", + "\n", + "check_target_imbalance(df, \"Delivery_Time\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Mean Squared Error in NumPy\n", + "def mean_squared_error(y, y_hat):\n", + " return (1 / (2 * len(y))) * np.sum((y_hat - y) ** 2)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "def gradient_descent(X, y, learning_rate, n_iters=500):\n", + " m, n = X.shape # m rows, n columns (dimensions)\n", + " theta = np.zeros(n) # initialize a zeros weight vector with n dimensions\n", + " losses = []\n", + "\n", + " for _ in tqdm(range(n_iters), desc=\"Training Linear Regression\"):\n", + " y_hat = np.dot(X, theta)\n", + " gradient = np.dot(X.T, (y_hat - y)) / m\n", + " theta -= learning_rate * gradient\n", + "\n", + " loss = mean_squared_error(y, y_hat)\n", + " losses.append(loss)\n", + "\n", + " return theta, losses" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "from sklearn.model_selection import KFold\n", + "from sklearn.metrics import mean_squared_error as sklearn_mse, mean_absolute_error, r2_score" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "n_splits = 5 # K=5 Folds\n", + "\n", + "# 5-Fold Cross-Validation, shuffled\n", + "kf = KFold(n_splits=n_splits, shuffle=True, random_state=42)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Storage for linear regression results for each fold\n", + "lr_losses = []\n", + "lr_mse = []\n", + "lr_rmse = []\n", + "lr_r2 = []" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "for fold_idx, (train_index, test_index) in enumerate(kf.split(X)):\n", + " print(f\"\\nFold {fold_idx + 1}/{n_splits}\")\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", + " # Train\n", + " theta, losses = gradient_descent(X_train.values, y_train.values, learning_rate=0.1, n_iters=500)\n", + "\n", + " # Validate\n", + " y_pred = np.dot(X_test.values, theta)\n", + "\n", + " # Calculate evaluation metrics\n", + " mse = sklearn_mse(y_test, y_pred)\n", + " rmse = np.sqrt(mse)\n", + " r2 = r2_score(y_test, y_pred)\n", + "\n", + " # Store results\n", + " lr_losses.append(losses)\n", + " lr_mse.append(mse)\n", + " lr_rmse.append(rmse)\n", + " lr_r2.append(r2)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "#Split the dataset into features (X) and target (y)\n", + "\n", + "import numpy as np # for random data generation\n", + "\n", + "np.random.seed(42) # for reproducbility\n", + "\n", + "X_reg = pd.DataFrame({\"Feature_1\": np.random.randn(500)}) # features\n", + "y_reg = 3 * X_reg[\"Feature_1\"] + np.random.randn(500) * 0.5 # continous labels with noise\n", + "\n", + "\n", + "X_clf = pd.DataFrame({\"Feature_1\": np.random.randn(500)}) # features\n", + "y_clf = (X_clf[\"Feature_1\"] > 0).astype(int) # labels as class 0 or 1\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task2\n", + "#Use the correct split: KFold OR StratifiedKFold\n", + "\n", + "from sklearn.model_selection import KFold\n", + "from sklearn.metrics import mean_squared_error as sklearn_mse, mean_absolute_error, r2_score" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4\n", + "\n", + "from sklearn.metrics import mean_squared_error, mean_absolute_error\n", + "\n", + "print(\"Regression Metrics\\n\" + \"-\"*30)\n", + "\n", + "# Use previously generated random classification data\n", + "X, y = X_reg.copy(), y_reg.copy()\n", + "\n", + "# Split ratio (80% train, 20% test)\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y,test_size=0.2,random_state=42,shuffle=True)\n", + "\n", + "# Train a regression model\n", + "reg_model = LinearRegression()\n", + "reg_model.fit(X_train, y_train)\n", + "y_pred = reg_model.predict(X_test)\n", + "\n", + "# Calculate metrics\n", + "mae = mean_absolute_error(y_test, y_pred)\n", + "\n", + "print(\"MAE :\", mae)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "#Task 5\n", + "\n", + "average_losses = np.mean(lr_losses, axis=0)\n", + "\n", + "plt.figure(figsize=(10, 6))\n", + "plt.plot(average_losses, label='Average Loss')\n", + "plt.xlabel('Iteration')\n", + "plt.ylabel('MSE Loss')\n", + "plt.title('Linear Regression Training Loss (Averaged Across Folds)')\n", + "plt.legend()\n", + "plt.grid(True, alpha=0.3)\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "print(\"Evaluating models on the test set...\")\n", + "\n", + "# Dictionary to store performance metrics\n", + "model_performance = {}\n", + "\n", + "# Iterate through each trained model\n", + "for model_name, model in models.items():\n", + " print(f\"\\nEvaluating {model_name}...\")\n", + "\n", + " # Make predictions on the test set (hard labels)\n", + " y_pred = model.predict(X_test)\n", + "\n", + " # Calculate evaluation metrics\n", + " accuracy = accuracy_score(y_test, y_pred)\n", + " precision = precision_score(y_test, y_pred, average='weighted', zero_division=0)\n", + " recall = recall_score(y_test, y_pred, average='weighted', zero_division=0)\n", + " f1 = f1_score(y_test, y_pred, average='weighted', zero_division=0)\n", + "\n", + " # Store metrics\n", + " model_performance[model_name] = {\n", + " 'Accuracy': accuracy,\n", + " 'Precision': precision,\n", + " 'Recall': recall,\n", + " 'F1-Score': f1\n", + " }\n", + "\n", + " # Print metrics\n", + " print(f\" Accuracy: {accuracy:.4f}\")\n", + " print(f\" Precision: {precision:.4f}\")\n", + " print(f\" Recall: {recall:.4f}\")\n", + " print(f\" F1-Score: {f1:.4f}\")\n", + "\n", + " # Generate and visualize Confusion Matrix\n", + " cm = confusion_matrix(y_test, y_pred)\n", + " plt.figure(figsize=(6, 5))\n", + " sns.heatmap(cm, annot=True, fmt='d', cmap='Blues', cbar=False,\n", + " xticklabels=label_encoder.classes_, yticklabels=label_encoder.classes_)\n", + " plt.title(f'Confusion Matrix for {model_name}')\n", + " plt.xlabel('Predicted Label')\n", + " plt.ylabel('True Label')\n", + " plt.show()\n", + "\n", + "print(\"\\nAll models evaluated.\")" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/388/Q2.ipynb b/submissions_extracted/388/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..a3d64c7faaa9e0fe180dfaaeac51ace2eb3d4ed9 --- /dev/null +++ b/submissions_extracted/388/Q2.ipynb @@ -0,0 +1,336 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q2-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)\n", + "\n", + "csv_path = os.path.join(path, \"labels.csv\")\n", + "df = pd.read_csv(csv_path)\n", + "\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import numpy as np\n", + "import pandas as pd\n", + "import matplotlib.pyplot as plt\n", + "import seaborn as sns\n", + "from scipy import stats\n", + "from tqdm import tqdm\n", + "!pip install optuna\n", + "#import optuna\n", + "tqdm.pandas()\n", + "\n", + "from sklearn.preprocessing import LabelEncoder\n", + "from sklearn.linear_model import LogisticRegression\n", + "from sklearn.model_selection import KFold\n", + "\n", + "from lightgbm import LGBMClassifier\n", + "from xgboost import XGBClassifier\n", + "!pip install catboost\n", + "from catboost import CatBoostClassifier\n", + "from sklearn.ensemble import RandomForestClassifier\n", + "from sklearn.ensemble import VotingClassifier\n", + "from sklearn.metrics import f1_score\n", + "\n", + "\n", + "import warnings\n", + "warnings.simplefilter(action='ignore', category=FutureWarning)\n", + "pd.options.mode.chained_assignment = None # default='warn'\n", + "#pd.set_option('display.float_format', lambda x: '%.3f' % x)\n", + "plt.rcParams[\"figure.figsize\"] = (12, 8)\n", + "pd.set_option('display.max_columns', None)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Import required libraries\n", + "import kagglehub\n", + "import pandas as pd\n", + "import numpy as np\n", + "import torch\n", + "import torch.nn as nn\n", + "from torch.optim import AdamW\n", + "import matplotlib.pyplot as plt\n", + "from torch.utils.data import DataLoader, TensorDataset\n", + "from sklearn.model_selection import train_test_split\n", + "from sklearn.preprocessing import StandardScaler, LabelEncoder\n", + "from sklearn.metrics import mean_absolute_error, mean_squared_error, r2_score\n", + "\n", + "print(f\"PyTorch version: {torch.__version__}\")\n", + "print(f\"CUDA available: {torch.cuda.is_available()}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "df.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 1. Convert Numpy arrays to PyTorch Tensors\n", + "\n", + "categorical_cols = df.select_dtypes(include=[\"object\"]).columns\n", + "\n", + "for col in categorical_cols:\n", + " print(f\"Encoding column: {col}\")\n", + " le = LabelEncoder()\n", + " # TODO: Apply fit_transform to encode the column\n", + " df[col] = le.fit_transform(df[col])\n", + "\n", + "df.head()\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "numerical_cols = df.select_dtypes(include=[\"number\"]).columns.drop(\"image_id\")\n", + "\n", + "scaler = StandardScaler()\n", + "\n", + "# TODO: Apply fit_transform to scale the numerical columns\n", + "df[numerical_cols] = scaler.fit_transform(df[numerical_cols])\n", + "\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# TODO: Split the dataset into training and testing sets (80% train, 20% test)\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n", + "\n", + "# TODO: Transform to PyTorch tensors with dtype=torch.float32\n", + "X_train = torch.tensor(X_train.values, dtype=torch.float32)\n", + "X_test = torch.tensor(X_test.values, dtype=torch.float32)\n", + "y_train = torch.tensor(y_train.values, dtype=torch.float32)\n", + "y_test = torch.tensor(y_test.values, dtype=torch.float32)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 2. Create TensorDataset objects\n", + "\n", + "train_dataset = TensorDataset(X_train, y_train)\n", + "test_dataset = TensorDataset(X_test, y_test)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 3. Create DataLoaders\n", + "\n", + "# Create Dataloaders to train and test data in batches\n", + "train_loader = DataLoader(train_dataset, batch_size=32, shuffle=True)\n", + "test_loader = DataLoader(test_dataset, batch_size=32, shuffle=False)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 4. Print shape of one batch\n", + "\n", + "X_batch, y_batch = next(iter(train_loader))\n", + "print(f\"Training batch input shape: {X_batch.shape}\")\n", + "print(f\"Training batch labels shape: {y_batch.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 5. Display sample images\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your model class here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your training loop here:\n", + "\n", + "def train_one_epoch(model, optimizer, criterion, train_loader, device):\n", + " # Set the model to training mode\n", + " model.train()\n", + "\n", + " running_loss = 0.0\n", + "\n", + " for X_batch, y_batch in train_loader:\n", + " # Move batch to the selected device\n", + " X_batch = X_batch.to(device)\n", + " y_batch = y_batch.view(-1, 1).to(device)\n", + "\n", + " # Forward pass\n", + " outputs = model(X_batch)\n", + " loss = criterion(outputs, y_batch)\n", + "\n", + " # Backward pass & optimization\n", + " optimizer.zero_grad() # Clear previous gradients\n", + " loss.backward() # Compute gradients\n", + " optimizer.step() # Update model parameters\n", + "\n", + " running_loss += loss.item()\n", + "\n", + " # Average loss over all batches\n", + " avg_loss = running_loss / len(train_loader)\n", + "\n", + " return avg_loss" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your validation loop here:\n", + "\n", + "def validate(model, criterion, test_loader, device):\n", + " # Set the model to evaluation mode\n", + " model.eval()\n", + "\n", + " running_loss = 0.0\n", + " correct = 0\n", + " total = 0\n", + "\n", + " with torch.no_grad(): # Disable gradient computation\n", + " for X_batch, y_batch in test_loader:\n", + " # Move batch to the selected device\n", + " X_batch = X_batch.to(device)\n", + " y_batch = y_batch.view(-1, 1).to(device)\n", + "\n", + " # Forward pass\n", + " outputs = model(X_batch)\n", + " loss = criterion(outputs, y_batch)\n", + " running_loss += loss.item()\n", + "\n", + " # Binary predictions\n", + " predicted = (outputs > 0.5).float()\n", + "\n", + " # Accuracy calculation\n", + " correct += (predicted == y_batch).sum().item()\n", + " total += y_batch.size(0)\n", + "\n", + " avg_loss = running_loss / len(test_loader)\n", + " accuracy = correct / total\n", + "\n", + " return avg_loss, accuracy\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Define device, model, loss, optimizer:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Start training for 20 epochs:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "\n", + "# Plotting results\n", + "plt.figure(figsize=(7, 5))\n", + "\n", + "plt.plot(train_losses, label='Train Loss')\n", + "plt.plot(val_losses, label='Validation Loss')\n", + "plt.title('Loss over Epochs')\n", + "plt.xlabel('Epoch')\n", + "plt.ylabel('Loss')\n", + "plt.legend()\n", + "\n", + "plt.tight_layout()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2 (Bonus): Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/388/Q3.ipynb b/submissions_extracted/388/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..ad66b28fa39761293b0b414301f9dcb104340174 --- /dev/null +++ b/submissions_extracted/388/Q3.ipynb @@ -0,0 +1,307 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "\n", + "\n", + "# Download latest version\n", + "\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q3-exam-data\")\n", + "\n", + "\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import pandas as pd\n", + "import numpy as np\n", + "import matplotlib.pyplot as plt\n", + "import seaborn as sns\n", + "import kagglehub\n", + "import os\n", + "from tqdm import tqdm\n", + "\n", + "%matplotlib inline" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "#Read the dataset Q3_data.csv using read_csv()\n", + "csv_path = os.path.join(path, \"Q3_data.csv\")\n", + "\n", + "df = pd.read_csv(csv_path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "#Inspect the first few rows using head()\n", + "\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "#Display dataset information using info()\n", + "\n", + "df.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "#Show statistical description using describe()\n", + "\n", + "df.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "#Handle missing values appropriately\n", + "\n", + "# Missing values\n", + "print(\"Missing values:\")\n", + "print(df.isnull().sum())" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "df.dropna(df=['col'])" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "#Check and remove duplicates if any exist\n", + "\n", + "def check_duplicates(df):\n", + "\n", + " #TODO: get duplicated data using pandas\n", + " duplicates = df.duplicated().sum()\n", + "\n", + " print(f\"Number of Duplicate Samples: {duplicates}\")\n", + " if duplicates > 0:\n", + " print(\"Dropping Duplicates...\")\n", + " df.drop_duplicates(inplace=True)\n", + " print(\"Duplicates Dropped.\")\n", + " else:\n", + " print(\"No Duplicate Samples Found.\")\n", + "\n", + "check_duplicates(df)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "#Encode categorical variables if needed\n", + "\n", + "categorical_cols = df.select_dtypes(include=[\"object\"]).columns\n", + "print(\"Categorical Columns:\", list(categorical_cols))\n", + "\n", + "\n", + "#NO categorical variables in this data" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "#Apply feature scaling to numerical features (Use StandardScaler)\n", + "\n", + "from sklearn.preprocessing import StandardScaler #import StandardScaler\n", + "\n", + "print('data before scaling:\\n', df) #show before scaling\n", + "standard_scaler = StandardScaler() # Instantiate StandardScaler\n", + "df = standard_scaler.fit_transform(df) # Apply fit_transform\n", + "\n", + "print('\\nData after scaling:\\n', df) #show after scaling" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "#Check for target imbalance and state if it is imbalanced or not\n", + "\n", + "def check_target_imbalance(df, target_column):\n", + " print(\"Target Distribution:\")\n", + " print(df[target_column].value_counts(normalize=True))\n", + " sns.countplot(x=df[target_column])\n", + " plt.title(\"Target Distribution\")\n", + " plt.show()\n", + "\n", + "check_target_imbalance(df, \"Target\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "print(\"Initializing models and K-Fold cross-validation...\")\n", + "\n", + "# Determine the number of classes for one-hot encoding\n", + "num_classes = len(np.unique(y_encoded))\n", + "\n", + "# 1. Initialize the machine learning models\n", + "models = {\n", + " 'Logistic Regression': LogisticRegression(solver='liblinear', max_iter=200, random_state=42),\n", + " 'Decision Tree': DecisionTreeClassifier(random_state=42),\n", + " 'Random Forest': RandomForestClassifier(n_estimators=100, random_state=42),\n", + " 'SVM': SVC(probability=True, random_state=42) # probability=True is needed for .predict_proba\n", + "}\n", + "\n", + "# 2. Create a KFold object\n", + "kf = KFold(n_splits=5, shuffle=True, random_state=42)\n", + "\n", + "# 3. Create an empty dictionary to store average losses\n", + "model_losses = {}\n", + "\n", + "print(\"Starting K-Fold Cross-Validation for each model...\")\n", + "\n", + "# 4. For each model:\n", + "for model_name, model in models.items():\n", + " print(f\"\\nTraining and evaluating {model_name}...\")\n", + " fold_losses = [] # List to store loss from each fold\n", + "\n", + " for fold, (train_index, val_index) in enumerate(kf.split(X_train)):\n", + " # Split X_train and y_train into training and validation sets for the current fold\n", + " X_train_fold, X_val_fold = X_train.iloc[train_index], X_train.iloc[val_index]\n", + " y_train_fold, y_val_fold = y_train[train_index], y_train[val_index]\n", + "\n", + " # Train the current model\n", + " model.fit(X_train_fold, y_train_fold)\n", + "\n", + " # Generate predictions (probabilities) on the validation set\n", + " y_pred_proba = model.predict_proba(X_val_fold)\n", + "\n", + " # Convert y_val_fold (true labels) into a one-hot encoded format\n", + " y_val_one_hot = one_hot_encode(y_val_fold, num_classes)\n", + "\n", + " # Calculate categorical cross-entropy loss for the current fold\n", + " loss = categorical_cross_entropy(y_val_one_hot, y_pred_proba)\n", + " fold_losses.append(loss)\n", + "\n", + " # Calculate the average loss for the model\n", + " avg_loss = np.mean(fold_losses)\n", + " model_losses[model_name] = avg_loss\n", + "\n", + " # Print the average cross-validation loss for the current model\n", + " print(f\"{model_name} - Average Cross-Validation Loss: {avg_loss:.4f}\")\n", + "\n", + "print(\"\\nAll models trained and evaluated. Stored average losses:\")\n", + "print(model_losses)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/389/Q1.ipynb b/submissions_extracted/389/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..20475b3fba1ffd071174cd7bf4f8d8e431ff8bba --- /dev/null +++ b/submissions_extracted/389/Q1.ipynb @@ -0,0 +1,312 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q1-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "import pandas as pd\n", + "import numpy as np\n", + "import matplotlib.pyplot as plt\n", + "import seaborn as sns\n", + "import kagglehub\n", + "import os\n", + "from tqdm import tqdm\n", + "\n", + "csv_path = os.path.join(path, \"Q1_data.csv\")\n", + "df = pd.read_csv(csv_path)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "df.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "df.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "def check_target_imbalance(df, target_column):\n", + " print(\"Target Distribution:\")\n", + " print(df[target_column].value_counts(normalize=True))\n", + " sns.countplot(x=df[target_column])\n", + " plt.title(\"Target Distribution\")\n", + " plt.show()\n", + "\n", + "check_target_imbalance(df, \"Delivery_Time\") # we can see that the data is not equally distributed so we need to use stratified kfold for splitting" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "df = df.drop('Order_ID', axis=1)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "def check_missing_values(df):\n", + " missing_values = df.isnull().sum()\n", + " print(\"Missing Values per Column:\")\n", + " print(missing_values[missing_values > 0])\n", + " if missing_values.any():\n", + " print(\"\\nHandle Missing Values as needed.\")\n", + " else:\n", + " print(\"\\nNo Missing Values Found.\")\n", + "\n", + "check_missing_values(df)\n", + "\n", + "df[\"Delivery_Time\"] = df[\"Delivery_Time\"].mean()\n", + "df[\"Weather\"] = df[\"Weather\"].mode()\n", + "df[\"Traffic_Level\"] = df[\"Traffic_Level\"].mode()\n", + "\n", + "df[\"Time_of_Day\"] = df[\"Time_of_Day\"].mode()\n", + "df[\"Courier_Experience_yrs\"] = df[\"Courier_Experience_yrs\"].mean()\n", + "\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "def check_duplicates(df):\n", + " duplicates = df.duplicated().sum()\n", + " print(f\"Number of Duplicate Samples: {duplicates}\")\n", + " if duplicates > 0:\n", + " print(\"Dropping Duplicates...\")\n", + " df.drop_duplicates(inplace=True)\n", + " print(\"Duplicates Dropped.\")\n", + " else:\n", + " print(\"No Duplicate Samples Found.\")\n", + "\n", + "check_duplicates(df)\n", + "df" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "\n", + "# task4\n", + "from sklearn.preprocessing import OneHotEncoder #import OneHotEncoder\n", + "cat_cols = df.select_dtypes(exclude=[\"number\"]).columns\n", + "num_cols = df.select_dtypes(include=[\"number\"]).columns\n", + "\n", + "print('data before encoding:\\n', df[cat_cols]) #show before encoding\n", + "\n", + "onehot_encoder = OneHotEncoder(sparse_output=False) # Instantiate OneHotEncoder\n", + "data_onehot_encoded = onehot_encoder.fit_transform(df[cat_cols]) # Apply fit_transform to the copied\n", + "X_num = df[num_cols].to_numpy()\n", + "df = np.hstack([X_num, data_onehot_encoded])\n", + "\n", + "print('\\nData after encoding:\\n', data_onehot_encoded)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "import pandas as pd\n", + "from sklearn.preprocessing import StandardScaler\n", + "\n", + "# 1. Initialize the StandardScaler\n", + "scaler = StandardScaler()\n", + "\n", + "# 2. Fit and Transform the data\n", + "# This calculates the mean and std, then scales the data\n", + "scaled_data = scaler.fit_transform(df)\n", + "\n", + "# 3. Convert the resulting NumPy array back into a DataFrame\n", + "df_scaled = pd.DataFrame(scaled_data, columns=df.columns)\n", + "\n", + "# Display the first few rows\n", + "print(df_scaled.head())\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 6: Write your code here:\n", + "df.value_counts(normalize=True) # normalize give percentage" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Separate features and target\n", + "X = df_scaled.drop(columns=['target'])\n", + "y = df['target']" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:\n", + "import numpy as np\n", + "from sklearn.model_selection import KFold, cross_val_score\n", + "from sklearn.ensemble import RandomForestRegressor\n", + "\n", + "# 1. Define the KFold strategy\n", + "kf = KFold(n_splits=5, shuffle=True, random_state=42)\n", + "\n", + "# 2. Initialize the Random Forest Regressor\n", + "rf_model = RandomForestRegressor(n_estimators=100, random_state=42)\n", + "\n", + "# 3. Evaluate using MAE only\n", + "# 'neg_mean_absolute_error' returns negative values; we multiply by -1\n", + "mae_scores = -cross_val_score(rf_model, X, y, cv=kf, scoring='neg_mean_absolute_error')\n", + "\n", + "# 4. Print the averaged score\n", + "print(f\"MAE per fold: {mae_scores}\")\n", + "print(f\"Average MAE across all folds: {np.mean(mae_scores):.4f}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:import matplotlib.pyplot as plt\n", + "import seaborn as sns\n", + "from sklearn.model_selection import cross_val_predict\n", + "\n", + "# 1. Plot Feature Importance\n", + "# We fit the model on the full scaled dataset to get final importance scores\n", + "rf_model.fit(X_scaled_df, y)\n", + "\n", + "plt.figure(figsize=(10, 6))\n", + "importances = rf_model.feature_importances_\n", + "feature_names = X.columns\n", + "# Sort importances in descending order\n", + "indices = np.argsort(importances)[::-1]\n", + "\n", + "sns.barplot(x=importances[indices], y=feature_names[indices], palette='viridis')\n", + "plt.title('Feature Importance (Random Forest)')\n", + "plt.xlabel('Importance Score')\n", + "plt.ylabel('Features')\n", + "plt.tight_layout()\n", + "plt.savefig('feature_importance.png')\n", + "\n", + "# 2. Plot Predicted Delivery Time Histogram\n", + "# Using cross_val_predict to get \"out-of-fold\" predictions for the histogram\n", + "y_pred = cross_val_predict(rf_model, X_scaled_df, y, cv=kf)\n", + "\n", + "plt.figure(figsize=(10, 6))\n", + "sns.histplot(y_pred, kde=True, color='blue', bins=30)\n", + "plt.title('Distribution of Predicted Delivery Times')\n", + "plt.xlabel('Predicted Delivery Time (mins)')\n", + "plt.ylabel('Frequency')\n", + "plt.tight_layout()\n", + "plt.savefig('predicted_histogram.png')" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/389/Q2.ipynb b/submissions_extracted/389/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..0a13e8345f06b019535933edc7a4626b78e7218a --- /dev/null +++ b/submissions_extracted/389/Q2.ipynb @@ -0,0 +1,390 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "import pandas as pd\n", + "import torch\n", + "import torch.nn as nn\n", + "from torch.optim import AdamW\n", + "import matplotlib.pyplot as plt\n", + "import torch.nn.functional as F\n", + "from torch.utils.data import DataLoader, TensorDataset\n", + "from sklearn.model_selection import train_test_split\n", + "from sklearn.preprocessing import StandardScaler, LabelEncoder\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q2-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import os\n", + "import pandas as pd\n", + "import numpy as np\n", + "from PIL import Image\n", + "from sklearn.model_selection import train_test_split\n", + "\n", + "\n", + "# Load Labels\n", + "labels_df = pd.read_csv(os.path.join(path, \"labels.csv\"))\n", + "img_dir = os.path.join(path, \"images\")\n", + "\n", + "images = []\n", + "ages = []\n", + "\n", + "# Load Images and Resize\n", + "print(\"Loading images...\")\n", + "for index, row in labels_df.iterrows():\n", + " img_name = row.iloc[0]\n", + " age = row.iloc[1]\n", + " img_path = os.path.join(img_dir, img_name)\n", + "\n", + " if os.path.exists(img_path):\n", + " img = Image.open(img_path).convert('RGB')\n", + " img_array = np.array(img) / 255.0 # Normalize pixel values to [0, 1]\n", + " images.append(img_array)\n", + " ages.append(age)\n", + "\n", + "X = np.array(images)\n", + "y = np.array(ages)\n", + "\n", + "# Transpose image dimensions to match PyTorch format (N, C, H, W)\n", + "X = np.transpose(X, (0, 3, 1, 2))\n", + "\n", + "# Split Data\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n", + "\n", + "print(f\"X_train shape: {X_train.shape}\")\n", + "print(f\"X_test shape: {X_test.shape}\")\n", + "print(f\"y_train shape: {y_train.shape}\")\n", + "print(f\"y_test shape: {y_test.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 1. Convert Numpy arrays to PyTorch Tensors\n", + "import torch\n", + "from torch.utils.data import TensorDataset, DataLoader\n", + "import matplotlib.pyplot as plt\n", + "import numpy as np\n", + "\n", + "# 1. Convert NumPy arrays to PyTorch Tensors\n", + "categorical_cols = labels_df.select_dtypes(include=[\"object\"]).columns\n", + "for col in categorical_cols:\n", + " print(f\"Encoding column: {col}\")\n", + " le = LabelEncoder()\n", + " labels_df[col] = le.fit_transform(labels_df[col])\n", + "labels_df\n", + "numerical_cols = labels_df.select_dtypes(exclude='object')\n", + "\n", + "X_train_tensor = torch.from_numpy(X_train).float()\n", + "y_train_tensor = torch.from_numpy(y_train).long()\n", + "X_test_tensor = torch.from_numpy(X_test).float() # we need to ensure the data types are correct\n", + "y_test_tensor = torch.from_numpy(y_test).long()\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 2. Create TensorDataset objects\n", + "\n", + "\n", + "train_dataset = TensorDataset(X_train_tensor, y_train_tensor)\n", + "test_dataset = TensorDataset(X_test_tensor, y_test_tensor)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 3. Create DataLoaders\n", + "\n", + "\n", + "batch_size = 32\n", + "train_loader = DataLoader(dataset=train_dataset, batch_size=batch_size, shuffle=True)\n", + "test_loader = DataLoader(dataset=test_dataset, batch_size=batch_size, shuffle=False)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 4. Print shape of one batch\n", + "data_iter = iter(train_loader)\n", + "images, labels = next(data_iter)\n", + "\n", + "print(f\"images shape: {images.shape}\") # Expect: [32, Channels, Height, Width]\n", + "print(f\"labels shape: {labels.shape}\") # Expect: [32]\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 5. Display sample images\n", + "def show_images(imgs, labels, num_images=5):\n", + " plt.figure(figsize=(12, 4))\n", + " for i in range(num_images):\n", + " plt.subplot(1, num_images, i + 1)\n", + "\n", + "\n", + " img = imgs[i].numpy()\n", + " if img.ndim == 3:\n", + " img = np.transpose(img, (1, 2, 0))\n", + "\n", + " plt.imshow(img, cmap='gray' if img.ndim == 2 else None)\n", + " plt.title(f\"label: {labels[i].item()}\")\n", + " plt.axis('off')\n", + " plt.show()\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import torch.nn as nn\n", + "import torch.nn.functional as F\n", + "\n", + "class AgePredictor(nn.Module):\n", + " def __init__(self, input_size, num_classes):\n", + " super(AgePredictor, self).__init__()\n", + " # Flatten the (C, H, W) image into a single vector\n", + " self.flatten = nn.Flatten()\n", + "\n", + " # 4 Linear Layers\n", + " self.fc1 = nn.Linear(input_size, 512)\n", + " self.fc2 = nn.Linear(512, 256)\n", + " self.fc3 = nn.Linear(256, 128)\n", + " self.fc4 = nn.Linear(128, num_classes) # num_classes = number of age categories\n", + "\n", + " def forward(self, x):\n", + " x = self.flatten(x)\n", + " x = F.relu(self.fc1(x))\n", + " x = F.relu(self.fc2(x))\n", + " x = F.relu(self.fc3(x))\n", + " x = self.fc4(x) # No activation on the final layer (CrossEntropyLoss handles it)\n", + " return x" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "def train_loop(model, loader, loss_fn, optimizer, device):\n", + " model.train()\n", + " running_loss = 0.0\n", + " for images, labels in loader:\n", + " images, labels = images.to(device), labels.to(device)\n", + "\n", + " # Forward pass\n", + " outputs = model(images)\n", + " loss = loss_fn(outputs, labels)\n", + "\n", + " # Backward pass\n", + " optimizer.zero_grad()\n", + " loss.backward()\n", + " optimizer.step()\n", + "\n", + " running_loss += loss.item()\n", + " return running_loss / len(loader)\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your validation loop here:\n", + "def validate_loop(model, loader, loss_fn, device):\n", + " model.eval()\n", + " running_loss = 0.0\n", + " with torch.no_grad():\n", + " for images, labels in loader:\n", + " images, labels = images.to(device), labels.to(device)\n", + " outputs = model(images)\n", + " loss = loss_fn(outputs, labels)\n", + " running_loss += loss.item()\n", + " return running_loss / len(loader)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Define device, model, loss, optimizer:\n", + "\n", + "# Device setup\n", + "device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n", + "\n", + "# Model parameters\n", + "input_dim = X_train.shape[1] # Number of tabular features\n", + "hidden_dim = 14 # Design choice\n", + "output_dim = 4 # Weather classes: Rainy, Sunny, Cloudy, Snowy\n", + "\n", + "# Instantiate model\n", + "model = NN4Layer(input_dim, hidden_dim, output_dim).to(device)\n", + "\n", + "# Print the model architecture\n", + "print(\"Model Architecture:\\n\")\n", + "print(model)\n", + "\n", + "# Calculate the total number of trainable parameters\n", + "total_params = sum(p.numel() for p in model.parameters() if p.requires_grad)\n", + "print(f\"\\nTotal trainable parameters: {total_params}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Start training for 20 epochs:\n", + "\n", + "\n", + "sample_batch = next(iter(train_loader))[0]\n", + "c, h, w = sample_batch.shape[1], sample_batch.shape[2], sample_batch.shape[3]\n", + "flattened_size = c * h * w\n", + "\n", + "print(f\"Correct Input Size: {flattened_size}\")\n", + "\n", + "# 2. Update the Model Class\n", + "class AgePredictor(nn.Module):\n", + " def __init__(self, input_size, num_classes):\n", + " super(AgePredictor, self).__init__()\n", + " self.flatten = nn.Flatten()\n", + "\n", + "\n", + " self.fc1 = nn.Linear(input_size, 512)\n", + " self.fc2 = nn.Linear(512, 256)\n", + " self.fc3 = nn.Linear(256, 128)\n", + " self.fc4 = nn.Linear(128, num_classes)\n", + "\n", + " def forward(self, x):\n", + " x = self.flatten(x)\n", + " x = F.relu(self.fc1(x))\n", + " x = F.relu(self.fc2(x))\n", + " x = F.relu(self.fc3(x))\n", + " x = self.fc4(x)\n", + " return x\n", + "\n", + "# 3. Re-initialize\n", + "model = AgePredictor(flattened_size, num_age_classes).to(device)\n", + "# Define Device\n", + "\n", + "# 4. Start Training for 20 Epochs\n", + "\n", + "train_losses = []\n", + "val_losses = []\n", + "epochs = 20\n", + "\n", + "print(f\"Starting training on {device}...\")\n", + "\n", + "for epoch in range(epochs):\n", + " train_loss = train_loop(model, train_loader, loss_fn, optimizer, device)\n", + " val_loss = validate_loop(model, test_loader, loss_fn, device)\n", + "\n", + " train_losses.append(train_loss)\n", + " val_losses.append(val_loss)\n", + "\n", + " print(f\"Epoch {epoch+1}/{epochs} | Train Loss: {train_loss:.4f} | Val Loss: {val_loss:.4f}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "# Plotting results\n", + "plt.figure(figsize=(7, 5))\n", + "\n", + "plt.plot(train_losses, label='Train Loss')\n", + "plt.plot(val_losses, label='Validation Loss')\n", + "plt.title('Loss over Epochs')\n", + "plt.xlabel('Epoch')\n", + "plt.ylabel('Loss')\n", + "plt.legend()\n", + "\n", + "plt.tight_layout()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2 (Bonus): Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/389/Q3.ipynb b/submissions_extracted/389/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..b3045b661296c2d67a10d347029c948143c48606 --- /dev/null +++ b/submissions_extracted/389/Q3.ipynb @@ -0,0 +1,309 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "import pandas as pd\n", + "import os\n", + "!pip install catboost # it was not working for me i dont know why\n", + "\n", + "\n", + "\n", + "# Download latest version\n", + "\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q3-exam-data\")\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "print(\"Path to dataset files:\", path)\n", + "csv_path = os.path.join(path, \"Q3_data.csv\")\n", + "df = df = pd.read_csv(csv_path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "csv_path = os.path.join(path, \"Q3_data.csv\")\n", + "df = df = pd.read_csv(csv_path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "df.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "df.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "def check_missing_values(df):\n", + " missing_values = df.isnull().sum()\n", + " print(\"Missing Values per Column:\")\n", + " print(missing_values[missing_values > 0])\n", + " if missing_values.any():\n", + " print(\"\\nHandle Missing Values as needed.\")\n", + " else:\n", + " print(\"\\nNo Missing Values Found.\")\n", + "\n", + "check_missing_values(df)\n", + "df = df.drop('D_142', axis=1)\n", + "df = df.drop('S_3', axis=1)\n", + "for col in df.columns:\n", + " if df[col].dtype in ['int64', 'float64']:\n", + " # Impute numerical features with Mean\n", + " df[col] = df[col].fillna(df[col].mean())\n", + " else:\n", + " # Impute categorical features with Mode\n", + " # [0] is used because .mode() returns a Series\n", + " if not df[col].mode().empty:\n", + " df[col] = df[col].fillna(df[col].mode()[0])" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "def check_duplicates(df):\n", + " duplicates = df.duplicated().sum()\n", + " print(f\"Number of Duplicate Samples: {duplicates}\")\n", + " if duplicates > 0:\n", + " print(\"Dropping Duplicates...\")\n", + " df.drop_duplicates(inplace=True)\n", + " print(\"Duplicates Dropped.\")\n", + " else:\n", + " print(\"No Duplicate Samples Found.\")\n", + "\n", + "check_duplicates(df)\n", + "df" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "#not needed" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "from sklearn.preprocessing import StandardScaler\n", + "\n", + "\n", + "num_cols = df.select_dtypes(include=['int64', 'float64']).columns\n", + "num_cols = num_cols.drop('Target') # Remove this line if 'target' is categorical\n", + "\n", + "scaler = StandardScaler()\n", + "\n", + "# Apply scaling\n", + "df[num_cols] = scaler.fit_transform(df[num_cols])\n", + "\n", + "print(\"Scaling complete. Numerical features now have Mean ≈ 0 and Std ≈ 1.\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "# 1. Calculate the distribution\n", + "target_counts = df['Target'].value_counts()\n", + "target_pct = df['Target'].value_counts(normalize=True) * 100\n", + "\n", + "print(\"Target Distribution (Counts):\")\n", + "print(target_counts)\n", + "print(\"\\nTarget Distribution (Percentages):\")\n", + "print(target_pct)\n", + "\n", + "# 2. Define a threshold (e.g., 20% for the minority class)\n", + "imbalance_threshold = 20.0\n", + "minority_class_pct = target_pct.min()\n", + "\n", + "# 3. State the status\n", + "if minority_class_pct < imbalance_threshold:\n", + " print(f\"\\nSTATUS: The dataset is IMBALANCED.\")\n", + " print(f\"The minority class represents only {minority_class_pct:.2f}% of the data.\")\n", + "else:\n", + " print(f\"\\nSTATUS: The dataset is BALANCED.\")\n", + " print(f\"The minority class represents {minority_class_pct:.2f}% of the data.\")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:from catboost import CatBoostClassifier\n", + "from sklearn.model_selection import StratifiedKFold, cross_val_score\n", + "from sklearn.metrics import f1_score, make_scorer\n", + "\n", + "# 1. Split the dataset into features (X) and target (y)\n", + "X = df.drop('Target', axis=1)\n", + "y = df['Target']\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:\n", + "\n", + "import pandas as pd\n", + "import numpy as np\n", + "from sklearn.model_selection import KFold, cross_val_score\n", + "from sklearn.preprocessing import StandardScaler\n", + "from catboost import CatBoostClassifier\n", + "\n", + "# 1. Impute missing values\n", + "# Loop through columns: Mean for numerical, Mode for categorical\n", + "for col in df.columns:\n", + " if df[col].dtype in ['int64', 'float64']:\n", + " df[col] = df[col].fillna(df[col].mean())\n", + " else:\n", + " if not df[col].mode().empty:\n", + " df[col] = df[col].fillna(df[col].mode()[0])\n", + "\n", + "# 2. Feature Scaling (StandardScaler)\n", + "num_cols = df.select_dtypes(include=['int64', 'float64']).columns.tolist()\n", + "if 'target' in num_cols: num_cols.remove('Target') # Exclude target from scaling\n", + "\n", + "scaler = StandardScaler()\n", + "df[num_cols] = scaler.fit_transform(df[num_cols])\n", + "\n", + "# 3. Check for target imbalance\n", + "target_counts = df['Target'].value_counts(normalize=True)\n", + "minority_class_pct = target_counts.min()\n", + "\n", + "# Define status and metric\n", + "# If minority class is < 20%, we consider it imbalanced and use F1-Score\n", + "if minority_class_pct < 0.20:\n", + " imbalance_status = \"IMBALANCED\"\n", + " metric = 'f1' # Or 'f1_weighted' if multiclass\n", + " print(f\"Status: {imbalance_status} (Minority class: {minority_class_pct:.2%})\")\n", + " print(f\"Appropriate Metric: F1-Score\")\n", + "else:\n", + " imbalance_status = \"BALANCED\"\n", + " metric = 'accuracy'\n", + " print(f\"Status: {imbalance_status} (Minority class: {minority_class_pct:.2%})\")\n", + " print(f\"Appropriate Metric: Accuracy\")\n", + "\n", + "# 4. Split into features (X) and target (y)\n", + "X = df.drop('Target', axis=1)\n", + "y = df['Target']\n", + "\n", + "# Identify categorical feature indices for CatBoost\n", + "cat_features = X.select_dtypes(exclude=[np.number]).columns.tolist()\n", + "\n", + "# 5. Setup Normal KFold\n", + "kf = KFold(n_splits=5, shuffle=True, random_state=42)\n", + "\n", + "# 6. Train CatBoostClassifier\n", + "# iterations=100 for speed; increase for better performance\n", + "model = CatBoostClassifier(verbose=0, iterations=100, cat_features=cat_features)\n", + "\n", + "# 7. Evaluate and Print averaged score\n", + "scores = cross_val_score(model, X, y, cv=kf, scoring=metric)\n", + "\n", + "print(\"-\" * 30)\n", + "print(f\"Average {metric.capitalize()} across 5 folds: {scores.mean():.4f}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/39/Q1.ipynb b/submissions_extracted/39/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..10a3932b17f21caac6ad55c7af2cb06f841dac58 --- /dev/null +++ b/submissions_extracted/39/Q1.ipynb @@ -0,0 +1,319 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import numpy as np\n", + "import pandas as pd\n", + "import matplotlib.pyplot as plt\n", + "import os\n", + "import kagglehub\n", + "\n", + "from sklearn.model_selection import train_test_split, KFold\n", + "from sklearn.preprocessing import StandardScaler, LabelEncoder\n", + "from sklearn.ensemble import RandomForestRegressor\n", + "from sklearn.metrics import mean_absolute_error, mean_squared_error\n", + "\n", + "import warnings\n", + "warnings.filterwarnings('ignore')\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q1-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "data1_path = os.path.join( '/kaggle/input/q1-exam-data/Q1_data.csv')\n", + "df_data1= pd.read_csv(data1_path)\n", + "print(df_data1)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "df_data1.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "df_data1.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "df_data1.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:Plot the target distribution (delivery_time)\n", + "\n", + "\n", + "plt.figure(figsize=(10, 5))\n", + "plt.hist(df_data1['Delivery_Time'].dropna(), bins=30, edgecolor='black')\n", + "plt.title('Delivery_Time')\n", + "plt.xlabel('Delivery_Time')\n", + "plt.ylabel('Frequency')\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "df_clean = df_data1.dropna(subset=['Order_ID'])\n", + "print(df_clean)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:Handle missing values appropriately\n", + "missing_percentage = (df_clean.isnull().sum() / len(df_clean)) * 100\n", + "missing_data = pd.DataFrame({\n", + " 'Column': missing_percentage.index,\n", + " 'Missing_Percentage': missing_percentage.values\n", + "})\n", + "missing_data = missing_data[missing_data['Missing_Percentage'] > 0].sort_values('Missing_Percentage', ascending=False)\n", + "\n", + "print(\"Missing Data Analysis:\")\n", + "missing_data.head(10)\n", + "\n", + "for col in ['Delivery_Time', 'Weather', 'Traffic_Level', 'Time_of_Day', 'Courier_Experience_yrs']:\n", + " df_clean[col] = df_clean[col].fillna('unknown')\n", + "\n", + "print(\"Missing values remaining:\", df_clean.isnull().sum().sum())\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:Check and remove duplicates if any exist\n", + "# 4. Do we have duplicate samples?\n", + "def check_duplicates(df):\n", + " duplicates = df.duplicated().sum()\n", + " print(f\"Number of Duplicate Samples: {duplicates}\")\n", + " if duplicates > 0:\n", + " print(\"Dropping Duplicates...\")\n", + " df.drop_duplicates(inplace=True)\n", + " print(\"Duplicates Dropped.\")\n", + " else:\n", + " print(\"No Duplicate Samples Found.\")\n", + "\n", + "check_duplicates(df_clean)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "from sklearn.preprocessing import OneHotEncoder\n", + "\n", + "\n", + "df_str=[['Delivery_Time'], ['Weather'],['Traffic_Level'] , ['Time_of_Day'], ['Courier_Experience_yrs']]\n", + "\n", + "encoder = OneHotEncoder(sparse_output=False)\n", + "encoded = encoder.fit_transform(df_str)\n", + "\n", + "print(\"Original:\", df_clean)\n", + "print(\"Encoded:\\n\", encoded)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "from sklearn.preprocessing import StandardScaler\n", + "import numpy as np\n", + "\n", + "\n", + "\n", + "data = np.array([[1, 100, 50], # Feature 1: 1-5\n", + " [2, 200, 60], # Feature 2: 100-500\n", + " [3, 300, 70], # Feature 3: 50-90\n", + " [4, 400, 80],\n", + " [5, 500, 90]])\n", + "\n", + "scaler = StandardScaler()\n", + "scaled = scaler.fit_transform(data)\n", + "\n", + "print(\"Original:\\n\", data)\n", + "print(\"\\nScaled (mean≈0, std≈1):\\n\", scaled)\n", + "print(\"\\nMeans:\", scaled.mean(axis=0))\n", + "print(\"Stds:\", scaled.std(axis=0))\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 6: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "print(df_clean.keys)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "# Define features (X) and target (y)\n", + "\n", + "X = df_str\n", + "y = df_clean['Delivery_time']\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:\n", + "# Scale features\n", + "scaler = StandardScaler()\n", + "X_train_scaled = scaler.fit_transform(X_train)\n", + "X_test_scaled = scaler.transform(X_test)\n", + "model = RandomForestClassifier(n_estimators=100, max_depth=15,\n", + " class_weight='balanced', random_state=42)\n", + "model.fit(X_train_scaled, y_train)\n", + "print(\"Model trained!\")\n", + "# Predict and evaluate\n", + "y_pred = model.predict(X_test_scaled)\n", + "\n", + "mae = mean_absolute_error(y_test, y_pred)\n", + "rmse = np.sqrt(mean_squared_error(y_test, y_pred))\n", + "\n", + "print(f\"MAE: ${mae:,.2f}\")\n", + "print(f\"RMSE: ${rmse:,.2f}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "# Feature importance\n", + "feature_importance = pd.df_clean({\n", + " 'feature': feature_cols,\n", + " 'importance': model.feature_importances_\n", + "}).sort_values('importance', ascending=False)\n", + "\n", + "plt.figure(figsize=(10, 6))\n", + "plt.barh(feature_importance['feature'], feature_importance['importance'])\n", + "plt.xlabel('Importance')\n", + "plt.title('Feature Importance')\n", + "plt.gca().invert_yaxis()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:kfold = KFold(n_splits=5, shuffle=True, random_state=42)\n", + "\n", + "mae_scores = []\n", + "rmse_scores = []\n", + "\n", + "for train_idx, val_idx in kfold.split(X_train_scaled):\n", + " X_fold_train, X_fold_val = X_train_scaled[train_idx], X_train_scaled[val_idx]\n", + " y_fold_train, y_fold_val = y_train.iloc[train_idx], y_train.iloc[val_idx]\n", + "\n", + " # Train and predict\n", + " model.fit(X_fold_train, y_fold_train)\n", + " y_fold_pred = model.predict(X_fold_val)\n", + "\n", + " # Calculate metrics\n", + " mae_scores.append(mean_absolute_error(y_fold_val, y_fold_pred))\n", + " rmse_scores.append(np.sqrt(mean_squared_error(y_fold_val, y_fold_pred)))\n", + "\n", + "mae_scores = np.array(mae_scores)\n", + "rmse_scores = np.array(rmse_scores)\n", + "\n", + "print(f\"5-Fold CV Results:\")\n", + "print(f\"MAE: ${mae_scores.mean():,.2f}\")\n", + "print(f\"RMSE: ${rmse_scores.mean():,.2f}\")" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/39/Q2.ipynb b/submissions_extracted/39/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..26b315d2b5449f2a2c97cb6b646eae795e25f010 --- /dev/null +++ b/submissions_extracted/39/Q2.ipynb @@ -0,0 +1,202 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q2-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import numpy as np\n", + "import pandas as pd\n", + "import matplotlib.pyplot as plt\n", + "import os\n", + "import kagglehub\n", + "\n", + "from sklearn.model_selection import train_test_split, KFold\n", + "from sklearn.preprocessing import StandardScaler, LabelEncoder\n", + "from sklearn.ensemble import RandomForestRegressor\n", + "from sklearn.metrics import mean_absolute_error, mean_squared_error\n", + "\n", + "import warnings\n", + "warnings.filterwarnings('ignore')\n", + "\n", + "\n", + "\n", + "# Load Labels\n", + "labels_df = pd.read_csv(os.path.join(path, \"labels.csv\"))\n", + "img_dir = os.path.join(path, \"images\")\n", + "\n", + "images = []\n", + "ages = []\n", + "\n", + "# Load Images and Resize\n", + "print(\"Loading images...\")\n", + "for index, row in labels_df.iterrows():\n", + " img_name = row.iloc[0]\n", + " age = row.iloc[1]\n", + " img_path = os.path.join(img_dir, img_name)\n", + "\n", + " if os.path.exists(img_path):\n", + " img = Image.open(img_path).convert('RGB')\n", + " img_array = np.array(img) / 255.0 # Normalize pixel values to [0, 1]\n", + " images.append(img_array)\n", + " ages.append(age)\n", + "\n", + "X = np.array(images)\n", + "y = np.array(ages)\n", + "\n", + "# Transpose image dimensions to match PyTorch format (N, C, H, W)\n", + "X = np.transpose(X, (0, 3, 1, 2))\n", + "\n", + "# Split Data\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n", + "\n", + "print(f\"X_train shape: {X_train.shape}\")\n", + "print(f\"X_test shape: {X_test.shape}\")\n", + "print(f\"y_train shape: {y_train.shape}\")\n", + "print(f\"y_test shape: {y_test.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 1. Convert Numpy arrays to PyTorch Tensors\n", + "\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 2. Create TensorDataset objects\n", + "\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 3. Create DataLoaders\n", + "\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 4. Print shape of one batch\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 5. Display sample images\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your model class here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your training loop here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your validation loop here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Define device, model, loss, optimizer:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Start training for 20 epochs:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2 (Bonus): Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/39/Q3.ipynb b/submissions_extracted/39/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..c97832709061629f03a86d1f40306ca8a3e2a744 --- /dev/null +++ b/submissions_extracted/39/Q3.ipynb @@ -0,0 +1,160 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "\n", + "\n", + "# Download latest version\n", + "\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q3-exam-data\")\n", + "\n", + "\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/390/Q1.ipynb b/submissions_extracted/390/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..665fc956c1dc29233b8cbc856c2cf4a376633a12 --- /dev/null +++ b/submissions_extracted/390/Q1.ipynb @@ -0,0 +1,313 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q1-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import numpy as np\n", + "import pandas as pd\n", + "import matplotlib.pyplot as plt\n", + "import os\n", + "import kagglehub\n", + "\n", + "from sklearn.model_selection import train_test_split, KFold\n", + "from sklearn.preprocessing import StandardScaler, LabelEncoder\n", + "from sklearn.ensemble import RandomForestRegressor\n", + "from sklearn.metrics import mean_absolute_error, mean_squared_error\n", + "\n", + "import warnings\n", + "warnings.filterwarnings('ignore')" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "food_path =os.path.join(path, 'Q1_data.csv')\n", + "df_food = pd.read_csv(food_path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "print(f\"Dataset shape: {df_food.shape}\")\n", + "df_food.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "df_food.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "df_food.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "plt.figure(figsize=(10, 5))\n", + "plt.hist(df_food['Delivery_Time'].dropna(), bins=50, edgecolor='black')\n", + "plt.title('Delivery time Distribution')\n", + "plt.xlabel('Delivery time')\n", + "plt.ylabel('Frequency')\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "df_food.drop(columns=['Order_ID'])" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "def check_missing_values(df):\n", + " missing_values = df.isnull().sum()\n", + " print(\"Missing Values per Column:\")\n", + " print(missing_values[missing_values > 0])\n", + " if missing_values.any():\n", + " print(\"\\nHandle Missing Values as needed.\")\n", + " else:\n", + " print(\"\\nNo Missing Values Found.\")\n", + "\n", + "check_missing_values(df_food)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "cols=['Weather','Traffic_Level','Time_of_Day','Courier_Experience_yrs']\n", + "df_clean = df_food.dropna(subset=cols).copy()\n", + "print(f\"Shape after cleaning: {df_clean.shape}\")\n", + "\n", + "\n", + "df_clean['Delivery_Time']=df_clean['Delivery_Time'].fillna(df_clean['Delivery_Time'].mean())\n", + "print(df_clean.isnull().sum())" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "def check_duplicates(df):\n", + " duplicates = df.duplicated().sum()\n", + " print(f\"Number of Duplicate Samples: {duplicates}\")\n", + " if duplicates > 0:\n", + " print(\"Dropping Duplicates...\")\n", + " df.drop_duplicates(inplace=True)\n", + " print(\"Duplicates Dropped.\")\n", + " else:\n", + " print(\"No Duplicate Samples Found.\")\n", + "\n", + "check_duplicates(df_clean)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "from sklearn.preprocessing import OneHotEncoder #import OneHotEncoder\n", + "categorical_cols = ['Weather','Traffic_Level','Time_of_Day','Vehicle_Type']\n", + "\n", + "for col in categorical_cols:\n", + " le = LabelEncoder()\n", + " df_clean[col] = le.fit_transform(df_clean[col].astype(str))\n", + "\n", + "df_clean.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "from sklearn.preprocessing import StandardScaler\n", + "\n", + "print('data before scaling:\\n', df_clean)\n", + "standard_scaler = StandardScaler() # Instantiate StandardScaler\n", + "data_standard_scaled = standard_scaler.fit_transform(df_clean[cols]) # Apply fit_transform\n", + "\n", + "print('\\nData after scaling:\\n', data_standard_scaled) #show after scaling" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 6: Write your code here:\n", + "import seaborn as sns\n", + "def check_target_imbalance(df, target_column):\n", + " print(\"Target Distribution:\")\n", + " print(df[target_column].value_counts(normalize=True))\n", + " sns.countplot(x=df[target_column])\n", + " plt.title(\"Target Distribution\")\n", + " plt.show()\n", + "\n", + "check_target_imbalance(df_clean, \"Delivery_Time\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "X = df_clean[cols]\n", + "y = df_clean['Delivery_Time']" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:\n", + "\n", + "\n", + "from sklearn.model_selection import KFold\n", + "from sklearn.metrics import mean_absolute_error as sklearn_mae\n", + "from sklearn.ensemble import RandomForestRegressor\n", + "\n", + "\n", + "\n", + "# 5-Fold Cross-Validation, shuffled\n", + "kf = KFold(n_splits=5, shuffle=True, random_state=42)\n", + "\n", + "lr_mae=[]\n", + "for fold_idx, (train_index, test_index) in enumerate(kf.split(X,y)):\n", + " print(f\"\\nFold {fold_idx + 1}/{5}\")\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", + "\n", + "\n", + " # Train\n", + " model = RandomForestRegressor(n_estimators=100, max_depth=15)\n", + " model.fit(X_train,y_train)\n", + " y_pred= model.predict(X_test)\n", + "\n", + " #Metric\n", + " mae= sklearn_mae(y_test,y_pred)\n", + " print(mae)\n", + " lr_mae.append(mae)\n", + "\n", + "average_loss=np.mean(lr_mae,axis=0)\n", + "print(\"Average loss:\", average_loss)\n", + "" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "importance = pd.DataFrame({\n", + " 'feature': cols,\n", + " 'importance': model.feature_importances_\n", + "}).sort_values('importance', ascending=False)\n", + "\n", + "plt.figure(figsize=(10, 6))\n", + "plt.barh(importance['feature'], importance['importance'], color='purple')\n", + "plt.xlabel('Importance')\n", + "plt.title('Feature Importance')\n", + "plt.gca().invert_yaxis()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/390/Q2.ipynb b/submissions_extracted/390/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..9b37ab53d61cc36b7a257846fe18a39afd94320e --- /dev/null +++ b/submissions_extracted/390/Q2.ipynb @@ -0,0 +1,388 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q2-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import os\n", + "import pandas as pd\n", + "import numpy as np\n", + "from PIL import Image\n", + "from sklearn.model_selection import train_test_split\n", + "\n", + "# Load Labels\n", + "labels_df = pd.read_csv(os.path.join(path, \"labels.csv\"))\n", + "img_dir = os.path.join(path, \"images\")\n", + "\n", + "images = []\n", + "ages = []\n", + "\n", + "# Load Images and Resize\n", + "print(\"Loading images...\")\n", + "for index, row in labels_df.iterrows():\n", + " img_name = row.iloc[0]\n", + " age = row.iloc[1]\n", + " img_path = os.path.join(img_dir, img_name)\n", + "\n", + " if os.path.exists(img_path):\n", + " img = Image.open(img_path).convert('RGB')\n", + " img_array = np.array(img) / 255.0 # Normalize pixel values to [0, 1]\n", + " images.append(img_array)\n", + " ages.append(age)\n", + "\n", + "X = np.array(images)\n", + "y = np.array(ages)\n", + "\n", + "# Transpose image dimensions to match PyTorch format (N, C, H, W)\n", + "X = np.transpose(X, (0, 3, 1, 2))\n", + "\n", + "# Split Data\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n", + "\n", + "print(f\"X_train shape: {X_train.shape}\")\n", + "print(f\"X_test shape: {X_test.shape}\")\n", + "print(f\"y_train shape: {y_train.shape}\")\n", + "print(f\"y_test shape: {y_test.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 1. Convert Numpy arrays to PyTorch Tensors\n", + "import torch\n", + "import torch.nn as nn\n", + "import torch.nn.functional as F\n", + "from torch.optim import AdamW\n", + "X_train = torch.tensor(X_train, dtype=torch.float32)\n", + "X_test = torch.tensor(X_test, dtype=torch.float32)\n", + "y_train = torch.tensor(y_train, dtype=torch.float32)\n", + "y_test = torch.tensor(y_test, dtype=torch.float32)\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 2. Create TensorDataset objects\n", + "from torch.utils.data import DataLoader, TensorDataset\n", + "\n", + "train_dataset = TensorDataset(X_train, y_train)\n", + "test_dataset = TensorDataset(X_test, y_test)\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 3. Create DataLoaders\n", + "from torchvision.datasets import CIFAR10\n", + "from torchvision.transforms.functional import to_tensor\n", + "from torch.utils.data import DataLoader\n", + "train_loader = DataLoader( train_dataset, batch_size=32, shuffle=True, num_workers=2)\n", + "test_loader = DataLoader( test_dataset, batch_size=32, shuffle=False, num_workers=2)\n", + "\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 4. Print shape of one batch\n", + "X_batch, y_batch = next(iter(train_loader))\n", + "print(f\"Training batch input shape: {X_batch.shape}\")\n", + "print(f\"Training batch labels shape: {y_batch.shape}\")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 5. Display sample images\n", + "\n", + "import matplotlib.pyplot as plt\n", + "# Get one batch of images and labels\n", + "images, labels = next(iter(train_loader))\n", + "\n", + "# Display the first 6 images in the batch\n", + "plt.figure(figsize=(8, 4))\n", + "\n", + "for i in range(6):\n", + " plt.subplot(2, 3, i + 1)\n", + "\n", + " # Convert from (C, H, W) to (H, W, C) for matplotlib\n", + " img = images[i].permute(1, 2, 0)\n", + "\n", + " plt.imshow(img)\n", + " plt.title(f\"Label: {labels[i].item()}\")\n", + " plt.axis('off')\n", + "\n", + "plt.tight_layout()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your model class here:\n", + "import torch.nn as nn\n", + "\n", + "class NN4Layer(nn.Module):\n", + "\n", + " def __init__(self, input_dim, hidden_dim, output_dim):\n", + " super(NN4Layer, self).__init__()\n", + "\n", + " # First linear layer: input features -> hidden layer\n", + " self.layer1 = nn.Linear(input_dim, hidden_dim)\n", + "\n", + " # Second linear layer: hidden layer -> hidden layer\n", + " self.layer2 = nn.Linear(hidden_dim, hidden_dim)\n", + "\n", + " # Output layer: hidden layer -> number of classes (logits)\n", + " self.layer3 = nn.Linear(hidden_dim, hidden_dim)\n", + "\n", + " self.layer4 = nn.Linear(hidden_dim, output_dim)\n", + "\n", + " # ReLU activation for non-linearity\n", + " self.relu = nn.ReLU()\n", + "\n", + " # Defines how input data flows through the network\n", + " def forward(self, x):\n", + " # First hidden layer\n", + " z1 = self.layer1(x)\n", + " a1 = self.relu(z1)\n", + "\n", + " # Second hidden layer\n", + " z2 = self.layer2(a1)\n", + " a2 = self.relu(z2)\n", + "\n", + " #Third hidden layer\n", + " z3 = self.layer2(a2)\n", + " a3 = self.relu(z3)\n", + "\n", + " # Output layer (raw scores / logits)\n", + " output = self.layer3(a3)\n", + "\n", + " return output\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your training loop here:\n", + "def train_one_epoch(model, optimizer, criterion, train_loader, device):\n", + " # Set the model to training mode\n", + " model.train()\n", + "\n", + " running_loss = 0.0\n", + "\n", + " for X_batch, y_batch in train_loader:\n", + " # Move batch to the selected device\n", + " X_batch = X_batch.view(X_batch.size(0), -1).to(device)\n", + " y_batch = y_batch.to(device)\n", + "\n", + " # Forward pass\n", + " outputs = model(X_batch) # shape: (batch_size, 10)\n", + " loss = criterion(outputs, y_batch)\n", + "\n", + " # Backward pass & optimization\n", + " optimizer.zero_grad() # Clear previous gradients\n", + " loss.backward() # Compute gradients\n", + " optimizer.step() # Update model parameters\n", + "\n", + " running_loss += loss.item()\n", + "\n", + " # Average loss over all batches\n", + " avg_loss = running_loss / len(train_loader)\n", + "\n", + " return avg_loss" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your validation loop here:\n", + "def validate(model, criterion, test_loader, device):\n", + " # Set the model to evaluation mode\n", + " model.eval()\n", + "\n", + " running_loss = 0.0\n", + " correct = 0\n", + " total = 0\n", + "\n", + " with torch.no_grad():\n", + " for X_batch, y_batch in test_loader:\n", + " # Move data to device\n", + " X_batch = X_batch.view(X_batch.size(0), -1).to(device)\n", + " y_batch = y_batch.to(device)\n", + "\n", + " # Forward pass\n", + " #outputs = model(X_batch) # shape: (batch_size, 10)\n", + " #loss = criterion(outputs, y_batch)\n", + " #running_loss += loss.item()\n", + "\n", + " # Apply Softmax to get probabilities\n", + " #probabilities = nn.softmax(outputs, dim=1)\n", + "\n", + " # Multiclass predictions\n", + " #predicted = torch.argmax(probabilities, dim=1)\n", + "\n", + " # Accuracy calculation\n", + " #correct += (predicted == y_batch).sum().item()\n", + " total += y_batch.size(0)\n", + "\n", + " avg_loss = running_loss / len(test_loader)\n", + " accuracy = correct / total\n", + "\n", + " return avg_loss, accuracy\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Define device, model, loss, optimizer:\n", + "# Device setup\n", + "device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n", + "\n", + "# Model parameters\n", + "input_dim = 32 * 32 # MNIST images flattened\n", + "hidden_dim = 14 # Design choice\n", + "output_dim = 1\n", + "\n", + "# Instantiate model\n", + "model = NN4Layer(input_dim, hidden_dim, output_dim).to(device)\n", + "\n", + "# Print the model architecture\n", + "print(\"Model Architecture:\\n\")\n", + "print(model)\n", + "\n", + "# Calculate the total number of trainable parameters\n", + "total_params = sum(p.numel() for p in model.parameters() if p.requires_grad)\n", + "print(f\"\\nTotal trainable parameters: {total_params}\")\n", + "\n", + "# Define criterion (loss function) - using CrossEntropyLoss as model now outputs logits\n", + "criterion = nn.CrossEntropyLoss()\n", + "# Define optimizer\n", + "learning_rate = 0.001\n", + "\n", + "optimizer = Adam(model.parameters(), learning_rate)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Start training for 20 epochs:\n", + "from torch.optim import Adam\n", + "\n", + "num_epochs = 20\n", + "\n", + "\n", + "# Run Training\n", + "train_losses = []\n", + "val_losses = []\n", + "val_accuracies = []\n", + "\n", + "print('Starting Training...')\n", + "for epoch in range(num_epochs):\n", + " # Train one epoch\n", + " train_loss = train_one_epoch(model, optimizer, criterion, train_loader, device)\n", + "\n", + " # Validate\n", + " val_loss, val_accuracy = validate(model, criterion, test_loader, device)\n", + "\n", + " train_losses.append(train_loss)\n", + " val_losses.append(val_loss)\n", + " val_accuracies.append(val_accuracy)\n", + "\n", + " print(f'Epoch [{epoch+1}/{num_epochs}], Train Loss: {train_loss:.4f}, Val Loss: {val_loss:.4f}, Val Accuracy: {val_accuracy:.4f}')\n", + "\n", + "print('Training Complete!')\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:# Plotting results\n", + "plt.figure(figsize=(7, 5))\n", + "\n", + "plt.plot(train_losses, label='Train Loss')\n", + "plt.plot(val_losses, label='Validation Loss')\n", + "plt.title('Loss over Epochs')\n", + "plt.xlabel('Epoch')\n", + "plt.ylabel('Loss')\n", + "plt.legend()\n", + "\n", + "plt.tight_layout()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2 (Bonus): Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/390/Q3.ipynb b/submissions_extracted/390/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..e69941968b754e5b3fdfc4eeb9ebff897d40822b --- /dev/null +++ b/submissions_extracted/390/Q3.ipynb @@ -0,0 +1,204 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "import numpy as np\n", + "import pandas as pd\n", + "import matplotlib.pyplot as plt\n", + "import os\n", + "import kagglehub\n", + "\n", + "from sklearn.model_selection import train_test_split, KFold\n", + "from sklearn.preprocessing import StandardScaler, LabelEncoder\n", + "from sklearn.ensemble import RandomForestRegressor\n", + "from sklearn.metrics import mean_absolute_error, mean_squared_error\n", + "\n", + "import warnings\n", + "warnings.filterwarnings('ignore')\n", + "\n", + "\n", + "# Download latest version\n", + "\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q3-exam-data\")\n", + "\n", + "\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "data_path =os.path.join(path, 'Q3_data.csv')\n", + "df = pd.read_csv(data_path)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "print(f\"Dataset shape: {df.shape}\")\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "df.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "df.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "def check_missing_values(df):\n", + " missing_values = df.isnull().sum()\n", + " print(\"Missing Values per Column:\")\n", + " print(missing_values[missing_values > 0])\n", + " if missing_values.any():\n", + " print(\"\\nHandle Missing Values as needed.\")\n", + " else:\n", + " print(\"\\nNo Missing Values Found.\")\n", + "\n", + "check_missing_values(df)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "cols=['Weather','Traffic_Level','Time_of_Day','Courier_Experience_yrs']\n", + "df_clean = df.drop(subset['Target'])\n", + "df_clan=df_clan.dropna(subset=cols).copy()\n", + "print(f\"Shape after cleaning: {df_clean.shape}\")\n", + "\n", + "\n", + "df_clean['Delivery_Time']=df_clean['Delivery_Time'].fillna(df_clean['Delivery_Time'].mean())\n", + "print(df_clean.isnull().sum())" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/391/Q1.ipynb b/submissions_extracted/391/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..734914444ed3129a42cd5d0efb99512ab464476b --- /dev/null +++ b/submissions_extracted/391/Q1.ipynb @@ -0,0 +1,379 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import numpy as np\n", + "import pandas as pd\n", + "import matplotlib.pyplot as plt\n", + "import seaborn as sns\n", + "import os\n", + "import kagglehub\n", + "\n", + "from sklearn.model_selection import train_test_split, StratifiedKFold, cross_val_score\n", + "from sklearn.preprocessing import StandardScaler, LabelEncoder\n", + "from sklearn.ensemble import RandomForestClassifier\n", + "from sklearn.metrics import classification_report, confusion_matrix, accuracy_score\n", + "\n", + "import warnings\n", + "warnings.filterwarnings('ignore')" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q1-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "#Read the dataset Q1_data.csv using read_csv():\n", + "\n", + "Q1_path = os.path.join(path, 'Q1_data.csv')\n", + "df = pd.read_csv(Q1_path)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "#Inspect the first few rows using head():\n", + "\n", + "print(f\"Shape: {df.shape}\")\n", + "df.head(10)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "#Display dataset information using info():\n", + "\n", + "df.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "#Show statistical description using describe():\n", + "\n", + "df.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "#Plot the target distribution (delivery_time):\n", + "\n", + "plt.figure(figsize=(10, 5))\n", + "plt.hist(df['Delivery_Time'].dropna(), bins=30, edgecolor='black')\n", + "plt.title('target distribution')\n", + "plt.xlabel('delivery_time')\n", + "plt.ylabel('minutes')\n", + "plt.show()\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "#Drop the 'Order_ID' column from the data:\n", + "\n", + "df=df.drop(['Order_ID'], axis=1)\n", + "\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "#Handle missing values appropriately (Hint: I guess you want to have a closer look at the columns with missing values :) )\n", + "\n", + "def check_missing_values(df):\n", + " missing_values = df.isnull().sum()\n", + " print(\"Missing Values per Column:\")\n", + " print(missing_values[missing_values > 0])\n", + " if missing_values.any():\n", + " print(\"\\nHandle Missing Values as needed.\")\n", + " else:\n", + " print(\"\\nNo Missing Values Found.\")\n", + "\n", + "check_missing_values(df)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "#Check and remove duplicates if any exist:\n", + "\n", + "def check_duplicates(df):\n", + "\n", + " #TODO: get duplicated data using pandas\n", + " duplicates = df.duplicated().sum()\n", + "\n", + " print(f\"Number of Duplicate Samples: {duplicates}\")\n", + " if duplicates > 0:\n", + " print(\"Dropping Duplicates...\")\n", + " df.drop_duplicates(inplace=True)\n", + " print(\"Duplicates Dropped.\")\n", + " else:\n", + " print(\"No Duplicate Samples Found.\")\n", + "\n", + "check_duplicates(df)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "#Encode categorical variables if needed (Bonus if used One Hot Encoding):\n", + "\n", + "from sklearn.preprocessing import OneHotEncoder #import OneHotEncoder\n", + "onehot_encoder = OneHotEncoder(sparse_output=False) # Instantiate OneHotEncoder\n", + "data_onehot_encoded = onehot_encoder.fit_transform(df) # Apply fit_transform to the copied\n", + "\n", + "print('\\nData after encoding:\\n', data_onehot_encoded) #show after encoding" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "#Apply feature scaling for all features (Use StandardScaler):\n", + "from sklearn.preprocessing import StandardScaler #import StandardScaler\n", + "standard_scaler = StandardScaler() # Instantiate StandardScaler\n", + "data_standard_scaled = standard_scaler.fit_transform(data_onehot_encoded) # Apply fit_transform\n", + "\n", + "print('\\nData after scaling:\\n', data_standard_scaled) #show after scaling" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 6: Write your code here:\n", + "#Check for target imbalance and state if it is imbalanced or not (keep this cell empty if not needed):\n", + "\n", + "def check_target_imbalance(df, target_column):\n", + " print(\"Target Distribution:\")\n", + " print(df[target_column].value_counts(normalize=True))\n", + " sns.countplot(x=df[target_column])\n", + " plt.title(\"Target Distribution\")\n", + " plt.show()\n", + "\n", + "check_target_imbalance(df, \"Delivery_Time\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Drop rows with missing stat values\n", + "df1 = df.dropna().copy()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "\n", + "from sklearn.model_selection import train_test_split\n", + "# Define features and target\n", + "feature_cols = ['Distance_km', 'Weather', 'Traffic_Level', 'Time_of_Day', 'Vehicle_Type', 'Preparation_Time_min', 'Courier_Experience_yrs' ]\n", + "\n", + "X = df1[feature_cols]\n", + "y = df1['Delivery_Time']\n", + "df\n", + "# Stratified split\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42, stratify=y)\n", + "print(f\"Train: {X_train.shape}, Test: {X_test.shape}\")\n", + "print(f\"delivery time: {y_train.sum()}, in test: {y_test.sum()}\")\n", + "\n", + "\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:\n", + "from sklearn.model_selection import KFold\n", + "\n", + "# Use previously generated random data (example: regression data)\n", + "X, y = x.copy(), y.copy()\n", + "\n", + "# Define K-Fold Cross Validation\n", + "kf = KFold(n_splits=5, shuffle=True, random_state=42)\n", + "\n", + "# Iterate through folds\n", + "for fold, (train_idx, test_idx) in enumerate(kf.split(X), start=1):\n", + " # indexing for each fold\n", + " X_train, X_test = X.iloc[train_idx], X.iloc[test_idx]\n", + " y_train, y_test = y.iloc[train_idx], y.iloc[test_idx]\n", + " # print shapes\n", + " print(f\"Fold {fold}\")\n", + " print(\" X_train shape:\", X_train.shape)\n", + " print(\" X_test shape :\", X_test.shape)\n", + " print(\" y_train shape:\", y_train.shape)\n", + " print(\" y_test shape :\", y_test.shape)\n", + " print(\"-\" * 30)\n", + "\n", + "#3:\n", + "# Train Random Forest Regressor\n", + "model = RandomForestRegressor(n_estimators=100, max_depth=20, random_state=42, n_jobs=-1)\n", + "model.fit(X_train_scaled, y_train)\n", + "print(\"Model trained!\")\n", + "\n", + "#4:\n", + "y_pred = model.predict(X_test_scaled)\n", + "\n", + "mae = mean_absolute_error(y_test, y_pred)\n", + "\n", + "print(f\"MAE: ${mae:,.2f}\")\n", + "\n", + "\n", + "kfold = KFold(n_splits=5, shuffle=True, random_state=42)\n", + "\n", + "mae_scores = []\n", + "rmse_scores = []\n", + "\n", + "for train_idx, val_idx in kfold.split(X_train_scaled):\n", + " X_fold_train, X_fold_val = X_train_scaled[train_idx], X_train_scaled[val_idx]\n", + " y_fold_train, y_fold_val = y_train.iloc[train_idx], y_train.iloc[val_idx]\n", + "\n", + " # Train and predict\n", + " model.fit(X_fold_train, y_fold_train)\n", + " y_fold_pred = model.predict(X_fold_val)\n", + "\n", + " # Calculate metrics\n", + " mae_scores.append(mean_absolute_error(y_fold_val, y_fold_pred))\n", + " rmse_scores.append(np.sqrt(mean_squared_error(y_fold_val, y_fold_pred)))\n", + "\n", + "mae_scores = np.array(mae_scores)\n", + "rmse_scores = np.array(rmse_scores)\n", + "\n", + "print(f\"5-Fold CV Results:\")\n", + "print(f\"MAE: ${mae_scores.mean():,.2f}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "importance = pd.DataFrame({\n", + " 'feature': feature_cols,\n", + " 'importance': model.feature_importances_\n", + "}).sort_values('importance', ascending=False)\n", + "\n", + "plt.figure(figsize=(10, 6))\n", + "plt.barh(importance['feature'], importance['importance'], color='purple')\n", + "plt.xlabel('Importance')\n", + "plt.title('Feature Importance')\n", + "plt.gca().invert_yaxis()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:\n", + "# Plot for Linear Regression Predictions vs. Ground Truth\n", + "plt.figure(figsize=(6, 4))\n", + "plt.scatter(y_test, y_pred, alpha=0.7)\n", + "plt.plot([min(y_test), max(y_test)], [min(y_test), max(y_test)], 'r--', linewidth=2)\n", + "plt.xlabel(\"Actual y_test (Ground Truth)\")\n", + "plt.ylabel(\"Predicted y_pred (Linear Regression)\")\n", + "plt.title(\"Linear Regression: Predictions vs. Ground Truth\")\n", + "plt.grid(True)\n", + "\n", + "plt.tight_layout()\n", + "plt.show()\n", + "\n", + "# it should show us our Predictions vs. Ground Truth so we can see the diffrent." + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/391/Q2.ipynb b/submissions_extracted/391/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..8549aa108982a71d4810f3c197078cc88e31a3b8 --- /dev/null +++ b/submissions_extracted/391/Q2.ipynb @@ -0,0 +1,437 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import numpy as np\n", + "import pandas as pd\n", + "import matplotlib.pyplot as plt\n", + "import seaborn as sns\n", + "from scipy import stats\n", + "from tqdm import tqdm\n", + "tqdm.pandas()\n", + "\n", + "from sklearn.preprocessing import LabelEncoder\n", + "from sklearn.linear_model import LogisticRegression\n", + "from sklearn.model_selection import KFold\n", + "\n", + "from lightgbm import LGBMClassifier\n", + "from xgboost import XGBClassifier\n", + "from sklearn.ensemble import RandomForestClassifier\n", + "from sklearn.ensemble import VotingClassifier\n", + "from sklearn.metrics import f1_score\n", + "import torch.nn as nn\n", + "import torch.optim as optim\n", + "from torch.utils.data import DataLoader, TensorDataset\n", + "from sklearn.model_selection import train_test_split\n", + "from sklearn.preprocessing import StandardScaler, LabelEncoder\n", + "from sklearn.metrics import mean_absolute_error, mean_squared_error, r2_score\n", + "import warnings\n", + "warnings.simplefilter(action='ignore', category=FutureWarning)\n", + "pd.options.mode.chained_assignment = None # default='warn'\n", + "#pd.set_option('display.float_format', lambda x: '%.3f' % x)\n", + "plt.rcParams[\"figure.figsize\"] = (12, 8)\n", + "pd.set_option('display.max_columns', None)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Import required libraries\n", + "import kagglehub\n", + "import pandas as pd\n", + "import numpy as np\n", + "import torch\n", + "import torch.nn as nn\n", + "from torch.optim import AdamW\n", + "import matplotlib.pyplot as plt\n", + "from torch.utils.data import DataLoader, TensorDataset\n", + "from sklearn.model_selection import train_test_split\n", + "from sklearn.preprocessing import StandardScaler, LabelEncoder\n", + "from sklearn.metrics import mean_absolute_error, mean_squared_error, r2_score\n", + "\n", + "print(f\"PyTorch version: {torch.__version__}\")\n", + "print(f\"CUDA available: {torch.cuda.is_available()}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q2-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import os\n", + "import pandas as pd\n", + "import numpy as np\n", + "from PIL import Image\n", + "from sklearn.model_selection import train_test_split\n", + "\n", + "# Load Labels\n", + "labels_df = pd.read_csv(os.path.join(path, \"labels.csv\"))\n", + "img_dir = os.path.join(path, \"images\")\n", + "\n", + "images = []\n", + "ages = []\n", + "\n", + "# Load Images and Resize\n", + "print(\"Loading images...\")\n", + "for index, row in labels_df.iterrows():\n", + " img_name = row.iloc[0]\n", + " age = row.iloc[1]\n", + " img_path = os.path.join(img_dir, img_name)\n", + "\n", + " if os.path.exists(img_path):\n", + " img = Image.open(img_path).convert('RGB')\n", + " img_array = np.array(img) / 255.0 # Normalize pixel values to [0, 1]\n", + " images.append(img_array)\n", + " ages.append(age)\n", + "\n", + "X = np.array(images)\n", + "y = np.array(ages)\n", + "\n", + "# Transpose image dimensions to match PyTorch format (N, C, H, W)\n", + "X = np.transpose(X, (0, 3, 1, 2))\n", + "\n", + "# Split Data\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n", + "\n", + "print(f\"X_train shape: {X_train.shape}\")\n", + "print(f\"X_test shape: {X_test.shape}\")\n", + "print(f\"y_train shape: {y_train.shape}\")\n", + "print(f\"y_test shape: {y_test.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 1. Convert Numpy arrays to PyTorch Tensors\n", + "\n", + "import torch\n", + "X_train = torch.tensor(X_train, dtype=torch.float32)\n", + "X_test = torch.tensor(X_test, dtype=torch.float32)\n", + "y_train = torch.tensor(y_train, dtype=torch.float32)\n", + "y_test = torch.tensor(y_test, dtype=torch.float32)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 2. Create TensorDataset objects\n", + "\n", + "train_dataset = TensorDataset(X_train, y_train)\n", + "test_dataset = TensorDataset(X_test, y_test)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 3. Create DataLoaders\n", + "\n", + "train_loader = DataLoader(train_dataset, batch_size=32, shuffle=True)\n", + "test_loader = DataLoader(test_dataset, batch_size=32, shuffle=False)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 4. Print shape of one batch\n", + "\n", + "print(\"Train dataset:\", len(train_dataset))\n", + "print(\"Test dataset:\", len(test_dataset))" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 5. Display sample images\n", + "\n", + "from torchvision.datasets import MNIST\n", + "from torchvision.transforms.functional import to_tensor\n", + "\n", + "# Training dataset\n", + "train_dataset = MNIST(\n", + " root='./datasets', # Dataset storage path\n", + " train=True, # Use training data\n", + " transform=to_tensor, # Convert images to tensors\n", + " download=True # Download if not available\n", + ")\n", + "\n", + "# Testing dataset\n", + "test_dataset = MNIST(\n", + " root='./datasets', # Dataset storage path\n", + " train=False, # Use test data\n", + " transform=to_tensor, # Convert images to tensors\n", + " download=True # Download if not available\n", + ")\n", + "\n", + "# print one sample from the dataset\n", + "# Each sample consists of an image tensor and its label\n", + "sample_image, sample_label = train_dataset[0]\n", + "\n", + "print(f\"\\n Image shape: {sample_image.shape}\") # (1, 28, 28)\n", + "print(f\"Label: {sample_label}\")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your model class here:\n", + "#Create a model class with 4 linear layers:\n", + "\n", + "class NN3Layer(nn.Module):\n", + " def __init__(self, input_dim, hidden_dim):\n", + " super(NN3Layer, self).__init__()\n", + "\n", + " # First linear layer: input features -> hidden layer\n", + " self.layer1 = nn.Linear(input_dim, hidden_dim)\n", + "\n", + " # Second linear layer: hidden layer -> hidden layer\n", + " self.layer2 = nn.Linear(hidden_dim, hidden_dim)\n", + "\n", + " self.layer3 = nn.Linear(hidden_dim, hidden_dim)\n", + "\n", + " # Output layer: hidden layer -> single continuous value\n", + " self.layer4 = nn.Linear(hidden_dim, 1)\n", + "\n", + "\n", + " # ReLU activation for non-linearity in hidden layers\n", + " self.relu = nn.ReLU()\n", + "\n", + " # Defines how input data flows through the network\n", + " def forward(self, x):\n", + " # First hidden layer\n", + " a1 = self.relu(self.layer1(x))\n", + "\n", + " # Second hidden layer\n", + " a2 = self.relu(self.layer2(a1))\n", + "\n", + " a3= self.relu(self.layer2(a2))\n", + "\n", + " # Output layer (regression output)\n", + " output = self.layer3(a3)\n", + "\n", + " return output" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your training loop here:\n", + "#Create a training loop function:\n", + "def train_one_epoch(model, optimizer, criterion, train_loader, device):\n", + " # Set the model to training mode\n", + " model.train()\n", + "\n", + " running_loss = 0.0\n", + "\n", + " for X_batch, y_batch in train_loader:\n", + " # Move batch to the selected device\n", + " X_batch = X_batch.to(device) # shape: (batch_size, num_features)\n", + " y_batch = y_batch.view(-1, 1).to(device) # shape: (batch_size, 1)\n", + "\n", + " # Forward pass (continuous output)\n", + " outputs = model(X_batch) # shape: (batch_size, 1)\n", + " loss = criterion(outputs, y_batch)\n", + "\n", + " # Backward pass & optimization\n", + " optimizer.zero_grad() # Clear previous gradients\n", + " loss.backward() # Compute gradients\n", + " optimizer.step() # Update model parameters\n", + "\n", + " running_loss += loss.item()\n", + "\n", + " # Average loss over all batches\n", + " avg_loss = running_loss / len(train_loader)\n", + "\n", + " return avg_loss" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your validation loop here:\n", + "#Create a validation loop function\n", + "def validate(model, criterion, test_loader, device):\n", + " # Set the model to evaluation mode\n", + " model.eval()\n", + "\n", + " running_loss = 0.0\n", + "\n", + " with torch.no_grad():\n", + " for X_batch, y_batch in test_loader:\n", + " # Move data to device\n", + " X_batch = X_batch.to(device) # shape: (batch_size, num_features)\n", + " y_batch = y_batch.view(-1, 1).to(device) # shape: (batch_size, 1)\n", + "\n", + " # Forward pass (continuous output)\n", + " outputs = model(X_batch) # shape: (batch_size, 1)\n", + " loss = criterion(outputs, y_batch)\n", + "\n", + " running_loss += loss.item()\n", + "\n", + " # Average loss over all batches\n", + " avg_loss = running_loss / len(test_loader)\n", + "\n", + " return avg_loss" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Define device, model, loss, optimizer:\n", + "#Define the device, model, loss function, and optimizer:\n", + "\n", + "# TODO: Set up the device (use GPU if available, otherwise CPU)\n", + "device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n", + "input_dim = X_train.shape[1] # Number of tabular features\n", + "hidden_dim = 30 # Design choice\n", + "\n", + "# Instantiate regression model\n", + "model = NN3Layer(input_dim, hidden_dim).to(device)\n", + "\n", + "criterion = nn.CrossEntropyLoss()\n", + "optimizer = optim.Adam(model.parameters(), lr=0.001)\n", + "\n", + "print(\"Model Architecture:\\n\")\n", + "print(model)\n", + "\n", + "# Calculate the total number of trainable parameters\n", + "total_params = sum(p.numel() for p in model.parameters() if p.requires_grad)\n", + "print(f\"\\nTotal trainable parameters: {total_params}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Start training for 20 epochs:\n", + "#Start training for 20 epochs and track training and validation losses:\n", + "\n", + "num_epochs = 20\n", + "learning_rate = 0.001\n", + "\n", + "# Define criterion (loss function)\n", + "criterion = nn.MSELoss()\n", + "# Define optimizer\n", + "optimizer = AdamW(model.parameters(), learning_rate)\n", + "\n", + "# Run Training\n", + "train_losses = []\n", + "val_losses = []\n", + "\n", + "print('Starting Training...')\n", + "for epoch in range(num_epochs):\n", + " # Train one epoch\n", + " train_loss = train_one_epoch(model, optimizer, criterion, train_loader, device)\n", + "\n", + " # Validate\n", + " val_loss = validate(model, criterion, test_loader, device)\n", + "\n", + " train_losses.append(train_loss)\n", + " val_losses.append(val_loss)\n", + "\n", + " if (epoch + 1) % 5 == 0:\n", + " print(\n", + " f'Epoch [{epoch+1}/{num_epochs}], '\n", + " f'Train Loss: {train_loss:.4f}, '\n", + " f'Val Loss: {val_loss:.4f}'\n", + " )\n", + "\n", + "print('Training Complete!')\n", + "#" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "#Plot the training and validation loss over epochs:\n", + "# Plotting results\n", + "plt.figure(figsize=(7, 5))\n", + "\n", + "plt.plot(train_losses, label='Train Loss')\n", + "plt.plot(val_losses, label='Validation Loss')\n", + "plt.title('Loss over Epochs')\n", + "plt.xlabel('Epoch')\n", + "plt.ylabel('Loss (MSE)')\n", + "plt.legend()\n", + "\n", + "plt.tight_layout()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2 (Bonus): Write your code here:\n", + "#Bonus: Plot some predictions with their actual images (show predicted age vs actual age)\n" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/391/Q3.ipynb b/submissions_extracted/391/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..f5942c5802ce85d99bae58220001c894779cfb8f --- /dev/null +++ b/submissions_extracted/391/Q3.ipynb @@ -0,0 +1,322 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "from torchvision.datasets import CIFAR10\n", + "from torchvision.transforms.functional import to_tensor\n", + "from torch.utils.data import DataLoader\n", + "import matplotlib.pyplot as plt\n", + "import torch.nn as nn\n", + "import torch.nn.functional as F\n", + "import torch\n", + "from torch.optim import AdamW\n", + "import numpy as np\n", + "import pandas as pd\n", + "import matplotlib.pyplot as plt\n", + "import seaborn as sns\n", + "import os\n", + "import kagglehub\n", + "\n", + "from sklearn.model_selection import train_test_split, StratifiedKFold, cross_val_score\n", + "from sklearn.preprocessing import StandardScaler, LabelEncoder\n", + "from sklearn.ensemble import RandomForestClassifier\n", + "from sklearn.metrics import classification_report, confusion_matrix, accuracy_score\n", + "\n", + "import warnings\n", + "warnings.filterwarnings('ignore')" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "\n", + "\n", + "# Download latest version\n", + "\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q3-exam-data\")\n", + "\n", + "\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "Q3_path = os.path.join(path, 'Q3_data.csv')\n", + "df = pd.read_csv(Q3_path)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "print(f\"Shape: {df.shape}\")\n", + "df.head(10)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "df.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "df.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "\n", + "def check_missing_values(df):\n", + " missing_values = df.isnull().sum()\n", + " print(\"Missing Values per Column:\")\n", + " print(missing_values[missing_values > 0])\n", + " if missing_values.any():\n", + " print(\"\\nHandle Missing Values as needed.\")\n", + " else:\n", + " print(\"\\nNo Missing Values Found.\")\n", + "\n", + "check_missing_values(df)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "def check_duplicates(df):\n", + "\n", + " #TODO: get duplicated data using pandas\n", + " duplicates = df.duplicated().sum()\n", + "\n", + " print(f\"Number of Duplicate Samples: {duplicates}\")\n", + " if duplicates > 0:\n", + " print(\"Dropping Duplicates...\")\n", + " df.drop_duplicates(inplace=True)\n", + " print(\"Duplicates Dropped.\")\n", + " else:\n", + " print(\"No Duplicate Samples Found.\")\n", + "\n", + "check_duplicates(df)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "# no need we already did it before but i wrote it again :)\n", + "from sklearn.preprocessing import OneHotEncoder #import OneHotEncoder\n", + "onehot_encoder = OneHotEncoder(sparse_output=False) # Instantiate OneHotEncoder\n", + "data_onehot_encoded = onehot_encoder.fit_transform(df) # Apply fit_transform to the copied\n", + "\n", + "print('\\nData after encoding:\\n', data_onehot_encoded) #show after encoding" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "from sklearn.preprocessing import StandardScaler #import StandardScaler\n", + "standard_scaler = StandardScaler() # Instantiate StandardScaler\n", + "data_standard_scaled = standard_scaler.fit_transform(data_onehot_encoded) # Apply fit_transform\n", + "\n", + "print('\\nData after scaling:\\n', data_standard_scaled) #show after scaling" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "def check_target_imbalance(df, target_column):\n", + " print(\"Target Distribution:\")\n", + " print(df[target_column].value_counts(normalize=True))\n", + " sns.countplot(x=df[target_column])\n", + " plt.title(\"Target Distribution\")\n", + " plt.show()\n", + "\n", + "check_target_imbalance(df, \"Delivery_Time\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "from sklearn.model_selection import train_test_split\n", + "# Define features and target\n", + "feature_cols = ['Distance_km', 'Weather', 'Traffic_Level', 'Time_of_Day', 'Vehicle_Type', 'Preparation_Time_min', 'Courier_Experience_yrs' ]\n", + "\n", + "X = df1[feature_cols]\n", + "y = df1['Delivery_Time']\n", + "df\n", + "# Stratified split\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42, stratify=y)\n", + "print(f\"Train: {X_train.shape}, Test: {X_test.shape}\")\n", + "print(f\"delivery time: {y_train.sum()}, in test: {y_test.sum(" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:\n", + "from sklearn.model_selection import KFold\n", + "\n", + "# Use previously generated random data (example: regression data)\n", + "X, y = x.copy(), y.copy()\n", + "\n", + "# Define K-Fold Cross Validation\n", + "kf = KFold(n_splits=5, shuffle=True, random_state=42)\n", + "\n", + "# Iterate through folds\n", + "for fold, (train_idx, test_idx) in enumerate(kf.split(X), start=1):\n", + " # indexing for each fold\n", + " X_train, X_test = X.iloc[train_idx], X.iloc[test_idx]\n", + " y_train, y_test = y.iloc[train_idx], y.iloc[test_idx]\n", + " # print shapes\n", + " print(f\"Fold {fold}\")\n", + " print(\" X_train shape:\", X_train.shape)\n", + " print(\" X_test shape :\", X_test.shape)\n", + " print(\" y_train shape:\", y_train.shape)\n", + " print(\" y_test shape :\", y_test.shape)\n", + " print(\"-\" * 30)\n", + "\n", + "#3:\n", + "# Train Random Forest Regressor\n", + "model = RandomForestRegressor(n_estimators=100, max_depth=20, random_state=42, n_jobs=-1)\n", + "model.fit(X_train_scaled, y_train)\n", + "print(\"Model trained!\")\n", + "\n", + "#4:\n", + "y_pred = model.predict(X_test_scaled)\n", + "\n", + "mae = mean_absolute_error(y_test, y_pred)\n", + "\n", + "print(f\"MAE: ${mae:,.2f}\")\n", + "\n", + "\n", + "kfold = KFold(n_splits=5, shuffle=True, random_state=42)\n", + "\n", + "mae_scores = []\n", + "rmse_scores = []\n", + "\n", + "for train_idx, val_idx in kfold.split(X_train_scaled):\n", + " X_fold_train, X_fold_val = X_train_scaled[train_idx], X_train_scaled[val_idx]\n", + " y_fold_train, y_fold_val = y_train.iloc[train_idx], y_train.iloc[val_idx]\n", + "\n", + " # Train and predict\n", + " model.fit(X_fold_train, y_fold_train)\n", + " y_fold_pred = model.predict(X_fold_val)\n", + "\n", + " # Calculate metrics\n", + " mae_scores.append(mean_absolute_error(y_fold_val, y_fold_pred))\n", + " rmse_scores.append(np.sqrt(mean_squared_error(y_fold_val, y_fold_pred)))\n", + "\n", + "mae_scores = np.array(mae_scores)\n", + "rmse_scores = np.array(rmse_scores)\n", + "\n", + "print(f\"5-Fold CV Results:\")\n", + "print(f\"MAE: ${mae_scores.mean():,.2f}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "# Feature importance\n", + "importance = pd.DataFrame({\n", + " 'feature': feature_cols,\n", + " 'importance': model.feature_importances_\n", + "}).sort_values('importance', ascending=False)\n", + "\n", + "plt.figure(figsize=(10, 6))\n", + "plt.barh(importance['feature'], importance['importance'], color='purple')\n", + "plt.xlabel('Importance')\n", + "plt.title('Feature Importance')\n", + "plt.gca().invert_yaxis()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "\n", + "# from the plot we can select the golden feature" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/392/Q1.ipynb b/submissions_extracted/392/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..985cbefc6e75c24893fb59a1b789e106b68a2da7 --- /dev/null +++ b/submissions_extracted/392/Q1.ipynb @@ -0,0 +1,343 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import numpy as np\n", + "import pandas as pd\n", + "import matplotlib.pyplot as plt\n", + "import os #يقرا الباث\n", + "import kagglehub\n", + "\n", + "from sklearn.model_selection import train_test_split, KFold\n", + "from sklearn.preprocessing import StandardScaler, LabelEncoder\n", + "from sklearn.ensemble import RandomForestRegressor\n", + "from sklearn.metrics import mean_absolute_error, mean_squared_error\n", + "\n", + "import warnings\n", + "warnings.filterwarnings('ignore')" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q1-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "\n", + "data_path = os.path.join(path, 'Q1_data.csv')\n", + "df = pd.read_csv(data_path)\n", + "\n", + "print(f\"Dataset shape: {df.shape}\")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "df.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "df.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "\n", + "plt.figure(figsize=(10, 5))\n", + "plt.hist(df['Delivery_Time'], bins=50, edgecolor='black')\n", + "plt.title('delivery_time Distribution')\n", + "plt.xlabel('delivery_time')\n", + "plt.ylabel('Frequency')\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "df.drop(columns=['Order_ID'])" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "def check_missing_values(df):\n", + " missing_values = df.isnull().sum()\n", + " print(\"Missing Values per Column:\")\n", + " print(missing_values[missing_values > 0])\n", + " if missing_values.any():\n", + " print(\"\\nHandle Missing Values as needed.\")\n", + " else:\n", + " print(\"\\nNo Missing Values Found.\")\n", + "\n", + "check_missing_values(df)\n", + "\n", + "df_clean = df.copy()\n", + "df_clean['Delivery_Time'] = df_clean['Delivery_Time'].fillna(df_clean['Delivery_Time'].mean())\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "check_missing_values(df_clean)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "\n", + "def check_duplicates(df):\n", + " duplicates = df.duplicated().sum()\n", + " print(f\"Number of Duplicate Samples: {duplicates}\")\n", + " if duplicates > 0:\n", + " print(\"Dropping Duplicates...\")\n", + " df.drop_duplicates(inplace=True)\n", + " print(\"Duplicates Dropped.\")\n", + " else:\n", + " print(\"No Duplicate Samples Found.\")\n", + "\n", + "check_duplicates(df)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "df" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "\n", + "categorical_cols = df.select_dtypes(include=[\"object\"]).columns\n", + "print(\"Categorical Columns:\", list(categorical_cols))\n", + "\n", + "\n", + "\n", + "\n", + "label_encoders = {}\n", + "for col in categorical_cols:\n", + " le = LabelEncoder()\n", + " df[col] = le.fit_transform(df[col])\n", + " label_encoders[col] = le\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "df" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "\"\"\"target_column = \"Delivery_Time\"\n", + "X = df.drop(target_column, axis=1) #drop whole col\n", + "y = df[target_column]\n", + "X_scaled = scaler.fit_transform(X) \"\"\"\n", + "features = df.columns.drop(\"Delivery_Time\")\n", + "scaler = StandardScaler()\n", + "df[features] = scaler.fit_transform(df[features])\n", + "\n", + "\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 6: Write your code here:\n", + "#does not need beacuse it is not a classfication task" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "target_column = \"Delivery_Time\"\n", + "feature_cols = ['Order_ID' ,\t'Distance_km' ,\n", + " 'Weather' ,\t'Traffic_Level' ,\t'Time_of_Day' ,\t'Vehicle_Type', 'Preparation_Time_min' ,\t'Courier_Experience_yrs' ]\n", + "X = df[feature_cols]\n", + "y = df[target_column]\n", + "\n", + "\n", + "\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:\n", + "# K-Fold Cross Validation\n", + "kf = KFold(n_splits=5, shuffle=True, random_state=42)\n", + "\n", + "mae_scores = []\n", + "for train_idx, test_idx in kf.split(X):\n", + " X_train, X_test = X[train_idx], X[test_idx]\n", + " y_train, y_test = y.iloc[train_idx], y.iloc[test_idx]\n", + "\n", + " model = RandomForestRegressor(n_estimators=100, max_depth=20, random_state=42, n_jobs=-1)\n", + " model.fit(X_train, y_train)\n", + "\n", + "\n", + " # Predict\n", + " y_pred = model.predict(X_test)\n", + "\n", + " # Evaluation metrics\n", + " mae_scores.append(mean_absolute_error(y_test, y_pred))\n", + "\n", + "print(f\"MAE : {np.mean(mae_scores):.2f}\")\n", + "\n", + "\n", + "print(\"Model trained!\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "importance = pd.DataFrame({\n", + " 'feature': feature_cols,\n", + " 'importance': model.feature_importances_\n", + "}).sort_values('importance', ascending=False)\n", + "\n", + "plt.figure(figsize=(10, 6))\n", + "plt.barh(importance['feature'], importance['importance'], color='purple')\n", + "plt.xlabel('Importance')\n", + "plt.title('Feature Importance')\n", + "plt.gca().invert_yaxis()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/392/Q2.ipynb b/submissions_extracted/392/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..11de36e871c272b18a5ba6f63e4c8a92dfd54f5f --- /dev/null +++ b/submissions_extracted/392/Q2.ipynb @@ -0,0 +1,385 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import torch\n", + "import torch.nn as nn\n", + "from torchvision.datasets import MNIST\n", + "from torch.utils.data import DataLoader\n", + "from torch.optim import Adam\n", + "from torchvision.transforms.functional import to_tensor\n", + "import torch.nn.functional as F\n", + "import matplotlib.pyplot as plt" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q2-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import os\n", + "import pandas as pd\n", + "import numpy as np\n", + "from PIL import Image\n", + "from sklearn.model_selection import train_test_split\n", + "\n", + "# Load Labels\n", + "labels_df = pd.read_csv(os.path.join(path, \"labels.csv\"))\n", + "img_dir = os.path.join(path, \"images\")\n", + "\n", + "images = []\n", + "ages = []\n", + "\n", + "# Load Images and Resize\n", + "print(\"Loading images...\")\n", + "for index, row in labels_df.iterrows():\n", + " img_name = row.iloc[0]\n", + " age = row.iloc[1]\n", + " img_path = os.path.join(img_dir, img_name)\n", + "\n", + " if os.path.exists(img_path):\n", + " img = Image.open(img_path).convert('RGB')\n", + " img_array = np.array(img) / 255.0 # Normalize pixel values to [0, 1]\n", + " images.append(img_array)\n", + " ages.append(age)\n", + "\n", + "X = np.array(images)\n", + "y = np.array(ages)\n", + "\n", + "# Transpose image dimensions to match PyTorch format (N, C, H, W)\n", + "X = np.transpose(X, (0, 3, 1, 2))\n", + "\n", + "# Split Data\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n", + "\n", + "print(f\"X_train shape: {X_train.shape}\")\n", + "print(f\"X_test shape: {X_test.shape}\")\n", + "print(f\"y_train shape: {y_train.shape}\")\n", + "print(f\"y_test shape: {y_test.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 1. Convert Numpy arrays to PyTorch Tensors\n", + "import kagglehub\n", + "import pandas as pd\n", + "import torch\n", + "\n", + "X_train = torch.tensor(X_train, dtype=torch.float32)\n", + "X_test = torch.tensor(X_test, dtype=torch.float32)\n", + "y_train = torch.tensor(y_train, dtype=torch.float32)\n", + "y_test = torch.tensor(y_test, dtype=torch.float32)\n", + "\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 2. Create TensorDataset objects\n", + "train_dataset = TensorDataset(X_train, y_train)\n", + "test_dataset = TensorDataset(X_test, y_test)\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 3. Create DataLoaders\n", + "train_loader = DataLoader(train_dataset, batch_size=32, shuffle=True)\n", + "test_loader = DataLoader(test_dataset, batch_size=32, shuffle=False)\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 4. Print shape of one batch\n", + "\n", + "X_batch, y_batch = next(iter(train_loader))\n", + "print(f\"Training batch input shape: {X_batch.shape}\")\n", + "print(f\"Training batch labels shape: {y_batch.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 5. Display sample images\n", + "# Get one batch of images and labels\n", + "import matplotlib.pyplot as plt\n", + "images, labels = next(iter(train_loader))\n", + "\n", + "# Display the first 6 images in the batch\n", + "plt.figure(figsize=(8, 4))\n", + "\n", + "for i in range(6):\n", + " plt.subplot(2, 3, i + 1)\n", + " plt.imshow(images[i].squeeze(), cmap='gray')\n", + " plt.title(f\"Label: {labels[i].item()}\")\n", + " plt.axis('off')\n", + "\n", + "plt.tight_layout()\n", + "plt.show()\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your model class here:\n", + "class NN4Layer(nn.Module):\n", + "\n", + " def __init__(self, input_dim, hidden_dim, output_dim):\n", + " super(NN4Layer, self).__init__() #موجودة دايما\n", + "\n", + " # First linear layer: input features -> hidden layer\n", + " self.layer1 = nn.Linear(input_dim, hidden_dim) #انبوت حقنا\n", + "\n", + " # Second linear layer: hidden layer -> hidden layer\n", + " self.layer2 = nn.Linear(hidden_dim, hidden_dim)\n", + " self.layer3 = nn.Linear(hidden_dim, hidden_dim)\n", + "\n", + " # Output layer: hidden layer -> number of classes (logits)\n", + " self.layer4 = nn.Linear(hidden_dim, output_dim) #اخر شي اوتبت\n", + "\n", + " # ReLU activation for non-linearity\n", + " self.relu = nn.ReLU()\n", + "\n", + " # Defines how input data flows through the network\n", + " def forward(self, x):\n", + " # First hidden layer\n", + " z1 = self.layer1(x)\n", + " a1 = self.relu(z1)\n", + "\n", + " # Second hidden layer\n", + " z2 = self.layer2(a1)\n", + " a2 = self.relu(z2)\n", + "\n", + " z3 = self.layer2(a2)\n", + " a3 = self.relu(z3)\n", + "\n", + " # Output layer (raw scores / logits)\n", + " output = self.layer3(a3) # there is something missing here, remember? :)\n", + " #ماهنسوي اكتفيشن نسوي سوفت ماكس لما نستعمل لوس فنكشن يعرف انه ملتي كلاس\n", + "\n", + " return output\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your training loop here:\n", + "def train_one_epoch(model, optimizer, criterion, train_loader, device):\n", + " # Set the model to training mode\n", + " model.train()\n", + "\n", + " running_loss = 0.0\n", + "\n", + " for X_batch, y_batch in train_loader:\n", + " # Move batch to the selected device\n", + " X_batch = X_batch.view(X_batch.size(0), -1).to(device)\n", + "\n", + " y_batch = y_batch.to(device)\n", + "\n", + " # Forward pass\n", + " outputs = model(X_batch) # shape: (batch_size, 10)\n", + " loss = criterion(outputs, y_batch)\n", + "#لكل كلاس\n", + " # Backward pass & optimization\n", + " optimizer.zero_grad() # Clear previous gradients\n", + " loss.backward() # Compute gradients\n", + " optimizer.step() # Update model parameters\n", + "\n", + " running_loss += loss.item()\n", + "\n", + " # Average loss over all batches\n", + " avg_loss = running_loss / len(train_loader)\n", + "\n", + " return avg_loss" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your validation loop here:\n", + "def validate(model, criterion, test_loader, device):\n", + " # Set the model to evaluation mode\n", + " model.eval()\n", + "\n", + " running_loss = 0.0\n", + "\n", + "\n", + " with torch.no_grad(): # Disable gradient computation\n", + " for X_batch, y_batch in test_loader: #تست\n", + " # Move batch to the selected device\n", + " X_batch = X_batch.to(device)\n", + " y_batch = y_batch.view(-1, 1).to(device)\n", + "\n", + " # Forward pass\n", + " outputs = model(X_batch)\n", + " loss = criterion(outputs, y_batch)\n", + " running_loss += loss.item()\n", + "\n", + "\n", + " avg_loss = running_loss / len(test_loader)\n", + "\n", + "\n", + " return avg_loss\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Define device, model, loss, optimizer:\n", + "# Device setup\n", + "from torch.optim import AdamW\n", + "device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n", + "\n", + "# Model parameters\n", + "input_dim = X_train.shape[1] #\n", + "hidden_dim = 14 # Design choice\n", + "output_dim = 1\n", + "\n", + "# Instantiate model\n", + "model = NN4Layer(input_dim, hidden_dim, output_dim).to(device)\n", + "\n", + "# Print the model architecture\n", + "print(\"Model Architecture:\\n\")\n", + "print(model)\n", + "\n", + "# Calculate the total number of trainable parameters\n", + "total_params = sum(p.numel() for p in model.parameters() if p.requires_grad)\n", + "print(f\"\\nTotal trainable parameters: {total_params}\")\n", + "\n", + "\n", + "learning_rate = 0.001\n", + "# Define criterion (loss function) - using CrossEntropyLoss as model now outputs logits\n", + "criterion = nn.MSELoss()\n", + "# Define optimizer\n", + "\n", + "optimizer = AdamW(model.parameters(), learning_rate)\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Start training for 20 epochs:\n", + "num_epochs = 20\n", + "train_losses = []\n", + "val_losses = []\n", + "val_accuracies = []\n", + "\n", + "\n", + "print('Starting Training...')\n", + "for epoch in range(num_epochs):\n", + " # Train one epoch\n", + " train_loss = train_one_epoch(model, optimizer, criterion, train_loader, device)\n", + "\n", + " # Validate\n", + " val_loss, val_accuracy = validate(model, criterion, test_loader, device)\n", + "\n", + " train_losses.append(train_loss)\n", + " val_losses.append(val_loss)\n", + " val_accuracies.append(val_accuracy)\n", + "\n", + " if (epoch + 1) % 5 == 0:\n", + " print(f'Epoch [{epoch+1}/{num_epochs}], Train Loss: {train_loss:.4f}, Val Loss: {val_loss:.4f}, Val Accuracy: {val_accuracy:.4f}')\n", + "\n", + "print('Training Complete!')" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "\n", + "# Plotting results\n", + "plt.figure(figsize=(7, 5))\n", + "\n", + "plt.plot(train_losses, label='Train Loss')\n", + "plt.plot(val_losses, label='Validation Loss')\n", + "plt.title('Loss over Epochs')\n", + "plt.xlabel('Epoch')\n", + "plt.ylabel('Loss')\n", + "plt.legend()\n", + "\n", + "plt.tight_layout()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2 (Bonus): Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/392/Q3.ipynb b/submissions_extracted/392/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..51ff313ee5bf0f33eed8d1d8f0ec0b19cef7ec7c --- /dev/null +++ b/submissions_extracted/392/Q3.ipynb @@ -0,0 +1,249 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "\n", + "\n", + "# Download latest version\n", + "\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q3-exam-data\")\n", + "\n", + "\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "import numpy as np\n", + "import pandas as pd\n", + "import matplotlib.pyplot as plt\n", + "import os #يقرا الباث\n", + "\n", + "\n", + "data_path = os.path.join(path, 'Q3_data.csv')\n", + "df = pd.read_csv(data_path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "print(df.shape)\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "df.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "df.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "def check_missing_values(df):\n", + " missing_values = df.isnull().sum()\n", + " print(\"Missing Values per Column:\")\n", + " print(missing_values[missing_values > 0])\n", + " if missing_values.any():\n", + " print(\"\\nHandle Missing Values as needed.\")\n", + " else:\n", + " print(\"\\nNo Missing Values Found.\")\n", + "\n", + "check_missing_values(df)\n", + "\n", + "\n", + "df_clean = df.copy()\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "def check_duplicates(df):\n", + "\n", + " #TODO: get duplicated data using pandas\n", + " duplicates = df.duplicated().sum()\n", + "\n", + " print(f\"Number of Duplicate Samples: {duplicates}\")\n", + " if duplicates > 0:\n", + " print(\"Dropping Duplicates...\")\n", + " df.drop_duplicates(inplace=True)\n", + " print(\"Duplicates Dropped.\")\n", + " else:\n", + " print(\"No Duplicate Samples Found.\")\n", + "\n", + "check_duplicates(df)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "\n", + "categorical_cols = df.select_dtypes(include=[\"object\"]).columns\n", + "print(\"Categorical Columns:\", list(categorical_cols)) #there is no Categorical col" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "from sklearn.preprocessing import StandardScaler, LabelEncoder\n", + "features = df.columns.drop(\"Target\")\n", + "scaler = StandardScaler()\n", + "df[features] = scaler.fit_transform(df[features])\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "target_column = \"Target\"\n", + "X = df.drop(target_column, axis=1) #drop whole col\n", + "y = df[target_column]\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:\n", + "from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score\n", + "from catboost import CatBoostClassifier\n", + "\n", + "from sklearn.model_selection import train_test_split, KFold\n", + "from sklearn.metrics import mean_absolute_error, mean_squared_error\n", + "kf = KFold(n_splits=5, shuffle=True, random_state=42)\n", + "\n", + "accurcy_scores = []\n", + "f1_scores = []\n", + "for train_idx, test_idx in kf.split(X):\n", + " X_train, X_test = X[train_idx], X[test_idx]\n", + " y_train, y_test = y.iloc[train_idx], y.iloc[test_idx]\n", + "\n", + " model = CatBoostClassifier(n_estimators=100, max_depth=20, random_state=42, n_jobs=-1)\n", + " model.fit(X_train, y_train)\n", + " y_pred = model.predict(X_test)\n", + "\n", + "\n", + " accuracy = accuracy_score(y_test, y_pred)\n", + " f1 = f1_score(y_test, y_pred, zero_division=0)\n", + "\n", + "print(f\"accuracy : {np.mean(accurcy_scores):.2f}\")\n", + "print(f\"f1 : {np.mean(f1_scores):.2f}\")\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "importance = pd.DataFrame({\n", + " 'feature': feature_cols,\n", + " 'importance': model.feature_importances_\n", + "}).sort_values('importance', ascending=False)\n", + "\n", + "plt.figure(figsize=(10, 6))\n", + "plt.barh(importance['feature'], importance['importance'], color='purple')\n", + "plt.xlabel('Importance')\n", + "plt.title('Feature Importance')\n", + "plt.gca().invert_yaxis()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/393/Q1.ipynb b/submissions_extracted/393/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..1776d834268cbf05b36ec21e02dafe21421d0308 --- /dev/null +++ b/submissions_extracted/393/Q1.ipynb @@ -0,0 +1,285 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import pandas as pd\n", + "import numpy as np\n", + "import matplotlib.pyplot as plt\n", + "import seaborn as sns\n", + "import kagglehub\n", + "import os\n", + "from tqdm import tqdm\n", + "%matplotlib inline\n", + "import warnings\n", + "warnings.filterwarnings('ignore')\n", + "\n", + "\n", + "from sklearn.preprocessing import LabelEncoder\n", + "from sklearn.linear_model import LogisticRegression\n", + "from sklearn.model_selection import KFold\n", + "\n", + "from lightgbm import LGBMClassifier\n", + "from xgboost import XGBClassifier\n", + "from sklearn.ensemble import RandomForestClassifier\n", + "from sklearn.ensemble import VotingClassifier\n", + "from sklearn.metrics import f1_score\n", + "\n", + "\n", + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q1-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "csv_path = os.path.join(path, \"Q1_data.csv\")\n", + "\n", + "df = pd.read_csv(csv_path)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "df.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "df.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "plt.figure(figsize=(10, 5))\n", + "plt.hist(df['Delivery_Time'].dropna(), bins=50, edgecolor='black')\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "cols = ['Order_ID', 'Distance_km', 'Preparation_Time_min', 'Courier_Experience_yrs', 'Delivery_Time']\n", + "df_clean = df[cols].copy()\n", + "df_clean.drop(columns=['Order_ID'])" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "#df_clean['Traffic_Level'] = df_clean['Traffic_Level'].fillna(df_clean['Traffic_Level'].mode()[0])\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "def check_duplicates(df):\n", + " duplicates = df.duplicated().sum()\n", + " print(f\"Number of Duplicate Samples: {duplicates}\")\n", + " if duplicates > 0:\n", + " print(\"Dropping Duplicates...\")\n", + " df.drop_duplicates(inplace=True)\n", + " print(\"Duplicates Dropped.\")\n", + " else:\n", + " print(\"No Duplicate Samples Found.\")\n", + "\n", + "check_duplicates(df_clean)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "def encode_categorical_columns(df):\n", + " categorical_cols = df.select_dtypes(include=[\"object\"]).columns\n", + " print(\"Categorical Columns:\", list(categorical_cols))\n", + "\n", + "label_encoders = encode_categorical_columns(df_clean)\n", + "\n", + "\n", + "from sklearn.preprocessing import LabelEncoder\n", + "\n", + "categorical_cols = df_clean.select_dtypes(include=[\"object\"]).columns\n", + "for col in categorical_cols:\n", + " print(f\"Encoding column: {col}\")\n", + " le = LabelEncoder()\n", + " df_clean[col] = le.fit_transform(df_clean[col])\n", + "df_clean" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "\n", + "print(\"Before scaling:\")\n", + "df_clean\n", + "\n", + "from sklearn.preprocessing import StandardScaler #import StandardScaler\n", + "\n", + "print('data before scaling:\\n', df_clean) #show before scaling\n", + "standard_scaler = StandardScaler() # Instantiate StandardScaler\n", + "data_standard_scaled = standard_scaler.fit_transform(df_clean) # Apply fit_transform\n", + "print('\\nData after scaling:\\n', data_standard_scaled) #show after scaling" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 6: Write your code here:\n", + "def check_target_imbalance(df, target_column):\n", + " print(\"Target Distribution:\")\n", + " print(df[target_column].value_counts(normalize=True))\n", + " sns.countplot(x=df[target_column])\n", + " plt.title(\"Target Distribution\")\n", + " plt.show()\n", + "\n", + "check_target_imbalance(df_clean, \"Delivery_Time\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "X = df_clean.drop(\"Delivery_Time\",axis=1)\n", + "y = df_clean['Delivery_Time']\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:\n", + "from sklearn.model_selection import KFold\n", + "from sklearn.metrics import mean_squared_error as sklearn_mse, mean_absolute_error, r2_score\n", + "\n", + "model = {\n", + " \"Random Forest Classifier\": RandomForestClassifier(n_estimators=100),\n", + "}\n", + "\n", + "model[\"Ensemble\"] = VotingClassifier(estimators=[('gnb', model[\"Random Forest Classifier\"])], voting=\"soft\")\n", + "\n", + "for model_name, model in model.items():\n", + " mae = []\n", + "\n", + "\n", + " # Stratified 5-Fold Cross-Validation\n", + " skf = KFold(n_splits=5)\n", + " for train_index, test_index in skf.split(X, y):\n", + " # Split data into training and testing sets\n", + " X_Train, X_Test = X.loc[train_index, :], X.loc[test_index, :]\n", + " y_Train, y_Test = y.iloc[train_index], y.iloc[test_index]\n", + " # Train the model\n", + " model.fit(X_Train, y_Train)\n", + " # Predict on the test set\n", + " y_pred = model.predict(X_Test)\n", + " # Calculate metrics\n", + " z = df_clean.mean_absolute_error()\n", + " mae.append(df_clean.mean_absolute_error(y_Test, y_pred))\n", + "\n", + " # Print the results\n", + "print(f\"{model_name} MAE: {np.mean(mae):.4f}\")\n", + "print(\"\\n\")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/393/Q2.ipynb b/submissions_extracted/393/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..c8937ff34d658b6340ef5c82e1d71e84083e0ea8 --- /dev/null +++ b/submissions_extracted/393/Q2.ipynb @@ -0,0 +1,192 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q2-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import os\n", + "import pandas as pd\n", + "import numpy as np\n", + "from PIL import Image\n", + "from sklearn.model_selection import train_test_split\n", + "\n", + "# Load Labels\n", + "labels_df = pd.read_csv(os.path.join(path, \"labels.csv\"))\n", + "img_dir = os.path.join(path, \"images\")\n", + "\n", + "images = []\n", + "ages = []\n", + "\n", + "# Load Images and Resize\n", + "print(\"Loading images...\")\n", + "for index, row in labels_df.iterrows():\n", + " img_name = row.iloc[0]\n", + " age = row.iloc[1]\n", + " img_path = os.path.join(img_dir, img_name)\n", + "\n", + " if os.path.exists(img_path):\n", + " img = Image.open(img_path).convert('RGB')\n", + " img_array = np.array(img) / 255.0 # Normalize pixel values to [0, 1]\n", + " images.append(img_array)\n", + " ages.append(age)\n", + "\n", + "X = np.array(images)\n", + "y = np.array(ages)\n", + "\n", + "# Transpose image dimensions to match PyTorch format (N, C, H, W)\n", + "X = np.transpose(X, (0, 3, 1, 2))\n", + "\n", + "# Split Data\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n", + "\n", + "print(f\"X_train shape: {X_train.shape}\")\n", + "print(f\"X_test shape: {X_test.shape}\")\n", + "print(f\"y_train shape: {y_train.shape}\")\n", + "print(f\"y_test shape: {y_test.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 1. Convert Numpy arrays to PyTorch Tensors\n", + "\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 2. Create TensorDataset objects\n", + "\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 3. Create DataLoaders\n", + "\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 4. Print shape of one batch\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 5. Display sample images\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your model class here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your training loop here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your validation loop here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Define device, model, loss, optimizer:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Start training for 20 epochs:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2 (Bonus): Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/393/Q3.ipynb b/submissions_extracted/393/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..16561e9c32f3969a49ce220e16c1de10224a14e3 --- /dev/null +++ b/submissions_extracted/393/Q3.ipynb @@ -0,0 +1,283 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import pandas as pd\n", + "import numpy as np\n", + "import matplotlib.pyplot as plt\n", + "import seaborn as sns\n", + "import kagglehub\n", + "import os\n", + "from tqdm import tqdm\n", + "%matplotlib inline\n", + "import warnings\n", + "warnings.filterwarnings('ignore')\n", + "\n", + "\n", + "from sklearn.preprocessing import LabelEncoder\n", + "from sklearn.linear_model import LogisticRegression\n", + "from sklearn.model_selection import KFold\n", + "\n", + "from lightgbm import LGBMClassifier\n", + "from xgboost import XGBClassifier\n", + "from sklearn.ensemble import RandomForestClassifier\n", + "from sklearn.ensemble import VotingClassifier\n", + "from sklearn.metrics import f1_score\n", + "\n", + "\n", + "import kagglehub\n", + "\n", + "\n", + "\n", + "# Download latest version\n", + "\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q3-exam-data\")\n", + "\n", + "\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "csv_path = os.path.join(path, \"Q3_data.csv\")\n", + "\n", + "df = pd.read_csv(csv_path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "df.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "df.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "def check_duplicates(df):\n", + " duplicates = df.duplicated().sum()\n", + " print(f\"Number of Duplicate Samples: {duplicates}\")\n", + " if duplicates > 0:\n", + " print(\"Dropping Duplicates...\")\n", + " df.drop_duplicates(inplace=True)\n", + " print(\"Duplicates Dropped.\")\n", + " else:\n", + " print(\"No Duplicate Samples Found.\")\n", + "\n", + "check_duplicates(df)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "def encode_categorical_columns(df):\n", + " categorical_cols = df.select_dtypes(include=[\"object\"]).columns\n", + " print(\"Categorical Columns:\", list(categorical_cols))\n", + "\n", + "label_encoders = encode_categorical_columns(df)\n", + "\n", + "\n", + "from sklearn.preprocessing import LabelEncoder\n", + "\n", + "categorical_cols = df.select_dtypes(include=[\"object\"]).columns\n", + "for col in categorical_cols:\n", + " print(f\"Encoding column: {col}\")\n", + " le = LabelEncoder()\n", + " df[col] = le.fit_transform(df[col])\n", + "df" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "print(\"Before scaling:\")\n", + "df\n", + "\n", + "from sklearn.preprocessing import StandardScaler #import StandardScaler\n", + "\n", + "print('data before scaling:\\n', df) #show before scaling\n", + "standard_scaler = StandardScaler() # Instantiate StandardScaler\n", + "data_standard_scaled = standard_scaler.fit_transform(df) # Apply fit_transform\n", + "print('\\nData after scaling:\\n', data_standard_scaled) #show after scaling" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "def check_target_imbalance(df, target_column):\n", + " print(\"Target Distribution:\")\n", + " print(df[target_column].value_counts(normalize=True))\n", + " sns.countplot(x=df[target_column])\n", + " plt.title(\"Target Distribution\")\n", + " plt.show()\n", + "\n", + "check_target_imbalance(df, \"Target\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "X = df.drop(\"Target\",axis=1)\n", + "y = df['Target']" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:\n", + "from sklearn.model_selection import KFold\n", + "from sklearn.metrics import mean_squared_error as sklearn_mse, r2_score, accuracy_score, f1_score\n", + "\n", + "def gradient_descent(X, y, learning_rate, n_iters=500):\n", + " m, n = X.shape # m rows, n columns (dimensions)\n", + " theta = np.zeros(n) # initialize a zeros weight vector with n dimensions\n", + " losses = []\n", + "\n", + "def mean_absolute_error(y, y_hat):\n", + " return (1 / (2 * len(y))) * np.sum(abs((y_hat - y)))\n", + "\n", + " for _ in tqdm(range(n_iters), desc=\"Training Linear Regression\"):\n", + " y_hat = np.dot(X, theta)\n", + " gradient = np.dot(X.T, (y_hat - y)) / m\n", + " theta -= learning_rate * gradient\n", + "\n", + " loss = mean_absolute_error(y, y_hat)\n", + " losses.append(loss)\n", + " return theta, losses\n", + "\n", + "n_splits = 5 # K=5 Folds\n", + "\n", + "# 5-Fold Cross-Validation, shuffled\n", + "kf = KFold(n_splits=n_splits, shuffle=True, random_state=42)\n", + "\n", + "\n", + "accuracy_scores = []\n", + "f1_scores = []\n", + "\n", + "for fold_idx, (train_index, test_index) in enumerate(kf.split(X)):\n", + " print(f\"\\nFold {fold_idx + 1}/{n_splits}\")\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", + " # Train\n", + " theta, losses = gradient_descent(X_train.values, y_train.values, learning_rate=0.1, n_iters=500)\n", + "\n", + " # Validate\n", + " y_pred = np.dot(X_test.values, theta)\n", + "\n", + " # Calculate evaluation metrics\n", + " f1 = f1_score(y_test, y_pred)\n", + " accuracy = accuracy_score(y_test, y_pred)\n", + "\n", + "\n", + " # Store results\n", + " accuracy_scores.append(accuracy)\n", + " f1_scores.append(f1)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/394/Q1.ipynb b/submissions_extracted/394/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..cf2a153fd63bf0eb508a866cd9c086b4289385cd --- /dev/null +++ b/submissions_extracted/394/Q1.ipynb @@ -0,0 +1,342 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import numpy as np\n", + "import pandas as pd\n", + "import matplotlib.pyplot as plt\n", + "import os\n", + "import kagglehub\n", + "\n", + "import seaborn as sns\n", + "\n", + "from tqdm import tqdm\n", + "\n", + "from sklearn.model_selection import train_test_split, KFold\n", + "from sklearn.preprocessing import StandardScaler, LabelEncoder\n", + "from sklearn.ensemble import RandomForestRegressor\n", + "from sklearn.metrics import mean_absolute_error, mean_squared_error\n", + "\n", + "import warnings\n", + "warnings.filterwarnings('ignore')\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q1-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "delivery_path = os.path.join(path, 'Q1_data.csv')\n", + "df_delivery = pd.read_csv(delivery_path)\n", + "\n", + "print(f\"Dataset shape: {df_delivery.shape}\")\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "df_delivery.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "df_delivery.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "df_delivery.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "plt.figure(figsize=(10, 5))\n", + "plt.hist(df_delivery['Delivery_Time'].dropna(), bins=50, edgecolor='black')\n", + "plt.title('Delivery Time Distribution')\n", + "plt.xlabel('Delivery Time')\n", + "plt.ylabel('Frequency')\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "cols = ['Order_ID',\t'Distance_km',\t'Weather',\t'Traffic_Level',\t'Time_of_Day',\t'Vehicle_Type',\t'Preparation_Time_min',\t'Courier_Experience_yrs',\t'Delivery_Time']\n", + "df_clean = df_delivery[cols].copy()\n", + "\n", + "print(f\"Before: {df_clean.shape}\")\n", + "df_clean = df_clean.drop(columns='Delivery_Time')\n", + "print(f\"After dropping Delivery_Time: {df_clean.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "def check_missing_values(df):\n", + " missing_values = df.isnull().sum()\n", + " print(\"Missing Values per Column:\")\n", + " print(missing_values[missing_values > 0])\n", + " if missing_values.any():\n", + " print(\"\\nHandling Missing Values as needed.\")\n", + " else:\n", + " print(\"\\nNo Missing Values Found.\")\n", + "\n", + "check_missing_values(df_delivery)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "#task 2\n", + "for col in ['Weather', 'Traffic_Level', 'Time_of_Day', 'Courier_Experience_yrs']:\n", + " df_clean[col] = df_clean[col].fillna('unknown')\n", + "print(\"Missing values remaining:\", df_clean.isnull().sum().sum())" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "def check_duplicates(df):\n", + " duplicates = df.duplicated().sum()\n", + " print(f\"Number of Duplicate Samples: {duplicates}\")\n", + " if duplicates > 0:\n", + " print(\"Dropping Duplicates...\")\n", + " df.drop_duplicates(inplace=True)\n", + " print(\"Duplicates Dropped.\")\n", + " else:\n", + " print(\"No Duplicate Samples Found.\")\n", + "\n", + "check_duplicates(df_delivery)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "categorical_cols = ['Weather','Traffic_Level'\t,'Time_of_Day'\t,'Vehicle_Type', ]\n", + "for col in categorical_cols:\n", + " le = LabelEncoder()\n", + " df_clean[col] = le.fit_transform(df_clean[col].astype(str))\n", + "\n", + "df_clean.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "data_for_scale = pd.DataFrame(df_clean)\n", + "print('data before scaling:\\n', data_for_scale)\n", + "standard_scaler = StandardScaler() # Instantiate StandardScaler\n", + "data_standard_scaled = standard_scaler.fit_transform(data_for_scale) # Apply fit_transform\n", + "\n", + "print('\\nData after scaling:\\n', data_standard_scaled)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 6: Write your code here:\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "\n", + "# Task 1: Write your code here:\n", + "# Define features and target\n", + "feature_cols = ['Order_ID',\t'Distance_km',\t'Weather',\t'Traffic_Level',\t'Time_of_Day',\t'Vehicle_Type',\t'Preparation_Time_min',\t'Courier_Experience_yrs']\n", + "X = df_clean[feature_cols]\n", + "y = df_clean['Delivery_Time']\n", + "\n", + "# TODO: Split data with stratification (test_size=0.2, random_state=42)\n", + "from sklearn.model_selection import train_test_split\n", + "\n", + "X_train, X_test, y_train, y_test = train_test_split(\n", + " X, y, test_size=0.2, random_state=42, stratify=y\n", + ")\n", + "\n", + "print(f\"Train: {X_train.shape}, Test: {X_test.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "n_splits = 5 # K=5 Folds\n", + "\n", + "# 5-Fold Cross-Validation, shuffled\n", + "kf = KFold(n_splits=n_splits, shuffle=True, random_state=42)\n", + "lr_losses = []\n", + "lr_mse = []\n", + "lr_rmse =[]\n", + "lr_r2 = []\n", + "\n", + "for fold_idx, (train_index, test_index) in enumerate(kf.split(X)):\n", + " print(f\"\\nFold {fold_idx + 1}/{n_splits}\") #+1 because indexing starts at 0, but humans start at 1\n", + "\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", + " # Train\n", + " theta, losses = gradient_descent(X_train.values, y_train.values, learning_rate=0.1, n_iters=500)\n", + " #theta → trained weights for this fold\n", + "\t#losses → loss curve during training\n", + "\n", + "\n", + " # Validate\n", + " y_pred = np.dot(X_test.values, theta) # Applies the learned model to unseen test data ŷ = X dot heta\n", + "\n", + " # Calculate evaluation metrics\n", + " mse = sklearn_mse(y_test, y_pred)\n", + "\n", + " rmse = np.sqrt(mse)\n", + "\n", + " r2 = r2_score(y_test, y_pred)\n", + "\n", + " lr_losses.append(losses)\n", + " lr_mse.append(mse)\n", + " lr_rmse.append(rmse)\n", + " lr_r2.append(r2)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Train Random Forest Regressor\n", + "model = RandomForestRegressor(n_estimators=100, max_depth=20, random_state=42, n_jobs=-1) #use all\n", + "model.fit(X_train_scaled, y_train)\n", + "print(\"Model trained!\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "\n", + "feature_importance = pd.DataFrame({\n", + " 'feature': feature_cols,\n", + " 'importance': model.feature_importances_\n", + "}).sort_values('importance', ascending=False)\n", + "\n", + "plt.figure(figsize=(10, 6))\n", + "plt.barh(feature_importance['feature'], feature_importance['importance'])\n", + "plt.xlabel('Importance')\n", + "plt.title('Feature Importance')\n", + "plt.gca().invert_yaxis()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "plt.figure(figsize=(10, 5))\n", + "plt.hist(df_clean['Delivery_Time'].dropna(), bins=50, edgecolor='black')\n", + "plt.title('Delivery Time Distribution')\n", + "plt.xlabel('Delivery Time')\n", + "plt.ylabel('Frequency')\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/394/Q2.ipynb b/submissions_extracted/394/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..b311ec4553eca9994a2175a2ade666a875ba4a30 --- /dev/null +++ b/submissions_extracted/394/Q2.ipynb @@ -0,0 +1,418 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q2-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import os\n", + "import pandas as pd\n", + "import numpy as np\n", + "from PIL import Image\n", + "from sklearn.model_selection import train_test_split\n", + "\n", + "# Load Labels\n", + "labels_df = pd.read_csv(os.path.join(path, \"labels.csv\"))\n", + "img_dir = os.path.join(path, \"images\")\n", + "\n", + "images = []\n", + "ages = []\n", + "\n", + "# Load Images and Resize\n", + "print(\"Loading images...\")\n", + "for index, row in labels_df.iterrows():\n", + " img_name = row.iloc[0]\n", + " age = row.iloc[1]\n", + " img_path = os.path.join(img_dir, img_name)\n", + "\n", + " if os.path.exists(img_path):\n", + " img = Image.open(img_path).convert('RGB')\n", + " img_array = np.array(img) / 255.0 # Normalize pixel values to [0, 1]\n", + " images.append(img_array)\n", + " ages.append(age)\n", + "\n", + "X = np.array(images)\n", + "y = np.array(ages)\n", + "\n", + "# Transpose image dimensions to match PyTorch format (N, C, H, W)\n", + "X = np.transpose(X, (0, 3, 1, 2))\n", + "\n", + "# Split Data\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n", + "\n", + "print(f\"X_train shape: {X_train.shape}\")\n", + "print(f\"X_test shape: {X_test.shape}\")\n", + "print(f\"y_train shape: {y_train.shape}\")\n", + "print(f\"y_test shape: {y_test.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 1. Convert Numpy arrays to PyTorch Tensors\n", + "import torch\n", + "x1 = torch.tensor(X_train)\n", + "x2 = torch.tensor(X_test)\n", + "y1= torch.tensor(y_train)\n", + "y2 = torch.tensor( y_test)\n", + "\n", + "y = torch.randn(3)\n", + "print(\"x:\", x1, x2)\n", + "print(\"y:\", y1, y2)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import torch\n", + "import torch.nn as nn\n", + "from torchvision.datasets import MNIST\n", + "from torch.utils.data import DataLoader\n", + "from torch.optim import Adam\n", + "from torchvision.transforms.functional import to_tensor\n", + "import torch.nn.functional as F\n", + "import matplotlib.pyplot as plt" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 2. Create TensorDataset objects\n", + "from torchvision.datasets import MNIST\n", + "# Training dataset\n", + "train_dataset = MNIST(\n", + " root='./datasets',\n", + " train=True,\n", + "\n", + " download=True\n", + ")\n", + "\n", + "# Testing dataset\n", + "test_dataset = MNIST(\n", + " root='./datasets', #\n", + " train=False, # Use test data\n", + "\n", + " download=True\n", + ")\n", + "\n", + "sample_image, sample_label = train_dataset[0]\n", + "\n", + "\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 3. Create DataLoaders\n", + "\n", + "from torch.utils.data import DataLoader\n", + "\n", + "# DataLoader for training data\n", + "train_loader = DataLoader(\n", + " train_dataset,\n", + " batch_size=32,\n", + " shuffle=True,\n", + " num_workers=2\n", + ")\n", + "# DataLoader for test/validation data\n", + "test_loader = DataLoader(\n", + " test_dataset,\n", + " batch_size=32,\n", + " shuffle=False,\n", + " num_workers=2\n", + ")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 4. Print shape of one batch\n", + "X_batch, y_batch = next(iter(train_loader))\n", + "print(f\"Training batch input shape: {X_batch.shape}\")\n", + "\n", + "print(f\"Training batch labels shape: {y_batch.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 5. Display sample images\n", + "\n", + "image, label = next(iter(train_loader))\n", + "\n", + "# Display the first 6 images in the batch\n", + "plt.figure(figsize=(8, 4))\n", + "\n", + "for i in range(6):\n", + " plt.subplot(2, 3, i + 1) #. 2 rows\t3 columns. i + 1 → position (matplotlib indexing starts at 1)\n", + " plt.imshow(image[i].squeeze(), cmap='gray') #Display the image correctly. squeeze() removes the channel dimension, MNIST images are grayscale\n", + " plt.title(f\"Label: {label[i].item()}\") #labels[i] is a tensor (e.g. tensor(7)), .item() converts it to a Python integer\n", + " plt.axis('off')\n", + "\n", + "plt.tight_layout() #prevents overlapping\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your model class here:\n", + "class NN4Layer(nn.Module):\n", + "\n", + " def __init__(self, input_dim, hidden_dim, hidden_dimm, output_dim):\n", + " super(NN4Layer, self).__init__()\n", + "\n", + " # First linear layer: input features -> hidden layer\n", + " self.layer1 = nn.Linear(input_dim, hidden_dim)\n", + "\n", + " # Second linear layer: hidden layer -> hidden layer\n", + " self.layer2 = nn.Linear(hidden_dim, hidden_dim)\n", + "\n", + " self.layer3 = nn.Linear(hidden_dim, hidden_dim)\n", + "\n", + " # Output layer: hidden layer -> number of classes (logits)\n", + " self.layer4 = nn.Linear(hidden_dim, output_dim)\n", + "\n", + " # ReLU activation for non-linearity\n", + " self.relu = nn.ReLU()\n", + "\n", + " # Defines how input data flows through the network\n", + " def forward(self, x):\n", + " # First hidden layer\n", + " z1 = self.layer1(x)\n", + " a1 = self.relu(z1)\n", + "\n", + " # Second hidden layer\n", + " z2 = self.layer2(a1)\n", + " a2 = self.relu(z2)\n", + "\n", + " z3 = self.layer3(a2)\n", + " a3 = self.relu(z3)\n", + "\n", + "\n", + "\n", + " # Output layer (raw scores / logits)\n", + " output = self.layer4(a3) # there is something missing here, remember? :)\n", + "\n", + " return output\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your training loop here:\n", + "def train_one_epoch(model, optimizer, criterion, train_loader, device):\n", + " # Set the model to training mode\n", + " model.train()\n", + "\n", + " running_loss = 0.0\n", + "\n", + " for X_batch, y_batch in train_loader:\n", + " # Move batch to the selected device\n", + " X_batch = X_batch.view(X_batch.size(0), -1).to(device)\n", + " y_batch = y_batch.to(device)\n", + "\n", + " # Forward pass\n", + " outputs = model(X_batch) # shape: (batch_size, 10)\n", + " loss = criterion(outputs, y_batch)\n", + "\n", + " # Backward pass & optimization\n", + " optimizer.zero_grad() # Clear previous gradients\n", + " loss.backward() # Compute gradients\n", + " optimizer.step() # Update model parameters\n", + "\n", + " running_loss += loss.item()\n", + "\n", + " # Average loss over all batches\n", + " avg_loss = running_loss / len(train_loader)\n", + "\n", + " return avg_loss" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your validation loop here:\n", + "def validate(model, criterion, test_loader, device):\n", + " # Set the model to evaluation mode\n", + " model.eval()\n", + "\n", + " running_loss = 0.0\n", + " correct = 0\n", + " total = 0\n", + "\n", + " with torch.no_grad():\n", + " for X_batch, y_batch in test_loader:\n", + " # Move data to device\n", + " X_batch = X_batch.view(X_batch.size(0), -1).to(device)\n", + " y_batch = y_batch.to(device)\n", + "\n", + " # Forward pass\n", + " outputs = model(X_batch) # shape: (batch_size, 10)\n", + " loss = criterion(outputs, y_batch)\n", + " running_loss += loss.item()\n", + "\n", + " # Apply Softmax to get probabilities\n", + " probabilities = F.softmax(outputs, dim=1)\n", + "\n", + " # Multiclass predictions\n", + " predicted = torch.argmax(probabilities, dim=1)\n", + "\n", + " # Accuracy calculation\n", + " correct += (predicted == y_batch).sum().item()\n", + " total += y_batch.size(0)\n", + "\n", + " avg_loss = running_loss / len(test_loader)\n", + " accuracy = correct / total\n", + "\n", + " return avg_loss, accuracy" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Define device, model, loss, optimizer:\n", + "# Device setup\n", + "device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n", + "\n", + "# Model parameters\n", + "input_dim = 28 * 28 # MNIST images flattened\n", + "hidden_dim = 14\n", + "hidden_dimm = 14 # Design choice\n", + "output_dim = 10 # Digits 0–9\n", + "\n", + "# Instantiate model\n", + "model = NN4Layer(input_dim, hidden_dim, hidden_dimm, output_dim).to(device)\n", + "\n", + "# Print the model architecture\n", + "print(\"Model Architecture:\\n\")\n", + "print(model)\n", + "\n", + "# Calculate the total number of trainable parameters\n", + "total_params = sum(p.numel() for p in model.parameters() if p.requires_grad)\n", + "print(f\"\\nTotal trainable parameters: {total_params}\")\n", + "num_epochs = 20\n", + "learning_rate = 0.001\n", + "\n", + "# Define criterion (loss function) - using CrossEntropyLoss as model now outputs logits\n", + "criterion = nn.CrossEntropyLoss()\n", + "# Define optimizer\n", + "optimizer = Adam(model.parameters(), learning_rate)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Start training for 20 epochs:\n", + "train_losses = []\n", + "val_losses = []\n", + "val_accuracies = []\n", + "\n", + "print('Starting Training...')\n", + "for epoch in range(num_epochs):\n", + "\n", + " train_loss = train_one_epoch(model, optimizer, criterion, train_loader, device)\n", + "\n", + "\n", + " val_loss, val_accuracy = validate(model, criterion, test_loader, device)\n", + "\n", + " train_losses.append(train_loss)\n", + " val_losses.append(val_loss)\n", + " val_accuracies.append(val_accuracy)\n", + "\n", + " print(f'Epoch [{epoch+1}/{num_epochs}], Train Loss: {train_loss:.4f}, Val Loss: {val_loss:.4f}, Val Accuracy: {val_accuracy:.4f}')\n", + "\n", + "print('Training Complete!')" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "plt.figure(figsize=(7, 5))\n", + "\n", + "plt.plot(train_losses, label='Train Loss')\n", + "plt.plot(val_losses, label='Validation Loss')\n", + "plt.title('Loss over Epochs')\n", + "plt.xlabel('Epoch')\n", + "plt.ylabel('Loss')\n", + "plt.legend()\n", + "\n", + "plt.tight_layout()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2 (Bonus): Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/394/Q3.ipynb b/submissions_extracted/394/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..b4af4aaf81da58ffd6519069607eae1451296af0 --- /dev/null +++ b/submissions_extracted/394/Q3.ipynb @@ -0,0 +1,183 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "import pandas as pd\n", + "import torch\n", + "import torch.nn as nn\n", + "from torch.optim import AdamW\n", + "import matplotlib.pyplot as plt\n", + "import torch.nn.functional as F\n", + "from torch.utils.data import DataLoader, TensorDataset\n", + "from sklearn.model_selection import train_test_split\n", + "from sklearn.preprocessing import StandardScaler, LabelEncoder" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "\n", + "\n", + "# Download latest version\n", + "\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q3-exam-data\")\n", + "\n", + "\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "x_path = os.path.join(path, 'Q3_data.csv')\n", + "df_x = pd.read_csv(x_path)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "df_x.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "df_x.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "df_x.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/395/Q1.ipynb b/submissions_extracted/395/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..f202050369e76b3918f4444ed0db860cc2b4cdd5 --- /dev/null +++ b/submissions_extracted/395/Q1.ipynb @@ -0,0 +1,317 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q1-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import numpy as np\n", + "import pandas as pd\n", + "import matplotlib.pyplot as plt\n", + "import seaborn as sns\n", + "from scipy import stats\n", + "from tqdm import tqdm\n", + "\n", + "\n", + "from sklearn.preprocessing import LabelEncoder\n", + "from sklearn.preprocessing import OneHotEncoder\n", + "from sklearn.linear_model import LogisticRegression\n", + "from sklearn.model_selection import KFold\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "df = pd.read_csv(\"/kaggle/input/q1-exam-data/Q1_data.csv\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "df.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "df.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "df.isnull().sum()\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "df = df.drop(columns=['Order_ID'])\n", + "df.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "df['Weather'] = df['Weather'].fillna(df['Weather'].mode()[0])\n", + "df['Traffic_Level'] = df['Traffic_Level'].fillna(df['Traffic_Level'].mode()[0])\n", + "df['Time_of_Day'] = df['Time_of_Day'].fillna(df['Time_of_Day'].mode()[0])\n", + "\n", + "df['Courier_Experience_yrs'] = df['Courier_Experience_yrs'].fillna(df['Courier_Experience_yrs'].mean())\n", + "df['Delivery_Time'] = df['Delivery_Time'].fillna(df['Delivery_Time'].mean())\n", + "df.isnull().sum()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "duplicates = df.duplicated().sum()\n", + "print(f\"Duplicates: {duplicates}\")\n", + "df = df.drop_duplicates()\n", + "duplicates = df.duplicated().sum()\n", + "print(f\"Duplicates: {duplicates}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "catgorail = ['Weather', 'Traffic_Level', 'Time_of_Day','Vehicle_Type']\n", + "for col in catgorail:\n", + " le = LabelEncoder()\n", + " df[col] = le.fit_transform(df[col]).astype(float)\n", + "df['Preparation_Time_min'] = df['Preparation_Time_min'].astype(float)\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 6: Write your code here:\n", + "\n", + "def check_target_imbalance(df, target_column):\n", + " print(\"Target Distribution:\")\n", + " print(df[target_column].value_counts(normalize=True))\n", + " sns.countplot(x=df[target_column])\n", + " plt.title(\"Target Distribution\")\n", + " plt.show()\n", + "\n", + "check_target_imbalance(df, \"Delivery_Time\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "X = df.drop(\"Delivery_Time\",axis=1).astype(float)\n", + "\n", + "y = df['Delivery_Time'].astype(float)\n", + "df.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "from sklearn.model_selection import KFold\n", + "from sklearn.model_selection import StratifiedKFold\n", + "from sklearn.metrics import mean_squared_error as sklearn_mse, mean_absolute_error, r2_score\n", + "\n", + "from sklearn.ensemble import RandomForestRegressor" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:\n", + "models = {\n", + " \"Random Forest Regressor\": RandomForestRegressor(n_estimators=200)\n", + "\n", + "}" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "all_results = {}\n", + "\n", + "for name in models:\n", + " all_results[name] = {'mse': [], 'rmse': [], 'r2': []}" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "#we need to use stratifaied\n", + "()\n", + "kf = KFold(n_splits=5, shuffle=True, random_state=42)\n", + "\n", + "for fold_idx, (train_index, test_index) in enumerate(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", + " for model_name, model in models.items():\n", + " print(f\"Training {model_name}...\")\n", + "\n", + " # Train\n", + " model.fit(X_train, y_train)\n", + "\n", + " # Predict\n", + " y_pred = model.predict(X_test)\n", + "\n", + " # Calculate metrics\n", + " mse = sklearn_mse(y_test, y_pred)\n", + " rmse = np.sqrt(mse)\n", + " r2 = r2_score(y_test, y_pred)\n", + "\n", + " # Store results\n", + " all_results[model_name][\"mse\"].append(mse)\n", + " all_results[model_name][\"rmse\"].append(rmse)\n", + " all_results[model_name][\"r2\"].append(r2)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "for model_name in all_results:\n", + " print(f\"\\n{model_name}:\")\n", + " print(f\" MSE: {np.mean(all_results[model_name]['mse']):.4f}\")\n", + " print(f\" RMSE: {np.mean(all_results[model_name]['rmse']):.4f}\")\n", + " print(f\" R2: {np.mean(all_results[model_name]['r2']):.4f}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/395/Q2.ipynb b/submissions_extracted/395/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..919b01ac9ca96258931098ae0ef707cfefcdf877 --- /dev/null +++ b/submissions_extracted/395/Q2.ipynb @@ -0,0 +1,422 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q2-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import os\n", + "import pandas as pd\n", + "import numpy as np\n", + "from PIL import Image\n", + "from sklearn.model_selection import train_test_split\n", + "\n", + "# Load Labels\n", + "labels_df = pd.read_csv(os.path.join(path, \"labels.csv\"))\n", + "img_dir = os.path.join(path, \"images\")\n", + "\n", + "images = []\n", + "ages = []\n", + "\n", + "# Load Images and Resize\n", + "print(\"Loading images...\")\n", + "for index, row in labels_df.iterrows():\n", + " img_name = row.iloc[0]\n", + " age = row.iloc[1]\n", + " img_path = os.path.join(img_dir, img_name)\n", + "\n", + " if os.path.exists(img_path):\n", + " img = Image.open(img_path).convert('RGB')\n", + " img_array = np.array(img) / 255.0 # Normalize pixel values to [0, 1]\n", + " images.append(img_array)\n", + " ages.append(age)\n", + "\n", + "X = np.array(images)\n", + "y = np.array(ages)\n", + "\n", + "# Transpose image dimensions to match PyTorch format (N, C, H, W)\n", + "X = np.transpose(X, (0, 3, 1, 2))\n", + "\n", + "# Split Data\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n", + "\n", + "print(f\"X_train shape: {X_train.shape}\")\n", + "print(f\"X_test shape: {X_test.shape}\")\n", + "print(f\"y_train shape: {y_train.shape}\")\n", + "print(f\"y_test shape: {y_test.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import torch\n", + "import torch.nn as nn\n", + "from torchvision.datasets import MNIST\n", + "from torch.utils.data import DataLoader\n", + "from torch.optim import Adam\n", + "from torchvision.transforms.functional import to_tensor\n", + "import torch.nn.functional as F\n", + "import matplotlib.pyplot as plt\n", + "\n", + "import kagglehub\n", + "import pandas as pd\n", + "import numpy as np\n", + "import torch\n", + "import torch.nn as nn\n", + "from torch.optim import AdamW\n", + "import matplotlib.pyplot as plt\n", + "from torch.utils.data import DataLoader, TensorDataset\n", + "from sklearn.model_selection import train_test_split\n", + "from sklearn.preprocessing import StandardScaler, LabelEncoder\n", + "from sklearn.metrics import mean_absolute_error, mean_squared_error, r2_score\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 1. Convert Numpy arrays to PyTorch Tensors\n", + "X_train = torch.tensor(X_train, dtype=torch.float32)\n", + "X_test = torch.tensor(X_test, dtype=torch.float32)\n", + "y_train = torch.tensor(y_train, dtype=torch.float32)\n", + "y_test = torch.tensor(y_test, dtype=torch.float32)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 2. Create TensorDataset objects\n", + "train_dataset = TensorDataset(X_train, y_train)\n", + "test_dataset = TensorDataset(X_test, y_test)\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 3. Create DataLoaders\n", + "train_loader = DataLoader(train_dataset, batch_size=32, shuffle=True)\n", + "test_loader = DataLoader(test_dataset, batch_size=32, shuffle=False)\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 4. Print shape of one batch\n", + "# Print dataset sizes\n", + "print(\"Train dataset:\", len(train_dataset))\n", + "print(\"Test dataset:\", len(test_dataset))\n", + "\n", + "# Get the first batch from the training DataLoader\n", + "X_batch, y_batch = next(iter(train_loader))\n", + "print(f\"Training batch input shape: {X_batch.shape}\")\n", + "print(f\"Training batch labels shape: {y_batch.shape}\")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 5. Display sample images\n", + "# Get one batch of images and labels\n", + "images, labels = next(iter(train_loader))\n", + "\n", + "# Display the first 6 images in the batch\n", + "plt.figure(figsize=(8, 4))\n", + "\n", + "for i in range(6):\n", + " plt.subplot(2, 3, i + 1)\n", + "\n", + " # Convert from (C, H, W) to (H, W, C) for matplotlib\n", + " img = images[i].permute(1, 2, 0)\n", + "\n", + " plt.imshow(img)\n", + " plt.title(f\"Label: {labels[i].item()}\")\n", + " plt.axis('off')\n", + "\n", + "plt.tight_layout()\n", + "plt.show()\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your model class here:\n", + "class NN4Layer(nn.Module):\n", + "\n", + " def __init__(self, input_dim, hidden_dim, output_dim):\n", + " super(NN4Layer, self).__init__()\n", + "\n", + " # First linear layer: input features -> hidden layer\n", + " self.layer1 = nn.Linear(input_dim, hidden_dim)\n", + "\n", + " # Second linear layer: hidden layer -> hidden layer\n", + " self.layer2 = nn.Linear(hidden_dim, hidden_dim)\n", + "\n", + " # Output layer: hidden layer -> number of classes (logits)\n", + " self.layer3 = nn.Linear(hidden_dim, output_dim)\n", + "\n", + " self.layer4 = nn.Linear(hidden_dim, output_dim)\n", + "\n", + " # ReLU activation for non-linearity\n", + " self.relu = nn.ReLU()\n", + "\n", + " # Defines how input data flows through the network\n", + " def forward(self, x):\n", + " # First hidden layer\n", + " z1 = self.layer1(x)\n", + " a1 = self.relu(z1)\n", + "\n", + " # Second hidden layer\n", + " z2 = self.layer2(a1)\n", + " a2 = self.relu(z2)\n", + "\n", + " z3 = self.layer(a2)\n", + " a3 = self.relu(z3)\n", + "\n", + " # Output layer (raw scores / logits)\n", + " output = self.layer3(a3) # there is something missing here, remember? :)\n", + "\n", + " return output" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your training loop here:\n", + "def train_one_epoch(model, optimizer, criterion, train_loader, device):\n", + " # Set the model to training mode\n", + " model.train()\n", + "\n", + " running_loss = 0.0\n", + "\n", + " for X_batch, y_batch in train_loader:\n", + " # Move batch to the selected device\n", + " X_batch = X_batch.to(device)\n", + " y_batch = y_batch.view(-1, 1).to(device)\n", + "\n", + " # Forward pass\n", + " outputs = model(X_batch)\n", + " loss = criterion(outputs, y_batch)\n", + "\n", + " # Backward pass & optimization\n", + " optimizer.zero_grad() # Clear previous gradients\n", + " loss.backward() # Compute gradients\n", + " optimizer.step() # Update model parameters\n", + "\n", + " running_loss += loss.item()\n", + "\n", + " # Average loss over all batches\n", + " avg_loss = running_loss / len(train_loader)\n", + "\n", + " return avg_loss" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your validation loop here:\n", + "def validate(model, criterion, test_loader, device):\n", + " # Set the model to evaluation mode\n", + " model.eval()\n", + "\n", + " running_loss = 0.0\n", + " correct = 0\n", + " total = 0\n", + "\n", + " with torch.no_grad(): # Disable gradient computation\n", + " for X_batch, y_batch in test_loader:\n", + " # Move batch to the selected device\n", + " X_batch = X_batch.to(device)\n", + " y_batch = y_batch.view(-1, 1).to(device)\n", + "\n", + " # Forward pass\n", + " outputs = model(X_batch)\n", + " loss = criterion(outputs, y_batch)\n", + " running_loss += loss.item()\n", + "\n", + " # Binary predictions\n", + " predicted = (outputs > 0.5).float()\n", + "\n", + " # Accuracy calculation\n", + " correct += (predicted == y_batch).sum().item()\n", + " total += y_batch.size(0)\n", + "\n", + " avg_loss = running_loss / len(test_loader)\n", + " accuracy = correct / total\n", + "\n", + " return avg_loss, accuracy" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Define device, model, loss, optimizer:\n", + "# Device setup\n", + "device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n", + "\n", + "# Model parameters\n", + "input_dim = 36*36*3\n", + "hidden_dim = 14 # Design choice\n", + "\n", + "# Instantiate model\n", + "model = NN3Layer(input_dim, hidden_dim).to(device)\n", + "\n", + "# Print the model architecture\n", + "print(\"Model Architecture:\\n\")\n", + "print(model)\n", + "\n", + "# Calculate the total number of trainable parameters\n", + "total_params = sum(p.numel() for p in model.parameters() if p.requires_grad)\n", + "print(f\"\\nTotal trainable parameters: {total_params}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "num_epochs = 10\n", + "learning_rate = 0.001\n", + "\n", + "# Define criterion (loss function) - using CrossEntropyLoss as model now outputs logits\n", + "criterion = nn.MSELoss()\n", + "# Define optimizer\n", + "optimizer = Adam(model.parameters(), learning_rate)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Device setup\n", + "device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n", + "\n", + "# Model parameters\n", + "# TODO: What are input features ? (hint: flatten using channel, height, width)\n", + " # \n", + "\n", + "# TODO: choose number of hidden neurons\n", + "hidden_dim =512 # \n", + "\n", + "# TODO: what are the number of classes ?\n", + "output_dim =1 # \n", + "\n", + "# TODO: Instantiate model (what are the model class inputs?)\n", + "model = NN3Layer(input_dim, hidden_dim).to(device)# .to(device)\n", + "\n", + "# TODO: Print the model architecture\n", + "print(\"Model Architecture:\\n\")\n", + "print(model)\n", + "\n", + "# Calculate the total number of trainable parameters\n", + "total_params = sum(p.numel() for p in model.parameters() if p.requires_grad)\n", + "print(f\"\\nTotal trainable parameters: {total_params}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Start training for 20 epochs:\n", + "train_losses = []\n", + "val_losses = []\n", + "val_accuracies = []\n", + "\n", + "print('Starting Training...')\n", + "for epoch in range(num_epochs):\n", + " # Train one epoch\n", + " train_loss = train_one_epoch(model, optimizer, criterion, train_loader, device)\n", + "\n", + " # Validate\n", + " val_loss, val_accuracy = validate(model, criterion, test_loader, device)\n", + "\n", + " train_losses.append(train_loss)\n", + " val_losses.append(val_loss)\n", + " val_accuracies.append(val_accuracy)\n", + "\n", + " print(f'Epoch [{epoch+1}/{num_epochs}], Train Loss: {train_loss:.4f}, Val Loss: {val_loss:.4f}, Val Accuracy: {val_accuracy:.4f}')\n", + "\n", + "print('Training Complete!')" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2 (Bonus): Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/395/Q3.ipynb b/submissions_extracted/395/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..36348c14a8e84d2636eb6f01686bbdbdc42d1ec9 --- /dev/null +++ b/submissions_extracted/395/Q3.ipynb @@ -0,0 +1,189 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "\n", + "\n", + "# Download latest version\n", + "\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q3-exam-data\")\n", + "\n", + "\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import numpy as np\n", + "import pandas as pd\n", + "import matplotlib.pyplot as plt\n", + "import seaborn as sns\n", + "from scipy import stats" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "df = pd.read_csv(\"/kaggle/input/q3-exam-data/Q3_data.csv\")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "df.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "df.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "for col in df.columns:\n", + " if df[col].isnull().sum() > 0:\n", + " df[col] = df[col].fillna(df[col].mean())\n", + "df.isnull().sum()\n", + "\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "df.drop_duplicates()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "from sklearn.preprocessing import StandardScaler\n", + "\n", + "scaler = StandardScaler()\n", + "for col in list(df.columns):\n", + " df[col] = scaler.fit_transform(df[col])\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/396/Q1.ipynb b/submissions_extracted/396/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..729a3fc01047727853084b4c100cb321bb4a66f3 --- /dev/null +++ b/submissions_extracted/396/Q1.ipynb @@ -0,0 +1,251 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q1-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "import numpy as np\n", + "import pandas as pd\n", + "import matplotlib.pyplot as plt\n", + "import os\n", + "import kagglehub\n", + "\n", + "from sklearn.model_selection import train_test_split, KFold\n", + "from sklearn.preprocessing import LabelEncoder, OneHotEncoder, StandardScaler\n", + "from sklearn.ensemble import RandomForestRegressor\n", + "from sklearn.metrics import mean_absolute_error, mean_squared_error\n", + "\n", + "delivery_path = os.path.join(path, \"Q1_data.csv\")\n", + "df_raw = pd.read_csv(delivery_path)\n", + "df_delivery = df_raw.copy()\n", + "print(f\"Dataset shape: {df_delivery.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "df_delivery.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "df_delivery.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "df_delivery.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "plt.figure(figsize=(10, 5))\n", + "plt.hist(df_delivery['Delivery_Time'].dropna(), bins=67, edgecolor='black')\n", + "plt.title('Delivery Time distribution')\n", + "plt.xlabel('Delivery Time')\n", + "# plt.ylabel('Frequency')\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "df_delivery= df_delivery.drop(columns=['Order_ID'])\n", + "df_raw= df_raw.drop(columns=['Order_ID'])" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "# printing Missing values for better visualisation\n", + "print(\"Missing values:\")\n", + "print(df_delivery.isnull().sum())\n", + "\n", + "#Dropped rows with important features missing as theyre crucial to the calculation\n", + "df_delivery = df_delivery.dropna(subset=[ 'Traffic_Level', 'Time_of_Day','Weather'])\n", + "\n", + "#Replaced missing categorical with the mode as theyre less important\n", + "df_delivery['Courier_Experience_yrs'] = df_delivery['Courier_Experience_yrs'].fillna(df_delivery['Courier_Experience_yrs'].mode()[0])\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "duplicates = df_delivery.duplicated().sum()\n", + "print(f\"Number of Duplicate Samples: {duplicates}\")\n", + "df_delivery.drop_duplicates(inplace=True)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "\n", + "categorical_cols = df_delivery.select_dtypes(include=[\"object\"]).columns\n", + "print(\"Categorical Columns:\", list(categorical_cols))\n", + "\n", + "label_encoders = {}\n", + "for col in categorical_cols:\n", + " le = LabelEncoder()\n", + " df_delivery[col] = le.fit_transform(df_delivery[col])\n", + " label_encoders[col] = le\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "# need to split before scaling ,Train-test split (80% train, 20% test)\n", + "X_train, X_test, y_train, y_test = train_test_split(df_delivery, df_raw['Delivery_Time'], test_size=0.2, random_state=42)\n", + "print(f\"Train: {X_train.shape}, Test: {X_test.shape}\")\n", + "\n", + "\n", + "scaler = StandardScaler()\n", + "X_train_scaled = scaler.fit_transform(X_train)\n", + "X_test_scaled = scaler.transform(X_test)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 6: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:\n", + "kfold = KFold(n_splits=5, shuffle=True, random_state=42, stratify=True)\n", + "\n", + "mae_scores = []\n", + "rmse_scores = []\n", + "\n", + "for train_idx, val_idx in kfold.split(X_train_scaled):\n", + " X_fold_train, X_fold_val = X_train_scaled[train_idx], X_train_scaled[val_idx]\n", + " y_fold_train, y_fold_val = y_train.iloc[train_idx], y_train.iloc[val_idx]\n", + "\n", + " # Train and predict\n", + " model.fit(X_fold_train, y_fold_train)\n", + " y_fold_pred = model.predict(X_fold_val)\n", + "\n", + " # Calculate metrics\n", + " mae_scores.append(mean_absolute_error(y_fold_val, y_fold_pred))\n", + " rmse_scores.append(np.sqrt(mean_squared_error(y_fold_val, y_fold_pred)))\n", + "\n", + "mae_scores = np.array(mae_scores)\n", + "rmse_scores = np.array(rmse_scores)\n", + "\n", + "print(f\"5-Fold CV Results:\")\n", + "print(f\"MAE: ${mae_scores.mean():,.2f}\")\n", + "print(f\"RMSE: ${rmse_scores.mean():,.2f}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/396/Q2.ipynb b/submissions_extracted/396/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..e4d3eee3ce43a5f3506cdbc7ef847a56159b16e2 --- /dev/null +++ b/submissions_extracted/396/Q2.ipynb @@ -0,0 +1,394 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q2-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import os\n", + "import pandas as pd\n", + "import numpy as np\n", + "from PIL import Image\n", + "from sklearn.model_selection import train_test_split\n", + "\n", + "# Load Labels\n", + "labels_df = pd.read_csv(os.path.join(path, \"labels.csv\"))\n", + "img_dir = os.path.join(path, \"images\")\n", + "\n", + "images = []\n", + "ages = []\n", + "\n", + "# Load Images and Resize\n", + "print(\"Loading images...\")\n", + "for index, row in labels_df.iterrows():\n", + " img_name = row.iloc[0]\n", + " age = row.iloc[1]\n", + " img_path = os.path.join(img_dir, img_name)\n", + "\n", + " if os.path.exists(img_path):\n", + " img = Image.open(img_path).convert('RGB')\n", + " img_array = np.array(img) / 255.0 # Normalize pixel values to [0, 1]\n", + " images.append(img_array)\n", + " ages.append(age)\n", + "\n", + "X = np.array(images)\n", + "y = np.array(ages)\n", + "\n", + "# Transpose image dimensions to match PyTorch format (N, C, H, W)\n", + "X = np.transpose(X, (0, 3, 1, 2))\n", + "\n", + "# Split Data\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n", + "\n", + "print(f\"X_train shape: {X_train.shape}\")\n", + "print(f\"X_test shape: {X_test.shape}\")\n", + "print(f\"y_train shape: {y_train.shape}\")\n", + "print(f\"y_test shape: {y_test.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 1. Convert Numpy arrays to PyTorch Tensors\n", + "\n", + "import kagglehub\n", + "import pandas as pd\n", + "import numpy as np\n", + "import torch\n", + "import torch.nn as nn\n", + "from torch.optim import AdamW\n", + "import matplotlib.pyplot as plt\n", + "from torch.utils.data import DataLoader, TensorDataset\n", + "from sklearn.model_selection import train_test_split\n", + "from sklearn.preprocessing import StandardScaler, LabelEncoder\n", + "from sklearn.metrics import mean_absolute_error, mean_squared_error, r2_score\n", + "\n", + "\n", + "X_train = torch.tensor(X_train, dtype=float)\n", + "X_test = torch.tensor(X_test,dtype=float)\n", + "y_train = torch.tensor(y_train,dtype=float)\n", + "y_test = torch.tensor(y_test,dtype=float)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 2. Create TensorDataset objects\n", + "from sklearn.datasets import load_breast_cancer\n", + "from sklearn.model_selection import train_test_split\n", + "from sklearn.preprocessing import StandardScaler\n", + "from torch.utils.data import TensorDataset\n", + "from torch.utils.data import DataLoader\n", + "import torch\n", + "\n", + "train_dataset = TensorDataset(X_train, y_train)\n", + "test_dataset = TensorDataset(X_test, y_test)\n", + "\n", + "first_sample, _ = train_dataset[0]\n", + "print(f\"Shape of one sample: {first_sample.shape}\")\n", + "\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 3. Create DataLoaders\n", + "# DataLoader for training data\n", + "train_loader = DataLoader(\n", + " train_dataset,\n", + " batch_size=32,\n", + " shuffle=True,\n", + " num_workers=2\n", + ")\n", + "# DataLoader for test/validation data\n", + "test_loader = DataLoader(\n", + " test_dataset,\n", + " batch_size=32,\n", + " shuffle=False,\n", + " num_workers=2\n", + ")\n", + "# Get the first batch from the training DataLoader\n", + "X_batch, y_batch = next(iter(train_loader))\n", + "\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 4. Print shape of one batch\n", + "print(f\"Training batch input shape: {X_batch.shape}\")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 5. Display sample images\n", + "\n", + "# print(f\"Training batch labels shape: {y_batch.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your model class here:lass NN1Layer(nn.Module):\n", + "class NN1Layer(nn.Module):\n", + " def __init__(self, input_dim, hidden_dim):\n", + " super(NN1Layer, self).__init__()\n", + "\n", + " # First linear layer: input features -> hidden layer\n", + " self.layer1 = nn.Linear(input_dim, hidden_dim)\n", + "\n", + " # Second linear layer: hidden layer -> hidden layer\n", + " self.layer2 = nn.Linear(hidden_dim, hidden_dim)\n", + "\n", + " # Third linear layer: hidden layer -> hidden layer\n", + " self.layer3 = nn.Linear(hidden_dim, hidden_dim)\n", + "\n", + " # Fourth linear layer: hidden layer -> hidden layer\n", + " self.layer4 = nn.Linear(hidden_dim, hidden_dim)\n", + "\n", + "\n", + " # Output layer: hidden layer -> single continuous value\n", + " self.layer5 = nn.Linear(hidden_dim, 1)\n", + "\n", + " # ReLU activation for non-linearity in hidden layers\n", + " self.relu = nn.ReLU()\n", + "\n", + "\n", + " # Defines how input data flows through the network\n", + " def forward(self, x):\n", + " # First hidden layer\n", + " a1 = self.relu(self.layer1(x))\n", + "\n", + " a2 = self.relu(self.layer2(a1))\n", + "\n", + " a3 = self.relu(self.layer3(a2))\n", + "\n", + " a4 = self.relu(self.layer4(a3))\n", + " # Output layer (regression output)\n", + " output = self.layer5(a4)\n", + "\n", + " return output" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your training loop here:\n", + "def train_one_epoch(model, optimizer, criterion, train_loader, device):\n", + " # Set the model to training mode\n", + " model.train()\n", + "\n", + " running_loss = 0.0\n", + "\n", + " for X_batch, y_batch in train_loader:\n", + " # Move batch to the selected device\n", + " X_batch = X_batch.to(device) # shape: (batch_size, num_features)\n", + " y_batch = y_batch.view(-1, 1).to(device) # shape: (batch_size, 1)\n", + "\n", + " # Forward pass (continuous output)\n", + " outputs = model(X_batch) # shape: (batch_size, 1)\n", + " loss = criterion(outputs, y_batch)\n", + "\n", + " # Backward pass & optimization\n", + " optimizer.zero_grad() # Clear previous gradients\n", + " loss.backward() # Compute gradients\n", + " optimizer.step() # Update model parameters\n", + "\n", + " running_loss += loss.item()\n", + "\n", + " # Average loss over all batches\n", + " avg_loss = running_loss / len(train_loader)\n", + "\n", + " return avg_loss" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your validation loop here:\n", + "def validate(model, criterion, test_loader, device):\n", + " # Set the model to evaluation mode\n", + " model.eval()\n", + "\n", + " running_loss = 0.0\n", + " correct = 0\n", + " total = 0\n", + "\n", + " with torch.no_grad(): # Disable gradient computation\n", + " for X_batch, y_batch in test_loader:\n", + " # Move batch to the selected device\n", + " X_batch = X_batch.to(device)\n", + " y_batch = y_batch.view(-1, 1).to(device)\n", + "\n", + " # Forward pass\n", + " outputs = model(X_batch.astype(float))\n", + " loss = criterion(outputs, y_batch)\n", + " running_loss += loss.item()\n", + "\n", + " # Binary predictions\n", + " predicted = (outputs > 0.5).float()\n", + "\n", + " # Accuracy calculation\n", + " correct += (predicted == y_batch).sum().item()\n", + " total += y_batch.size(0)\n", + "\n", + " avg_loss = running_loss / len(test_loader)\n", + " accuracy = correct / total\n", + "\n", + " return avg_loss, accuracy\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Define device, model, loss, optimizer:\n", + "device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n", + "\n", + "# Model parameters\n", + "input_dim = X_train.shape[1] # Number of tabular features\n", + "hidden_dim = 64 # Design choice\n", + "\n", + "# Instantiate regression model\n", + "model = NN1Layer(input_dim, hidden_dim).to(device)\n", + "\n", + "# Print the model architecture\n", + "print(\"Model Architecture:\\n\")\n", + "print(model)\n", + "\n", + "# Calculate the total number of trainable parameters\n", + "total_params = sum(p.numel() for p in model.parameters() if p.requires_grad)\n", + "print(f\"\\nTotal trainable parameters: {total_params}\")\n", + "\n", + "num_epochs = 20\n", + "learning_rate = 0.001\n", + "\n", + "# Define criterion (loss function)\n", + "criterion = nn.MSELoss()\n", + "# Define optimizer\n", + "optimizer = AdamW(model.parameters(), learning_rate)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Start training for 20 epochs:\n", + "train_losses = []\n", + "val_losses = []\n", + "\n", + "print('Starting Training...')\n", + "for epoch in range(num_epochs):\n", + " # Train one epoch\n", + " train_loss = train_one_epoch(model, optimizer, criterion, train_loader, device)\n", + "\n", + " # Validate\n", + " val_loss = validate(model, criterion, test_loader, device)\n", + "\n", + " train_losses.append(train_loss)\n", + " val_losses.append(val_loss)\n", + "\n", + " if (epoch + 1) % 5 == 0:\n", + " print(\n", + " f'Epoch [{epoch+1}/{num_epochs}], '\n", + " f'Train Loss: {train_loss:.4f}, '\n", + " f'Val Loss: {val_loss:.4f}'\n", + " )" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "# Plotting results\n", + "plt.figure(figsize=(7, 5))\n", + "\n", + "plt.plot(train_losses, label='Train Loss')\n", + "plt.plot(val_losses, label='Validation Loss')\n", + "plt.title('Loss over Epochs')\n", + "plt.xlabel('Epoch')\n", + "plt.ylabel('Loss (MSE)')\n", + "plt.legend()\n", + "\n", + "plt.tight_layout()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2 (Bonus): Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/396/Q3.ipynb b/submissions_extracted/396/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..a297f3ab95b3da38ee797ca93e567efa810ec46a --- /dev/null +++ b/submissions_extracted/396/Q3.ipynb @@ -0,0 +1,191 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "\n", + "\n", + "# Download latest version\n", + "\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q3-exam-data\")\n", + "\n", + "\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "import numpy as np\n", + "import pandas as pd\n", + "import matplotlib.pyplot as plt\n", + "import os\n", + "import kagglehub\n", + "\n", + "from sklearn.model_selection import train_test_split, KFold\n", + "from sklearn.preprocessing import LabelEncoder, OneHotEncoder, StandardScaler\n", + "from sklearn.ensemble import RandomForestRegressor\n", + "from sklearn.metrics import mean_absolute_error, mean_squared_error\n", + "\n", + "amex = os.path.join(path, \"Q3_data.csv\")\n", + "df_raw = pd.read_csv(amex)\n", + "df_amex = df_raw.copy()\n", + "print(f\"Dataset shape: {df_amex.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "df_amex.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "df_amex.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "df_amex.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "\n", + "# printing Missing values for better visualisation\n", + "print(\"Missing values:\")\n", + "print(df_amex.isnull().sum())\n", + "\n", + "# #Dropped rows with important features missing as theyre crucial to the calculation\n", + "# df_delivery = df_amex.dropna(subset=['Delivery_Time', 'Traffic_Level', 'Time_of_Day','Weather'])\n", + "\n", + "# #Replaced missing categorical with the mode as theyre less important\n", + "# df_delivery['Courier_Experience_yrs'] = df_delivery['Courier_Experience_yrs'].fillna(df_delivery['Courier_Experience_yrs'].mode()[0])\n", + "\n", + "df_amex.dropna(axis=[0])\n", + "print(df_amex.isnull().sum())" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/397/Q1.ipynb b/submissions_extracted/397/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..95f6a37bdb72661dfa90e0c8d1bb1b8980ed078b --- /dev/null +++ b/submissions_extracted/397/Q1.ipynb @@ -0,0 +1,302 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q1-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "import os\n", + "import pandas as pd\n", + "csv_path = os.path.join(path, \"Q1_data.csv\")\n", + "df = pd.read_csv(csv_path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "df.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "df.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "import matplotlib.pyplot as plt\n", + "delivery_time_counts = df['Delivery_Time'].value_counts()\n", + "plt.figure(figsize=(10, 5))\n", + "plt.bar(delivery_time_counts.index, delivery_time_counts.values, color='coral')\n", + "plt.title('Dilivery Time Distribution')\n", + "plt.xlabel('Dilivery Time')\n", + "plt.ylabel('Count')\n", + "plt.xticks(rotation=45)\n", + "plt.show()\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "df.drop( columns= ['Order_ID'])" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "#Checking if there is missing values\n", + "def check_missing_values(df):\n", + " # Get missing values using pandas\n", + " missing_values = df.isnull().sum()\n", + " print(\"Missing Values per Column:\")\n", + " print(missing_values[missing_values > 0])\n", + " if missing_values.any():\n", + " print(\"\\nHandle Missing Values as needed.\")\n", + " else:\n", + " print(\"\\nNo Missing Values Found.\")\n", + "check_missing_values(df)\n", + "\n", + "#Handle the missing values\n", + "df['Courier_Experience_yrs'] = df['Courier_Experience_yrs'].fillna(df['Courier_Experience_yrs'].mean())\n", + "df['Delivery_Time'] = df['Delivery_Time'].fillna(df['Delivery_Time'].mean())\n", + "\n", + "df['Weather'] = df['Weather'].fillna(df['Weather'].mode()[0])\n", + "df['Traffic_Level'] = df['Traffic_Level'].fillna(df['Traffic_Level'].mode()[0])\n", + "df['Time_of_Day'] = df['Time_of_Day'].fillna(df['Time_of_Day'].mode()[0])\n", + "\n", + "print(\"Missing values remaining:\", df.isnull().sum().sum())" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "#Check for duplicates and remove them\n", + "def check_duplicates(df):\n", + " duplicates = df.duplicated().sum()\n", + " print(f\"Number of Duplicate Samples: {duplicates}\")\n", + " if duplicates > 0:\n", + " print(\"Dropping Duplicates...\")\n", + " df.drop_duplicates(inplace=True)\n", + " print(\"Duplicates Dropped.\")\n", + " else:\n", + " print(\"No Duplicate Samples Found.\")\n", + "check_duplicates(df)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "from sklearn.preprocessing import LabelEncoder\n", + "\n", + "#Label Encoder\n", + "categorical_cols = ['Weather', 'Time_of_Day', 'Vehicle_Type', 'Traffic_Level']\n", + "for col in categorical_cols:\n", + " le = LabelEncoder()\n", + " df[col] = le.fit_transform(df[col].astype(str))\n", + "df.head()\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "from sklearn.preprocessing import StandardScaler #import StandardScaler\n", + "print('data before scaling:\\n', df) #show before scaling\n", + "standard_scaler = StandardScaler() # Instantiate StandardScaler\n", + "data_standard_scaled = standard_scaler.fit_transform(df) # Apply fi\n", + "print('\\nData after scaling:\\n', data_standard_scaled) #show after scaling\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 6: Write your code here:\n", + "def check_target_imbalance(df, target_column):\n", + " print(\"Target Distribution:\")\n", + " df['Delivery_Time'].hist()\n", + " plt.show()\n", + "check_target_imbalance(df, \"delivery_time\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "X = df.drop(\"Delivery_Time\", axis=1).astype(float)\n", + "feature_cols = ['Order_ID',\t'Distance_km',\t'Weather',\t'Traffic_Level',\t'Time_of_Day',\t'Vehicle_Type',\t'Preparation_Time_min',\t'Courier_Experience_yrs']\n", + "X = df[feature_cols]\n", + "y = df['Delivery_Time'].astype(float)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:\n", + "import numpy as np\n", + "from sklearn.model_selection import train_test_split, KFold\n", + "from sklearn.ensemble import RandomForestRegressor\n", + "from sklearn.metrics import mean_absolute_error, mean_squared_error\n", + "import warnings\n", + "warnings.filterwarnings('ignore')\n", + "\n", + "# Train-test split (80% train, 20% test)\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n", + "print(f\"Train: {X_train.shape}, Test: {X_test.shape}\")\n", + "\n", + "# Scale features - fit on train, transform both\n", + "scaler = StandardScaler()\n", + "X_train_scaled = scaler.fit_transform(X_train)\n", + "X_test_scaled = scaler.transform(X_test)\n", + "print(f\"\\nScaled ranges - Min: {X_train_scaled.min():.2f}, Max: {X_train_scaled.max():.2f}\")\n", + "pd.DataFrame(X_train_scaled, columns=X_train.columns).head(3)\n", + "\n", + "# Train Random Forest Regressor\n", + "model = RandomForestRegressor(n_estimators=100, max_depth=20, random_state=42, n_jobs=-1)\n", + "model.fit(X_train_scaled, y_train)\n", + "print(\"Model trained!\")\n", + "\n", + "# Predict and evaluate\n", + "y_pred = model.predict(X_test_scaled)\n", + "mae = mean_absolute_error(y_test, y_pred)\n", + "print(f\"MAE: ${mae:,.2f}\")\n", + "\n", + "kfold = KFold(n_splits=5, shuffle=True, random_state=42)\n", + "mae_scores = []\n", + "rmse_scores = []\n", + "for train_idx, val_idx in kfold.split(X_train_scaled):\n", + " X_fold_train, X_fold_val = X_train_scaled[train_idx], X_train_scaled[val_idx]\n", + " y_fold_train, y_fold_val = y_train.iloc[train_idx], y_train.iloc[val_idx]\n", + "# Train and predict\n", + "model.fit(X_fold_train, y_fold_train)\n", + "y_fold_pred = model.predict(X_fold_val)\n", + "# Calculate metrics\n", + "mae_scores.append(mean_absolute_error(y_fold_val, y_fold_pred))\n", + "rmse_scores.append(np.sqrt(mean_squared_error(y_fold_val, y_fold_pred)))\n", + "mae_scores = np.array(mae_scores)\n", + "rmse_scores = np.array(rmse_scores)\n", + "print(f\"5-Fold CV Results:\")\n", + "print(f\"MAE: ${mae_scores.mean():,.2f}\")\n", + "print(f\"RMSE: ${rmse_scores.mean():,.2f}\")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "# Feature importance\n", + "feature_importance = pd.DataFrame({'feature': feature_cols,'importance': model.feature_importances_}).sort_values('importance', ascending=False)\n", + "plt.figure(figsize=(10, 6))\n", + "plt.barh(feature_importance['feature'], feature_importance['importance'])\n", + "plt.xlabel('Importance')\n", + "plt.title('Feature Importance')\n", + "plt.gca().invert_yaxis()\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "plt.figure(figsize=(10, 5))\n", + "plt.hist(df['Delivery_Time'].dropna(), bins=50, edgecolor='black')\n", + "plt.title('Delivery Time Distribution')\n", + "plt.xlabel('Delivery_Time')\n", + "plt.ylabel('Frequency')\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/397/Q2.ipynb b/submissions_extracted/397/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..bfcb7474f0eb5d1efbc9861bc50b96386f3222b1 --- /dev/null +++ b/submissions_extracted/397/Q2.ipynb @@ -0,0 +1,426 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q2-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import os\n", + "import pandas as pd\n", + "import numpy as np\n", + "from PIL import Image\n", + "from sklearn.model_selection import train_test_split\n", + "\n", + "# Load Labels\n", + "labels_df = pd.read_csv(os.path.join(path, \"labels.csv\"))\n", + "img_dir = os.path.join(path, \"images\")\n", + "\n", + "images = []\n", + "ages = []\n", + "\n", + "# Load Images and Resize\n", + "print(\"Loading images...\")\n", + "for index, row in labels_df.iterrows():\n", + " img_name = row.iloc[0]\n", + " age = row.iloc[1]\n", + " img_path = os.path.join(img_dir, img_name)\n", + "\n", + " if os.path.exists(img_path):\n", + " img = Image.open(img_path).convert('RGB')\n", + " img_array = np.array(img) / 255.0 # Normalize pixel values to [0, 1]\n", + " images.append(img_array)\n", + " ages.append(age)\n", + "\n", + "X = np.array(images)\n", + "y = np.array(ages)\n", + "\n", + "# Transpose image dimensions to match PyTorch format (N, C, H, W)\n", + "X = np.transpose(X, (0, 3, 1, 2))\n", + "\n", + "# Split Data\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n", + "\n", + "print(f\"X_train shape: {X_train.shape}\")\n", + "print(f\"X_test shape: {X_test.shape}\")\n", + "print(f\"y_train shape: {y_train.shape}\")\n", + "print(f\"y_test shape: {y_test.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 1. Convert Numpy arrays to PyTorch Tensors\n", + "from sklearn.preprocessing import StandardScaler\n", + "from torch.utils.data import TensorDataset\n", + "from torch.utils.data import DataLoader\n", + "import torch\n", + "# transform to tensors\n", + "X_train = torch.tensor(X_train, dtype=torch.float32)\n", + "X_test = torch.tensor(X_test, dtype=torch.float32)\n", + "y_train = torch.tensor(y_train, dtype=torch.float32)\n", + "y_test = torch.tensor(y_test, dtype=torch.float32)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 2. Create TensorDataset objects\n", + "\n", + "# TensorDataset pairs input features (X) with their corresponding labels (y)\n", + "# Each item in the dataset is returned as (X[i], y[i])\n", + "train_dataset = TensorDataset(X_train, y_train)\n", + "test_dataset = TensorDataset(X_test, y_test)\n", + "# Access a single sample from the dataset\n", + "# This helps verify the shape of one data sample\n", + "first_sample, _ = train_dataset[0]\n", + "print(f\"Shape of one sample: {first_sample.shape}\")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 3. Create DataLoaders\n", + "from torch.utils.data import DataLoader\n", + "# DataLoader for training data\n", + "train_loader = DataLoader(\n", + "train_dataset,\n", + "batch_size=32,\n", + "shuffle=True,\n", + "num_workers=2\n", + ")\n", + "# DataLoader for test/validation data\n", + "test_loader = DataLoader(\n", + "test_dataset,\n", + "batch_size=32,\n", + "shuffle=False,\n", + "num_workers=2\n", + ")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 4. Print shape of one batch\n", + "X_batch, y_batch = next(iter(train_loader))\n", + "print(f\"Training batch input shape: {X_batch.shape}\")\n", + "print(f\"Training batch labels shape: {y_batch.shape}\")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 5. Display sample images\n", + "sample_image, sample_label = train_dataset[0]\n", + "print(f\"\\n Image shape: {sample_image.shape}\") # (1, 28, 28)\n", + "print(f\"Label: {sample_label}\")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your model class here:\n", + "import torch\n", + "import torch.nn as nn\n", + "# Create a linear layer: 3 input features -> 1 output\n", + "linear = nn.Linear(in_features=3, out_features=1)\n", + "# Example input: batch of 4 samples, each with 3 features\n", + "x = torch.randn(4, 3)\n", + "# Forward through the layer\n", + "y = linear(x)\n", + "\n", + "class NN1Layer(nn.Module):\n", + " def __init__(self, input_dim):\n", + " super(NN1Layer, self).__init__()\n", + "# input_dim = num of features, Output for binary classification is 1\n", + " self.layer_1 = nn.Linear(input_dim, 1)\n", + "# output activation function\n", + " self.sigmoid = nn.Sigmoid()\n", + " # forward pass\n", + " def forward(self, x):\n", + " z = self.layer_1(x)\n", + " a = self.sigmoid(z)\n", + " return a\n", + "\n", + "class NN2Layer(nn.Module):\n", + "\n", + " def __init__(self, input_dim, hidden_dim):\n", + "\n", + " super(NN2Layer, self).__init__()\n", + " # input_dim = num of features, hidden_dim = num of neurons\n", + " self.layer1 = nn.Linear(input_dim, hidden_dim)\n", + " # hidden_dim = num of neurons, Output for binary classification is 1\n", + " self.layer2 = nn.Linear(hidden_dim, 1)\n", + "\n", + " # non-linearity activation function\n", + " self.relu = nn.ReLU()\n", + " # output activation function\n", + " self.sigmoid = nn.Sigmoid()\n", + "\n", + " # forward pass\n", + " def forward(self, x):\n", + " z1 = self.layer1(x)\n", + " a1 = self.relu(z1)\n", + " z2 = self.layer2(a1)\n", + " a2 = self.sigmoid(z2)\n", + " return a2\n", + "\n", + "class NN3Layer(nn.Module):\n", + "\n", + " def __init__(self, input_dim, hidden_dim):\n", + "\n", + " super(NN2Layer, self).__init__()\n", + " # input_dim = num of features, hidden_dim = num of neurons\n", + " self.layer2 = nn.Linear(input_dim, hidden_dim)\n", + " # hidden_dim = num of neurons, Output for binary classification is 1\n", + " self.layer3 = nn.Linear(hidden_dim, 1)\n", + "\n", + " # non-linearity activation function\n", + " self.relu = nn.ReLU()\n", + " # output activation function\n", + " self.sigmoid = nn.Sigmoid()\n", + "\n", + " # forward pass\n", + " def forward(self, x):\n", + " z1 = self.layer1(x)\n", + " a1 = self.relu(z1)\n", + " z2 = self.layer2(a1)\n", + " a2 = self.sigmoid(z2)\n", + " z3 = self.layer2(a1)\n", + " a3 = self.sigmoid(z2)\n", + " return a3\n", + "\n", + "class NN4Layer(nn.Module):\n", + "\n", + " def __init__(self, input_dim, hidden_dim):\n", + "\n", + " super(NN2Layer, self).__init__()\n", + " # input_dim = num of features, hidden_dim = num of neurons\n", + " self.layer3 = nn.Linear(input_dim, hidden_dim)\n", + " # hidden_dim = num of neurons, Output for binary classification is 1\n", + " self.layer4 = nn.Linear(hidden_dim, 1)\n", + "\n", + " # non-linearity activation function\n", + " self.relu = nn.ReLU()\n", + " # output activation function\n", + " self.sigmoid = nn.Sigmoid()\n", + "\n", + " # forward pass\n", + " def forward(self, x):\n", + " z1 = self.layer1(x)\n", + " a1 = self.relu(z1)\n", + " z2 = self.layer2(a1)\n", + " a2 = self.sigmoid(z2)\n", + " z3 = self.layer2(a1)\n", + " a3 = self.sigmoid(z2)\n", + " z4 = self.layer2(a1)\n", + " a4 = self.sigmoid(z2)\n", + " return a4\n", + "\n", + "# Instantiate the model\n", + "input_dim = 6 # number of input features\n", + "hidden_dim = 5 # number of hidden neurons\n", + "model = NN2Layer(input_dim, hidden_dim)\n", + "# Print the model architecture\n", + "print(\"Model Architecture:\\n\")\n", + "print(model)\n", + "# Calculate the total number of trainable parameters\n", + "total_params = sum(p.numel() for p in model.parameters() if p.requires_grad)\n", + "print(f\"\\nTotal trainable parameters: {total_params}\")\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your training loop here:\n", + "def train_one_epoch(model, optimizer, criterion, train_loader, device):\n", + "# Set the model to training mode\n", + " model.train()\n", + " running_loss = 0.0\n", + " for X_batch, y_batch in train_loader:\n", + "# Move batch to the selected device\n", + " X_batch = X_batch.to(device)\n", + " y_batch = y_batch.view(-1, 1).to(device)\n", + "# Forward pass\n", + " outputs = model(X_batch)\n", + " loss = criterion(outputs, y_batch)\n", + "# Backward pass & optimization\n", + " optimizer.zero_grad() # Clear previous gradients\n", + " loss.backward() # Compute gradients\n", + " optimizer.step() # Update model parameters\n", + " running_loss += loss.item()\n", + "# Average loss over all batches\n", + " avg_loss = running_loss / len(train_loader)\n", + " return avg_loss\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your validation loop here:\n", + "def validate(model, criterion, test_loader, device):\n", + "# Set the model to evaluation mode\n", + " model.eval()\n", + " running_loss = 0.0\n", + " correct = 0\n", + " total = 0\n", + " with torch.no_grad(): # Disable gradient computation\n", + " for X_batch, y_batch in test_loader:\n", + "# Move batch to the selected device\n", + " X_batch = X_batch.to(device)\n", + " y_batch = y_batch.view(-1, 1).to(device)\n", + "# Forward pass\n", + " outputs = model(X_batch)\n", + " loss = criterion(outputs, y_batch)\n", + " running_loss += loss.item()\n", + "# Binary predictions\n", + " predicted = (outputs > 0.5).float()\n", + "# Accuracy calculation\n", + " correct += (predicted == y_batch).sum().item()\n", + " total += y_batch.size(0)\n", + " avg_loss = running_loss / len(test_loader)\n", + " accuracy = correct / total\n", + " return avg_loss, accuracy" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Define device, model, loss, optimizer:\n", + "from torch.optim import Adam\n", + "num_epochs = 20\n", + "learning_rate = 0.001\n", + "# Define loss function\n", + "criterion = nn.CrossEntropyLoss()\n", + "# Define optimizer\n", + "optimizer = AdamW(model.parameters(), learning_rate)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Start training for 20 epochs:\n", + "# Device configuration\n", + "device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\n", + "print(f\"Using device: {device}\")\n", + "\n", + "num_epochs = 50\n", + "learning_rate = 0.001\n", + "\n", + "# Model, Criterion, Optimizer\n", + "input_dim = X_train.shape[1]\n", + "hidden_dim = 10\n", + "model =NN2Layer(input_dim, hidden_dim).to(device)\n", + "criterion = nn.BCELoss()\n", + "optimizer = Adam(model.parameters(), lr=learning_rate)\n", + "\n", + "\n", + "# Run Training\n", + "train_losses = []\n", + "val_losses = []\n", + "val_accuracies = []\n", + "\n", + "print('Starting Training...')\n", + "for epoch in range(num_epochs):\n", + " # Train one epoch\n", + " train_loss = train_one_epoch(model, optimizer, criterion, train_loader, device)\n", + "\n", + " # Validate\n", + " val_loss, val_accuracy = validate(model, criterion, test_loader, device)\n", + "\n", + " train_losses.append(train_loss)\n", + " val_losses.append(val_loss)\n", + " val_accuracies.append(val_accuracy)\n", + "\n", + " if (epoch + 1) % 5 == 0:\n", + " print(f'Epoch [{epoch+1}/{num_epochs}], Train Loss: {train_loss:.4f}, Val Loss: {val_loss:.4f}, Val Accuracy: {val_accuracy:.4f}')\n", + "\n", + "print('Training Complete!')\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "# Plotting results\n", + "plt.figure(figsize=(7, 5))\n", + "plt.plot(train_losses, label='Train Loss')\n", + "plt.plot(val_losses, label='Validation Loss')\n", + "plt.title('Loss over Epochs')\n", + "plt.xlabel('Epoch')\n", + "plt.ylabel('Loss')\n", + "plt.legend()\n", + "plt.tight_layout()\n", + "plt.show()\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2 (Bonus): Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/397/Q3.ipynb b/submissions_extracted/397/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..2a6ef4f8ce449e4e611623548aaa9ae0bb3b4900 --- /dev/null +++ b/submissions_extracted/397/Q3.ipynb @@ -0,0 +1,298 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "\n", + "\n", + "# Download latest version\n", + "\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q3-exam-data\")\n", + "\n", + "\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "import os\n", + "import pandas as pd\n", + "csv_path = os.path.join(path, \"Q3_data.csv\")\n", + "df = pd.read_csv(csv_path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "df.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "df.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "#Checking if there is missing values\n", + "def check_missing_values(df):\n", + " missing_values = df.isnull().sum()\n", + " print(\"Missing Values per Column:\")\n", + " print(missing_values[missing_values > 0])\n", + " if missing_values.any():\n", + " print(\"\\nHandle Missing Values as needed.\")\n", + " else:\n", + " print(\"\\nNo Missing Values Found.\")\n", + "check_missing_values(df)\n", + "\n", + "#Handle missing value\n", + "df['P_2'] = df['P_2'].fillna(df['P_2'].mean())\n", + "df['B_2'] = df['B_2'].fillna(df['B_2'].mean())\n", + "df['S_3'] = df['S_3'].fillna(df['S_3'].mean())\n", + "df['D_41'] = df['D_41'].fillna(df['D_41'].mean())\n", + "df['B_3'] = df['B_3'].fillna(df['B_3'].mean())\n", + "df['D_141'] = df['D_141'].fillna(df['D_141'].mean())\n", + "df['D_142'] = df['D_142'].fillna(df['D_142'].mean())\n", + "df['D_143'] = df['D_143'].fillna(df['D_143'].mean())\n", + "df['D_144'] = df['D_144'].fillna(df['D_144'].mean())\n", + "df['D_145'] = df['D_145'].fillna(df['D_145'].mean())\n", + "\n", + "print(\"\\n Missing Values Handeled.\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "def check_duplicates(df):\n", + " duplicates = df.duplicated().sum()\n", + " print(f\"Number of Duplicate Samples: {duplicates}\")\n", + " if duplicates > 0:\n", + " print(\"Dropping Duplicates...\")\n", + " df.drop_duplicates(inplace=True)\n", + " print(\"Duplicates Dropped.\")\n", + " else:\n", + " print(\"No Duplicate Samples Found.\")\n", + "\n", + "check_duplicates(df)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "#There is no categorical variables to encode" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "from sklearn.preprocessing import StandardScaler #import StandardScaler\n", + "numerical_cols = df.select_dtypes(include=[\"int64\", \"float64\"]).columns.drop(\"Target\")\n", + "scaler = StandardScaler()\n", + "df[numerical_cols] = scaler.fit_transform(df[numerical_cols])\n", + "df.head()\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "import matplotlib.pyplot as plt\n", + "def check_target_imbalance(df, target_column):\n", + " print(\"Target Distribution:\")\n", + " df['Target'].hist()\n", + " plt.show()\n", + "check_target_imbalance(df, \"Target\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "X = df.drop(\"Target\", axis=1).astype(float)\n", + "y = df['Target'].astype(float)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:\n", + "from sklearn.model_selection import StratifiedKFold\n", + "from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score\n", + "from tqdm import tqdm\n", + "from sklearn.neighbors import KNeighborsClassifier\n", + "from sklearn.svm import SVC\n", + "from sklearn.tree import DecisionTreeClassifier\n", + "from sklearn.ensemble import RandomForestClassifier\n", + "from xgboost import XGBClassifier\n", + "from catboost import CatBoostClassifier\n", + "\n", + "def gradient_descent(X, y, learning_rate, n_iters=500):\n", + " m, n = X.shape # m rows, n columns (dimensions)\n", + " theta = np.zeros(n) # initialize a zeros weight vector with n dimensions\n", + " losses = []\n", + "\n", + " for _ in tqdm(range(n_iters), desc=\"Training Logistic Regression\"):\n", + " z = np.dot(X, theta)\n", + " y_hat = sigmoid(z)\n", + " gradient = np.dot(X.T, (y_hat - y)) / m\n", + " theta -= learning_rate * gradient\n", + "\n", + " loss = binary_cross_entropy(y, y_hat)\n", + " losses.append(loss)\n", + "\n", + " return theta, losses\n", + "\n", + "n_splits = 5 # K=5 Folds\n", + "\n", + "# Stratified 5-Fold Cross-Validation, shuffled\n", + "skf = StratifiedKFold(n_splits=n_splits, shuffle=True, random_state=42)\n", + "\n", + "# Storage for logistic regression results for each fold\n", + "lr_losses = []\n", + "lr_accuracy = []\n", + "lr_precision = []\n", + "lr_recall = []\n", + "lr_f1 = []\n", + "\n", + "for fold_idx, (train_index, test_index) in enumerate(skf.split(X, y)):\n", + " print(f\"\\nFold {fold_idx + 1}/{n_splits}\")\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", + " # Train\n", + " theta, losses = gradient_descent(X_train, y_train, learning_rate=0.5, n_iters=500)\n", + "\n", + " # Validate\n", + " y_pred_proba = sigmoid(np.dot(X_test, theta))\n", + " y_pred = (y_pred_proba >= 0.5).astype(int)\n", + "\n", + " # Calculate evaluation metrics\n", + " accuracy = accuracy_score(y_test, y_pred)\n", + " precision = precision_score(y_test, y_pred, zero_division=0)\n", + " recall = recall_score(y_test, y_pred, zero_division=0)\n", + " f1 = f1_score(y_test, y_pred, zero_division=0)\n", + "\n", + " # Store results\n", + " lr_losses.append(losses)\n", + " lr_accuracy.append(accuracy)\n", + " lr_precision.append(precision)\n", + " lr_recall.append(recall)\n", + " lr_f1.append(f1)\n", + "\n", + "# Calculate average loss across folds\n", + "avg_loss = np.mean(lr_losses, axis=0)\n", + "\n", + "plt.figure(figsize=(10, 6))\n", + "plt.plot(avg_loss, label='Logistic Regression Loss', color='purple')\n", + "plt.title('Average Logistic Regression Loss Curve (Across 5 Folds)')\n", + "plt.xlabel('Iteration')\n", + "plt.ylabel('Binary Cross-Entropy Loss')\n", + "plt.legend()\n", + "plt.grid(True, alpha=0.3)\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "# Feature importance\n", + "feature_importance = pd.DataFrame({'feature': feature_cols,'importance': model.feature_importances_}).sort_values('importance', ascending=False)\n", + "plt.figure(figsize=(10, 6))\n", + "plt.barh(feature_importance['feature'], feature_importance['importance'])\n", + "plt.xlabel('Importance')\n", + "plt.title('Feature Importance')\n", + "plt.gca().invert_yaxis()\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/398/Q1.ipynb b/submissions_extracted/398/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..70a288fdcd20b7afb416796a258ae90640131c7e --- /dev/null +++ b/submissions_extracted/398/Q1.ipynb @@ -0,0 +1,280 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q1-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import numpy as np\n", + "import matplotlib.pyplot as plt\n", + "import seaborn as sns\n", + "import kagglehub\n", + "import os\n", + "from tqdm import tqdm\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: /kaggle/input/q1-exam-data/Q1_data.csv\n", + "import pandas as pd\n", + "Q1_data = os.path.join(path, \"/kaggle/input/q1-exam-data/Q1_data.csv\")\n", + "df = pd.read_csv(Q1_data)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2:\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3:\n", + "df.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4:\n", + "df.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5:\n", + "def check_target_distribution(df, Delivery_Time):\n", + " df[Delivery_Time].hist(bins=30, edgecolor='black')\n", + "\n", + " plt.title(f\"Target Distribution ({Delivery_Time})\")\n", + " plt.xlabel(Delivery_Time)\n", + " plt.ylabel(\"Frequency\")\n", + " plt.grid(False)\n", + "\n", + " plt.show()\n", + "\n", + "check_target_distribution(df, \"Delivery_Time\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1:\n", + "df = df.drop(['Order_ID'], axis=1)\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2:\n", + "def check_missing_values(df):\n", + " missing_values = df.isnull().sum()\n", + " print(\"Missing Values per Column:\")\n", + " print(missing_values[missing_values > 0])\n", + " if missing_values.any():\n", + " print(\"\\nHandle Missing Values as needed.\")\n", + " else:\n", + " print(\"\\nNo Missing Values Found.\")\n", + "\n", + "check_missing_values(df)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "df.dropna(subset=['Weather','Traffic_Level','Time_of_Day','Courier_Experience_yrs'])" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3:\n", + "def check_duplicates(df):\n", + " duplicates = df.duplicated().sum()\n", + " print(f\"Number of Duplicate Samples: {duplicates}\")\n", + " if duplicates > 0:\n", + " print(\"Dropping Duplicates...\")\n", + " df.drop_duplicates(inplace=True)\n", + " print(\"Duplicates Dropped.\")\n", + " else:\n", + " print(\"No Duplicate Samples Found.\")\n", + "\n", + "check_duplicates(df)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4:\n", + "from sklearn.preprocessing import OneHotEncoder\n", + "categorical_cols = df.select_dtypes(include=[\"object\"]).columns\n", + "\n", + "print(\"Categorical Columns:\", list(categorical_cols))\n", + "\n", + "from sklearn.preprocessing import LabelEncoder\n", + "\n", + "label_encoders = {}\n", + "for col in categorical_cols:\n", + " le = LabelEncoder()\n", + " df[col] = le.fit_transform(df[col])\n", + " label_encoders[col] = le\n", + "\n", + "df" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5:\n", + "from sklearn.preprocessing import StandardScaler\n", + "\n", + "numerical_cols = df.select_dtypes(include=[\"int64\", \"float64\"]).columns.drop(\"Delivery_Time\") # DON'T SCALE THE TARGET\n", + "\n", + "scaler = StandardScaler()\n", + "df[numerical_cols] = scaler.fit_transform(df[numerical_cols])\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 6: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1:\n", + "X = df.drop(\"Delivery_Time\", axis=1).astype(float)\n", + "y = df['Delivery_Time'].astype(float)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5:\n", + "from sklearn.model_selection import StratifiedKFold\n", + "from sklearn.ensemble import RandomForestRegressor\n", + "from sklearn.metrics import mean_absolute_error\n", + "n_splits = 5 # K=5 Folds\n", + "\n", + "# Stratified 5-Fold Cross-Validation, shuffled\n", + "skf = StratifiedKFold(n_splits=n_splits, shuffle=True, random_state=42)\n", + "for fold_idx, (train_index, test_index) in enumerate(skf.split(X, y)):\n", + " print(f\"\\nFold {fold_idx + 1}/{n_splits}\")\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", + " scaler = StandardScaler()\n", + "\n", + "\n", + "model = RandomForestRegressor(n_estimators=100, max_depth=20, random_state=42, n_jobs=-1)\n", + "model.fit(X_train, y_train)\n", + "print(\"Model trained!\")\n", + "y_pred = model.predict(X_test)\n", + "mae = mean_absolute_error(y_test, y_pred)\n", + "print(f\"MAE: ${mae:,.2f}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/398/Q2.ipynb b/submissions_extracted/398/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..9e83e0059ed90ec949b908aa65cf5a4d478a6f40 --- /dev/null +++ b/submissions_extracted/398/Q2.ipynb @@ -0,0 +1,424 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q2-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import os\n", + "import pandas as pd\n", + "import numpy as np\n", + "from PIL import Image\n", + "from sklearn.model_selection import train_test_split\n", + "\n", + "# Load Labels\n", + "labels_df = pd.read_csv(os.path.join(path, \"labels.csv\"))\n", + "img_dir = os.path.join(path, \"images\")\n", + "\n", + "images = []\n", + "ages = []\n", + "\n", + "# Load Images and Resize\n", + "print(\"Loading images...\")\n", + "for index, row in labels_df.iterrows():\n", + " img_name = row.iloc[0]\n", + " age = row.iloc[1]\n", + " img_path = os.path.join(img_dir, img_name)\n", + "\n", + " if os.path.exists(img_path):\n", + " img = Image.open(img_path).convert('RGB')\n", + " img_array = np.array(img) / 255.0 # Normalize pixel values to [0, 1]\n", + " images.append(img_array)\n", + " ages.append(age)\n", + "\n", + "X = np.array(images)\n", + "y = np.array(ages)\n", + "\n", + "# Transpose image dimensions to match PyTorch format (N, C, H, W)\n", + "X = np.transpose(X, (0, 3, 1, 2))\n", + "\n", + "# Split Data\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n", + "\n", + "print(f\"X_train shape: {X_train.shape}\")\n", + "print(f\"X_test shape: {X_test.shape}\")\n", + "print(f\"y_train shape: {y_train.shape}\")\n", + "print(f\"y_test shape: {y_test.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 1. Convert Numpy arrays to PyTorch Tensors\n", + "from torch.utils.data import TensorDataset\n", + "from torch.utils.data import DataLoader\n", + "import torch\n", + "X_train = torch.tensor(X_train, dtype=torch.float32)\n", + "X_test = torch.tensor(X_test, dtype=torch.float32)\n", + "y_train = torch.tensor(y_train, dtype=torch.float32)\n", + "y_test = torch.tensor(y_test, dtype=torch.float32)\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 2. Create TensorDataset objects\n", + "\n", + "from torchvision.datasets import MNIST\n", + "from torchvision.transforms.functional import to_tensor\n", + "\n", + "# Training dataset\n", + "train_dataset = MNIST(\n", + " root='./datasets', # Dataset storage path\n", + " train=True, # Use training data\n", + " transform=to_tensor, # Convert images to tensors\n", + " download=True\n", + ")\n", + "\n", + "# Testing dataset\n", + "test_dataset = MNIST(\n", + " root='./datasets', # Dataset storage path\n", + " train=False, # Use test data\n", + " transform=to_tensor, # Convert images to tensors\n", + " download=True # Download if not available\n", + ")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 3. Create DataLoaders\n", + "from torch.utils.data import DataLoader\n", + "\n", + "# DataLoader for training data\n", + "train_loader = DataLoader(\n", + " train_dataset,#shuffle the dataset to get the samples for 32 batches\n", + " batch_size=32,\n", + " shuffle=True,\n", + " num_workers=2\n", + ")\n", + "# DataLoader for test/validation data\n", + "test_loader = DataLoader(\n", + " test_dataset,\n", + " batch_size=32,\n", + " shuffle=False,# we dont shuffle here cuz its the teest\n", + " num_workers=2\n", + ")\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 4. Print shape of one batch\n", + "\n", + "X_batch, y_batch = next(iter(train_loader))\n", + "print(f\"Training batch input shape: {X_batch.shape}\")\n", + "print(f\"Training batch labels shape: {y_batch.shape}\")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 5. Display sample images\n", + "import matplotlib.pyplot as plt\n", + "images, labels = next(iter(train_loader))\n", + "\n", + "# Display the first 6 images in the batch\n", + "plt.figure(figsize=(8, 4))\n", + "\n", + "for i in range(6):\n", + " plt.subplot(2, 3, i + 1)\n", + " plt.imshow(images[i].squeeze(), cmap='gray')\n", + " plt.title(f\"Label: {labels[i].item()}\")\n", + " plt.axis('off')\n", + "\n", + "plt.tight_layout()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1:\n", + "import torch.nn.functional as F\n", + "import torch.nn as nn\n", + "class NN4Layer(nn.Module):\n", + "\n", + " def __init__(self, input_dim, hidden_dim, output_dim):\n", + " super(NN4Layer, self).__init__()\n", + "\n", + " # First linear layer: input features -> hidden layer\n", + " self.layer1 = nn.Linear(input_dim, hidden_dim)\n", + "\n", + " # Second linear layer: hidden layer -> hidden layer\n", + " self.layer2 = nn.Linear(hidden_dim, hidden_dim)\n", + " self.layer3 = nn.Linear(hidden_dim, hidden_dim)\n", + "\n", + " # Output layer: hidden layer -> number of classes (logits)\n", + " self.layer4 = nn.Linear(hidden_dim, output_dim)\n", + "\n", + " # ReLU activation for non-linearity\n", + " self.relu = nn.ReLU()\n", + "\n", + " # Defines how input data flows through the network\n", + " def forward(self, x):\n", + " # First hidden layer\n", + " z1 = self.layer1(x)\n", + " a1 = self.relu(z1)\n", + "\n", + " # Second hidden layer\n", + " z2 = self.layer2(a1)\n", + " a2 = self.relu(z2)\n", + " z3=self.layer3(a2)\n", + " a3=self.relu(z3)\n", + "\n", + " # Output layer (raw scores / logits)\n", + " output = self.layer4(a3) # there is something missing here, remember? :)\n", + "\n", + " return output" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2:\n", + "def train_one_epoch(model, optimizer, criterion, train_loader, device):\n", + " # Set the model to training mode\n", + " model.train()\n", + "\n", + " running_loss = 0.0\n", + "\n", + " for X_batch, y_batch in train_loader:\n", + " # Move batch to the selected device we flattened x here to match what the model wants as inputs because thsi is in high dimn. and we want in lower we fl.\n", + " X_batch = X_batch.view(X_batch.size(0), -1).to(device)#basicaly were flattening the matrix into an array leaving the first one untouched\n", + " y_batch = y_batch.to(device)\n", + "\n", + " # Forward pass\n", + " outputs = model(X_batch) # shape: (batch_size, 10)\n", + " loss = criterion(outputs, y_batch)\n", + "\n", + " # Backward pass & optimization\n", + " optimizer.zero_grad() # Clear previous gradients\n", + " loss.backward() # Compute gradients\n", + " optimizer.step() # Update model parameters\n", + "\n", + " running_loss += loss.item()\n", + "\n", + " # Average loss over all batches\n", + " avg_loss = running_loss / len(train_loader)\n", + "\n", + " return avg_loss" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3:\n", + "def validate(model, criterion, test_loader, device):\n", + " # Set the model to evaluation mode\n", + " model.eval()\n", + "\n", + " running_loss = 0.0\n", + " correct = 0\n", + " total = 0\n", + "\n", + " with torch.no_grad():\n", + " for X_batch, y_batch in test_loader:\n", + " # Move data to device\n", + " X_batch = X_batch.view(X_batch.size(0), -1).to(device)\n", + " y_batch = y_batch.to(device)\n", + "\n", + " # Forward pass\n", + " outputs = model(X_batch) # shape: (batch_size, 10)\n", + " loss = criterion(outputs, y_batch)\n", + " running_loss += loss.item()\n", + "\n", + " # Apply Softmax to get probabilities\n", + " probabilities = F.softmax(outputs, dim=1)\n", + "\n", + " # Multiclass predictions\n", + " predicted = torch.argmax(probabilities, dim=1)\n", + "\n", + " # Accuracy calculation\n", + " correct += (predicted == y_batch).sum().item()\n", + " total += y_batch.size(0)\n", + "\n", + " avg_loss = running_loss / len(test_loader)\n", + " accuracy = correct / total\n", + "\n", + " return avg_loss, accuracy" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Define device, model, loss, optimizer:\n", + "from torch.optim import Adam\n", + "device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n", + "\n", + "# Model parameters\n", + "input_dim = 28 * 28 # MNIST images flattened\n", + "hidden_dim = 14 # Design choice\n", + "output_dim = 10 # Digits 0–9\n", + "\n", + "# Instantiate model\n", + "model = NN4Layer(input_dim, hidden_dim, output_dim).to(device)\n", + "\n", + "# Print the model architecture\n", + "print(\"Model Architecture:\\n\")\n", + "print(model)\n", + "\n", + "# Calculate the total number of trainable parameters\n", + "total_params = sum(p.numel() for p in model.parameters() if p.requires_grad)\n", + "print(f\"\\nTotal trainable parameters: {total_params}\")\n", + "num_epochs = 20\n", + "learning_rate = 0.001\n", + "\n", + "# Define criterion (loss function) - using CrossEntropyLoss as model now outputs logits\n", + "criterion = nn.CrossEntropyLoss()\n", + "# Define optimizer\n", + "optimizer = Adam(model.parameters(), learning_rate)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Start training for 20 epochs:\n", + "train_losses = []\n", + "val_losses = []\n", + "val_accuracies = []\n", + "\n", + "print('Starting Training...')\n", + "for epoch in range(num_epochs):\n", + " # Train one epoch\n", + " train_loss = train_one_epoch(model, optimizer, criterion, train_loader, device)\n", + "\n", + " # Validate\n", + " val_loss, val_accuracy = validate(model, criterion, test_loader, device)\n", + "\n", + " train_losses.append(train_loss)\n", + " val_losses.append(val_loss)\n", + " val_accuracies.append(val_accuracy)\n", + "\n", + " print(f'Epoch [{epoch+1}/{num_epochs}], Train Loss: {train_loss:.4f}, Val Loss: {val_loss:.4f}, Val Accuracy: {val_accuracy:.4f}')\n", + "\n", + "print('Training Complete!')" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "\n", + "plt.figure(figsize=(7, 5))\n", + "\n", + "plt.plot(train_losses, label='Train Loss')\n", + "plt.plot(val_losses, label='Validation Loss')\n", + "plt.title('Loss over Epochs')\n", + "plt.xlabel('Epoch')\n", + "plt.ylabel('Loss')\n", + "plt.legend()\n", + "\n", + "plt.tight_layout()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2 (Bonus): Write your code here:\n", + "model.eval()\n", + "# Get one batch from the test DataLoader\n", + "images, labels = next(iter(test_loader))\n", + "# Move images to device\n", + "images = images.to(device)\n", + "labels = labels.to(device)\n", + "\n", + "with torch.no_grad():\n", + " # Flatten images before passing to the model\n", + " outputs = model(images.view(images.size(0), -1))\n", + " predictions = torch.argmax(outputs, dim=1)\n", + "\n", + "# Move tensors back to CPU for plotting\n", + "images = images.cpu()\n", + "labels = labels.cpu()\n", + "predictions = predictions.cpu()\n", + "\n", + "# Plot first 6 predictions\n", + "plt.figure(figsize=(8, 4))\n", + "for i in range(6):\n", + " plt.subplot(2, 3, i + 1)\n", + " plt.imshow(images[i].squeeze(), cmap='gray')\n", + " plt.title(f\"True: {labels[i]} | Pred: {predictions[i]}\")\n", + " plt.axis('off')\n", + "\n", + "plt.tight_layout()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/398/Q3.ipynb b/submissions_extracted/398/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..df96ac6d9c3aa5760f5706b11137afd5400f0e6b --- /dev/null +++ b/submissions_extracted/398/Q3.ipynb @@ -0,0 +1,213 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "\n", + "\n", + "# Download latest version\n", + "\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q3-exam-data\")\n", + "\n", + "\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "import os\n", + "import pandas as pd\n", + "Q3_data = os.path.join(path, \"/kaggle/input/q3-exam-data/Q3_data.csv\")\n", + "df = pd.read_csv(Q3_data)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "df.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "df.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "missing_percentage = (df.isnull().sum() / len(df)) * 100\n", + "missing_data = pd.DataFrame({\n", + " 'Column': missing_percentage.index,\n", + " 'Missing_Percentage': missing_percentage.values\n", + "})\n", + "missing_data = missing_data[missing_data['Missing_Percentage'] > 0].sort_values('Missing_Percentage', ascending=False)\n", + "\n", + "print(\"Missing Data Analysis:\")\n", + "missing_data.head(10)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "cols = ['D_87', 'D_88', 'B_39', 'D_110', 'D_111', 'D_108', 'B_42', 'D_73', 'D_135','D_136']\n", + "df_clean = df[cols].copy()\n", + "\n", + "# Drop rows where target (price) or key features are missing - can't predict without them\n", + "print(f\"Before: {df_clean.shape}\")\n", + "df_clean = df_clean['D_87'].fillna(df['D_87'].mode()[0])\n", + "\n", + "df_clean = df_clean['B_39'].fillna(df['B_39'].median()[0])\n", + "df_clean = df_clean['D_110'].fillna(df['D_110'].mode()[0])\n", + "df_clean = df_clean['D_111'].fillna(df['D_111'].mode()[0])\n", + "print(f\"After dropping missing price/year/odometer: {df_clean.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "def check_duplicates(df):\n", + " duplicates = df.duplicated().sum()\n", + " print(f\"Number of Duplicate Samples: {duplicates}\")\n", + " if duplicates > 0:\n", + " print(\"Dropping Duplicates...\")\n", + " df.drop_duplicates(inplace=True)\n", + " print(\"Duplicates Dropped.\")\n", + " else:\n", + " print(\"No Duplicate Samples Found.\")\n", + "\n", + "check_duplicates(df)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "from sklearn.preprocessing import LabelEncoder\n", + "categorical_cols = [df]\n", + "for col in categorical_cols:\n", + " le = LabelEncoder()\n", + " df[col] = le.fit_transform(df[col].astype(str))\n", + "\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/399/Q1.ipynb b/submissions_extracted/399/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..e31235f64b11880a636c51f4a65f4d0483bf2f8f --- /dev/null +++ b/submissions_extracted/399/Q1.ipynb @@ -0,0 +1,327 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "import numpy as np\n", + "import pandas as pd\n", + "import matplotlib.pyplot as plt\n", + "import seaborn as sns\n", + "import os\n", + "\n", + "from sklearn.model_selection import train_test_split, KFold, cross_val_score\n", + "from sklearn.preprocessing import StandardScaler, OneHotEncoder, LabelEncoder, PolynomialFeatures\n", + "from sklearn.compose import ColumnTransformer\n", + "from sklearn.pipeline import Pipeline\n", + "from sklearn.linear_model import LinearRegression\n", + "from sklearn.metrics import mean_absolute_error, mean_squared_error, r2_score\n", + "\n", + "from sklearn.ensemble import RandomForestRegressor\n", + "\n", + "import warnings\n", + "\n", + "warnings.filterwarnings('ignore')\n", + "\n", + "plt.rcParams['figure.figsize'] = (8, 5)\n", + "plt.rcParams['axes.grid'] = True\n", + "\n", + "print(\"Libraries imported successfully.\")\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q1-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "csv_path = os.path.join(path, \"Q1_data.csv\")\n", + "\n", + "df = pd.read_csv(csv_path)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "df.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "df.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "def check_target_distribution(df, target_column):\n", + " df[target_column].hist(bins=30, edgecolor='black')\n", + "\n", + " plt.title(f\"Target Distribution ({target_column})\")\n", + " plt.xlabel(target_column)\n", + " plt.ylabel(\"Frequency\")\n", + " plt.grid(False)\n", + "\n", + " plt.show()\n", + "\n", + "check_target_distribution(df, \"Delivery_Time\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "df = df.drop(columns=\"Order_ID\", axis=1)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "def check_missing_values(df):\n", + " missing_values = df.isnull().sum()\n", + " print(\"Missing Values per Column:\")\n", + " print(missing_values[missing_values > 0])\n", + " if missing_values.any():\n", + " print(\"\\nHandle Missing Values as needed.\")\n", + " else:\n", + " print(\"\\nNo Missing Values Found.\")\n", + "\n", + "check_missing_values(df)\n", + "\n", + "numeric_cols = df.select_dtypes(include=['int64', 'float64']).columns.tolist()\n", + "categorical_cols = df.select_dtypes(include=['object']).columns.tolist()\n", + "\n", + "print(\"\\nNumeric columns:\", numeric_cols)\n", + "print(\"Categorical columns:\", categorical_cols)\n", + "\n", + "for col in numeric_cols:\n", + " df[col] = df[col].fillna(df[col].mean())\n", + "\n", + "for col in categorical_cols:\n", + " df[col] = df[col].fillna(df[col].mode()[0])\n", + "\n", + "print(\"Missing values handled.\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "def check_duplicates(df):\n", + " duplicates = df.duplicated().sum()\n", + " print(f\"Number of Duplicate Samples: {duplicates}\")\n", + " if duplicates > 0:\n", + " print(\"Dropping Duplicates...\")\n", + " df.drop_duplicates(inplace=True)\n", + " print(\"Duplicates Dropped.\")\n", + " else:\n", + " print(\"No Duplicate Samples Found.\")\n", + "\n", + "check_duplicates(df)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "\n", + "le = LabelEncoder()\n", + "df['Weather'] = le.fit_transform(df['Weather'])\n", + "df['Traffic_Level'] = le.fit_transform(df['Traffic_Level'])\n", + "df['Time_of_Day'] = le.fit_transform(df['Time_of_Day'])\n", + "df['Vehicle_Type'] = le.fit_transform(df['Vehicle_Type'])" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "\n", + "from sklearn.preprocessing import MinMaxScaler\n", + "\n", + "features = df.columns.drop(\"Delivery_Time\") # DON'T SCALE THE TARGET\n", + "\n", + "scaler = MinMaxScaler()\n", + "df[features] = scaler.fit_transform(df[features])\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "\n", + "# Task 6: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "TARGET_COL = 'Delivery_Time'\n", + "\n", + "df.dropna(subset=['Delivery_Time'])\n", + "X = df.drop(columns=[TARGET_COL])\n", + "y = df[TARGET_COL]\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import pandas as pd\n", + "import numpy as np\n", + "import matplotlib.pyplot as plt\n", + "import seaborn as sns\n", + "from sklearn.model_selection import train_test_split\n", + "from sklearn.preprocessing import StandardScaler, OneHotEncoder\n", + "from sklearn.impute import SimpleImputer\n", + "from sklearn.compose import ColumnTransformer\n", + "from sklearn.pipeline import Pipeline\n", + "from sklearn.metrics import mean_squared_error, r2_score\n", + "from sklearn.linear_model import LinearRegression, Ridge, Lasso\n", + "from sklearn.tree import DecisionTreeRegressor\n", + "from sklearn.ensemble import RandomForestRegressor\n", + "from xgboost import XGBRegressor\n", + "\n", + "numeric_features = X.select_dtypes(include=['int64', 'float64']).columns\n", + "categorical_features = X.select_dtypes(include=['object', 'category']).columns\n", + "\n", + "numeric_transformer = Pipeline(steps=[\n", + " ('imputer', SimpleImputer(strategy='mean')),\n", + " ('scaler', StandardScaler())\n", + "])\n", + "\n", + "categorical_transformer = Pipeline(steps=[\n", + " ('imputer', SimpleImputer(strategy='constant', fill_value='missing')),\n", + " ('onehot', OneHotEncoder(handle_unknown='ignore'))\n", + "])\n", + "\n", + "preprocessor = ColumnTransformer(\n", + " transformers=[\n", + " ('num', numeric_transformer, numeric_features),\n", + " ('cat', categorical_transformer, categorical_features)\n", + " ])\n", + "\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n", + "\n", + "# 4️⃣ Define Models\n", + "models = {\n", + " \"Linear Regression\": LinearRegression(),\n", + " \"Ridge\": Ridge(),\n", + " \"Lasso\": Lasso(),\n", + " \"Decision Tree\": DecisionTreeRegressor(),\n", + " \"Random Forest\": RandomForestRegressor(),\n", + " \"XGBoost\": XGBRegressor(),\n", + "}\n", + "\n", + "# 5️⃣ Training & Evaluation Loop\n", + "for name, model in models.items():\n", + " reg = Pipeline(steps=[('preprocessor', preprocessor),\n", + " ('regressor', model)])\n", + "\n", + " reg.fit(X_train, y_train)\n", + " y_pred = reg.predict(X_test)\n", + "\n", + " mse = mean_squared_error(y_test, y_pred)\n", + " r2 = r2_score(y_test, y_pred)\n", + "\n", + " print(f\"{name} -> MSE: {mse:.2f}, R2: {r2:.4f}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "plt.scatter(y_test, y_pred)\n", + "plt.plot([y_test.min(), y_test.max()], [y_test.min(), y_test.max()], 'r--')\n", + "plt.title('Actual vs Predicted')\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "def check_target_distribution(df, target_column):\n", + " df[target_column].hist(bins=30, edgecolor='black')\n", + "\n", + " plt.title(f\"Target Distribution ({target_column})\")\n", + " plt.xlabel(target_column)\n", + " plt.ylabel(\"Frequency\")\n", + " plt.grid(False)\n", + "\n", + " plt.show()\n", + "\n", + "check_target_distribution(df, \"Delivery_Time\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/399/Q2.ipynb b/submissions_extracted/399/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..996087787524e3a72eba1567a28727bfea37f834 --- /dev/null +++ b/submissions_extracted/399/Q2.ipynb @@ -0,0 +1,395 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q2-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import os\n", + "import pandas as pd\n", + "import numpy as np\n", + "from PIL import Image\n", + "from sklearn.model_selection import train_test_split\n", + "import torch\n", + "import torch.nn as nn\n", + "from torchvision.datasets import MNIST\n", + "from torch.utils.data import DataLoader\n", + "from torch.optim import Adam\n", + "from torchvision.transforms.functional import to_tensor\n", + "import torch.nn.functional as F\n", + "import matplotlib.pyplot as plt\n", + "\n", + "# Load Labels\n", + "labels_df = pd.read_csv(os.path.join(path, \"labels.csv\"))\n", + "img_dir = os.path.join(path, \"images\")\n", + "\n", + "images = []\n", + "ages = []\n", + "\n", + "# Load Images and Resize\n", + "print(\"Loading images...\")\n", + "for index, row in labels_df.iterrows():\n", + " img_name = row.iloc[0]\n", + " age = row.iloc[1]\n", + " img_path = os.path.join(img_dir, img_name)\n", + "\n", + " if os.path.exists(img_path):\n", + " img = Image.open(img_path).convert('RGB')\n", + " img_array = np.array(img) / 255.0 # Normalize pixel values to [0, 1]\n", + " images.append(img_array)\n", + " ages.append(age)\n", + "\n", + "X = np.array(images)\n", + "y = np.array(ages)\n", + "\n", + "# Transpose image dimensions to match PyTorch format (N, C, H, W)\n", + "X = np.transpose(X, (0, 3, 1, 2))\n", + "\n", + "# Split Data\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n", + "\n", + "print(f\"X_train shape: {X_train.shape}\")\n", + "print(f\"X_test shape: {X_test.shape}\")\n", + "print(f\"y_train shape: {y_train.shape}\")\n", + "print(f\"y_test shape: {y_test.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "\n", + "# Training dataset\n", + "train_dataset = MNIST(\n", + " root='labels.csv', # Dataset storage path\n", + " train=True, # Use training data\n", + " transform=to_tensor, # Convert images to tensors\n", + " download=True # Download if not available\n", + ")\n", + "\n", + "# Testing dataset\n", + "test_dataset = MNIST(\n", + " root='labels.csv', # Dataset storage path\n", + " train=False, # Use test data\n", + " transform=to_tensor, # Convert images to tensors\n", + " download=True # Download if not available\n", + ")\n", + "# print one sample from the dataset\n", + "# Each sample consists of an image tensor and its label\n", + "sample_image, sample_label = train_dataset[0]\n", + "\n", + "print(f\"\\n Image shape: {sample_image.shape}\") # (1, 28, 28)\n", + "print(f\"Label: {sample_label}\")\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# DataLoader for training data\n", + "train_loader = DataLoader(\n", + " train_dataset,\n", + " batch_size=32,\n", + " shuffle=True,\n", + " num_workers=2\n", + ")\n", + "# DataLoader for test/validation data\n", + "test_loader = DataLoader(\n", + " test_dataset,\n", + " batch_size=32,\n", + " shuffle=False,\n", + " num_workers=2\n", + ")\n", + "# Get the first batch from the training DataLoader\n", + "X_batch, y_batch = next(iter(train_loader))\n", + "print(f\"Training batch input shape: {X_batch.shape}\")\n", + "print(f\"Training batch labels shape: {y_batch.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Get one batch of images and labels\n", + "images, labels = next(iter(train_loader))\n", + "\n", + "# Display the first 6 images in the batch\n", + "plt.figure(figsize=(8, 4))\n", + "\n", + "for i in range(6):\n", + " plt.subplot(2, 3, i + 1)\n", + " plt.imshow(images[i].squeeze(), cmap='gray')\n", + " plt.title(f\"Label: {labels[i].item()}\")\n", + " plt.axis('off')\n", + "\n", + "plt.tight_layout()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 5. Display sample images\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "class NN3Layer(nn.Module):\n", + "\n", + " def __init__(self, input_dim, hidden_dim, output_dim):\n", + " super(NN3Layer, self).__init__()\n", + "\n", + " # First linear layer: input features -> hidden layer\n", + " self.layer1 = nn.Linear(input_dim, hidden_dim)\n", + "\n", + " # Second linear layer: hidden layer -> hidden layer\n", + " self.layer2 = nn.Linear(hidden_dim, hidden_dim)\n", + "\n", + " # Output layer: hidden layer -> number of classes (logits)\n", + " self.layer3 = nn.Linear(hidden_dim, output_dim)\n", + "\n", + " # ReLU activation for non-linearity\n", + " self.relu = nn.ReLU()\n", + "\n", + " # Defines how input data flows through the network\n", + " def forward(self, x):\n", + " # First hidden layer\n", + " z1 = self.layer1(x)\n", + " a1 = self.relu(z1)\n", + "\n", + " # Second hidden layer\n", + " z2 = self.layer2(a1)\n", + " a2 = self.relu(z2)\n", + "\n", + " # Output layer (raw scores / logits)\n", + " output = self.layer3(a2) # there is something missing here, remember? :)\n", + "\n", + " return output\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "def train_one_epoch(model, optimizer, criterion, train_loader, device):\n", + " # Set the model to training mode\n", + " model.train()\n", + "\n", + " running_loss = 0.0\n", + "\n", + " for X_batch, y_batch in train_loader:\n", + " # Move batch to the selected device\n", + " X_batch = X_batch.view(X_batch.size(0), -1).to(device)\n", + " y_batch = y_batch.to(device)\n", + "\n", + " # Forward pass\n", + " outputs = model(X_batch) # shape: (batch_size, 10)\n", + " loss = criterion(outputs, y_batch)\n", + "\n", + " # Backward pass & optimization\n", + " optimizer.zero_grad() # Clear previous gradients\n", + " loss.backward() # Compute gradients\n", + " optimizer.step() # Update model parameters\n", + "\n", + " running_loss += loss.item()\n", + "\n", + " # Average loss over all batches\n", + " avg_loss = running_loss / len(train_loader)\n", + "\n", + " return avg_loss" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "def validate(model, criterion, test_loader, device):\n", + " # Set the model to evaluation mode\n", + " model.eval()\n", + "\n", + " running_loss = 0.0\n", + " correct = 0\n", + " total = 0\n", + "\n", + " with torch.no_grad():\n", + " for X_batch, y_batch in test_loader:\n", + " # Move data to device\n", + " X_batch = X_batch.view(X_batch.size(0), -1).to(device)\n", + " y_batch = y_batch.to(device)\n", + "\n", + " # Forward pass\n", + " outputs = model(X_batch) # shape: (batch_size, 10)\n", + " loss = criterion(outputs, y_batch)\n", + " running_loss += loss.item()\n", + "\n", + " # Apply Softmax to get probabilities\n", + " probabilities = F.softmax(outputs, dim=1)\n", + "\n", + " # Multiclass predictions\n", + " predicted = torch.argmax(probabilities, dim=1)\n", + "\n", + " # Accuracy calculation\n", + " correct += (predicted == y_batch).sum().item()\n", + " total += y_batch.size(0)\n", + "\n", + " avg_loss = running_loss / len(test_loader)\n", + " accuracy = correct / total\n", + "\n", + " return avg_loss, accuracy\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Device setup\n", + "device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n", + "\n", + "# Model parameters\n", + "input_dim = 28 * 28 # MNIST images flattened\n", + "hidden_dim = 14 # Design choice\n", + "output_dim = 10 # Digits 0–9\n", + "\n", + "# Instantiate model\n", + "model = NN3Layer(input_dim, hidden_dim, output_dim).to(device)\n", + "\n", + "# Print the model architecture\n", + "print(\"Model Architecture:\\n\")\n", + "print(model)\n", + "\n", + "# Calculate the total number of trainable parameters\n", + "total_params = sum(p.numel() for p in model.parameters() if p.requires_grad)\n", + "print(f\"\\nTotal trainable parameters: {total_params}\")\n", + "\n", + "num_epochs = 10\n", + "learning_rate = 0.001\n", + "\n", + "# Define criterion (loss function) - using CrossEntropyLoss as model now outputs logits\n", + "criterion = nn.CrossEntropyLoss()\n", + "# Define optimizer\n", + "optimizer = Adam(model.parameters(), learning_rate)\n", + "\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Run Training\n", + "train_losses = []\n", + "val_losses = []\n", + "val_accuracies = []\n", + "\n", + "print('Starting Training...')\n", + "for epoch in range(num_epochs):\n", + " # Train one epoch\n", + " train_loss = train_one_epoch(model, optimizer, criterion, train_loader, device)\n", + "\n", + " # Validate\n", + " val_loss, val_accuracy = validate(model, criterion, test_loader, device)\n", + "\n", + " train_losses.append(train_loss)\n", + " val_losses.append(val_loss)\n", + " val_accuracies.append(val_accuracy)\n", + "\n", + " print(f'Epoch [{epoch+1}/{num_epochs}], Train Loss: {train_loss:.4f}, Val Loss: {val_loss:.4f}, Val Accuracy: {val_accuracy:.4f}')\n", + "\n", + "print('Training Complete!')" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Plotting results\n", + "plt.figure(figsize=(7, 5))\n", + "\n", + "plt.plot(train_losses, label='Train Loss')\n", + "plt.plot(val_losses, label='Validation Loss')\n", + "plt.title('Loss over Epochs')\n", + "plt.xlabel('Epoch')\n", + "plt.ylabel('Loss')\n", + "plt.legend()\n", + "\n", + "plt.tight_layout()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2 (Bonus): Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/399/Q3.ipynb b/submissions_extracted/399/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..722b032d511f81150322677b73a35fe08acb6653 --- /dev/null +++ b/submissions_extracted/399/Q3.ipynb @@ -0,0 +1,330 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "import numpy as np\n", + "import pandas as pd\n", + "import matplotlib.pyplot as plt\n", + "import seaborn as sns\n", + "import os\n", + "\n", + "from sklearn.model_selection import train_test_split, KFold, cross_val_score\n", + "from sklearn.preprocessing import StandardScaler, OneHotEncoder, LabelEncoder, PolynomialFeatures\n", + "from sklearn.compose import ColumnTransformer\n", + "from sklearn.pipeline import Pipeline\n", + "from sklearn.linear_model import LinearRegression\n", + "from sklearn.metrics import mean_absolute_error, mean_squared_error, r2_score\n", + "\n", + "from sklearn.ensemble import RandomForestRegressor\n", + "\n", + "import warnings\n", + "\n", + "warnings.filterwarnings('ignore')\n", + "\n", + "plt.rcParams['figure.figsize'] = (8, 5)\n", + "plt.rcParams['axes.grid'] = True\n", + "\n", + "print(\"Libraries imported successfully.\")\n", + "# Download latest version\n", + "\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q3-exam-data\")\n", + "\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "csv_path = os.path.join(path, \"Q3_data.csv\")\n", + "\n", + "df = pd.read_csv(csv_path)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "df.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "df.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "def check_missing_values(df):\n", + " missing_values = df.isnull().sum()\n", + " print(\"Missing Values per Column:\")\n", + " print(missing_values[missing_values > 0])\n", + " if missing_values.any():\n", + " print(\"\\nHandle Missing Values as needed.\")\n", + " else:\n", + " print(\"\\nNo Missing Values Found.\")\n", + "\n", + "check_missing_values(df)\n", + "\n", + "numeric_cols = df.select_dtypes(include=['int64', 'float64']).columns.tolist()\n", + "categorical_cols = df.select_dtypes(include=['object']).columns.tolist()\n", + "\n", + "print(\"\\nNumeric columns:\", numeric_cols)\n", + "print(\"Categorical columns:\", categorical_cols)\n", + "\n", + "for col in numeric_cols:\n", + " df[col] = df[col].fillna(df[col].mean())\n", + "\n", + "for col in categorical_cols:\n", + " df[col] = df[col].fillna(df[col].mode()[0])\n", + "\n", + "print(\"Missing values handled.\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "def check_duplicates(df):\n", + " duplicates = df.duplicated().sum()\n", + " print(f\"Number of Duplicate Samples: {duplicates}\")\n", + " if duplicates > 0:\n", + " print(\"Dropping Duplicates...\")\n", + " df.drop_duplicates(inplace=True)\n", + " print(\"Duplicates Dropped.\")\n", + " else:\n", + " print(\"No Duplicate Samples Found.\")\n", + "\n", + "check_duplicates(df)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "from sklearn.preprocessing import MinMaxScaler\n", + "features = df.columns\n", + "scaler = MinMaxScaler()\n", + "df[features] = scaler.fit_transform(df[features])\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + " df = df.copy()\n", + " y = df[Target]\n", + " if feature_cols is None:\n", + " X = df.drop(columns=[Target])\n", + " else:\n", + " X = df[feature_cols]\n", + "\n", + " if encode_target:\n", + " le = LabelEncoder()\n", + " y_enc = le.fit_transform(y)\n", + " y = pd.Series(y_enc, index=y.index, name=Target)\n", + " print(\"Target encoded with LabelEncoder.\")\n", + " return X, y, le\n", + "\n", + " print(\"X shape:\", X.shape, \"| y shape:\", y.shape)\n", + " return X, y, None\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import numpy as np\n", + "import pandas as pd\n", + "import matplotlib.pyplot as plt\n", + "\n", + "from sklearn.model_selection import train_test_split, StratifiedKFold\n", + "from sklearn.preprocessing import StandardScaler, LabelEncoder\n", + "from sklearn.metrics import (\n", + " accuracy_score,\n", + " precision_score,\n", + " recall_score,\n", + " f1_score,\n", + " classification_report,\n", + " confusion_matrix,\n", + " roc_auc_score,\n", + " roc_curve\n", + ")\n", + "from sklearn.linear_model import LogisticRegression\n", + "from sklearn.neighbors import KNeighborsClassifier\n", + "from sklearn.svm import SVC\n", + "from sklearn.tree import DecisionTreeClassifier\n", + "from sklearn.ensemble import RandomForestClassifier\n", + "\n", + "def split_and_scale_classification(\n", + " X,\n", + " y,\n", + " test_size=0.2,\n", + " random_state=42,\n", + " scale=True\n", + "):\n", + " # تقسم الداتا الى Train/Test مع stratify على y\n", + " X_train, X_test, y_train, y_test = train_test_split(\n", + " X, y, test_size=test_size, random_state=random_state, stratify=y\n", + " )\n", + "\n", + " if scale:\n", + " scaler = StandardScaler()\n", + " X_train_sc = scaler.fit_transform(X_train)\n", + " X_test_sc = scaler.transform(X_test)\n", + " else:\n", + " scaler = None\n", + " X_train_sc = X_train.values\n", + " X_test_sc = X_test.values\n", + "\n", + " print(\"Train size:\", X_train.shape[0], \"| Test size:\", X_test.shape[0])\n", + " return X_train, X_test, y_train, y_test, X_train_sc, X_test_sc, scaler\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "def classification_metrics(y_true, y_pred, average=\"binary\", title=\"Classification metrics\"):\n", + "\n", + " prec = precision_score(y_true, y_pred, average=average, zero_division=0)\n", + " rec = recall_score(y_true, y_pred, average=average, zero_division=0)\n", + " f1 = f1_score(y_true, y_pred, average=average, zero_division=0)\n", + " print(\"\\n\" + title)\n", + " print(\"Accuracy :\", acc)\n", + " print(\"Precision:\", prec)\n", + " print(\"Recall :\", rec)\n", + " print(\"F1-score :\", f1)\n", + " return acc, prec, rec, f1\n", + "\n", + "def print_classification_report(y_true, y_pred):\n", + " print(\"\\nClassification Report:\")\n", + " print(classification_report(y_true, y_pred, zero_division=0))\n", + "\n", + "def plot_confusion_matrix_custom(y_true, y_pred, normalize=False):\n", + " cm = confusion_matrix(y_true, y_pred)\n", + " if normalize:\n", + " cm = cm.astype(\"float\") / cm.sum(axis=1, keepdims=True)\n", + " plt.figure(figsize=(4, 4))\n", + " plt.imshow(cm, cmap=\"Blues\")\n", + " plt.title(\"Confusion Matrix\")\n", + " plt.colorbar()\n", + " tick_marks = np.arange(len(np.unique(y_true)))\n", + " plt.xticks(tick_marks, tick_marks)\n", + " plt.yticks(tick_marks, tick_marks)\n", + " thresh = cm.max() / 2.0\n", + " for i in range(cm.shape[0]):\n", + " for j in range(cm.shape[1]):\n", + " plt.text(\n", + " j, i, f\"{cm[i, j]:.2f}\" if normalize else str(cm[i, j]),\n", + " ha=\"center\", va=\"center\",\n", + " color=\"white\" if cm[i, j] > thresh else \"black\"\n", + " )\n", + " plt.xlabel(\"Predicted\")\n", + " plt.ylabel(\"True\")\n", + " plt.tight_layout()\n", + " plt.show()\n", + "\n", + "def plot_roc_curve_binary(y_true, y_scores):\n", + " fpr, tpr, thresholds = roc_curve(y_true, y_scores)\n", + " auc = roc_auc_score(y_true, y_scores)\n", + " plt.figure(figsize=(5, 4))\n", + " plt.plot(fpr, tpr, label=f\"ROC curve (AUC = {auc:.3f})\")\n", + " plt.plot([0, 1], [0, 1], linestyle=\"--\", label=\"Random\")\n", + " plt.xlabel(\"False Positive Rate\")\n", + " plt.ylabel(\"True Positive Rate\")\n", + " plt.title(\"ROC Curve (Binary)\")\n", + " plt.legend()\n", + " plt.grid(True)\n", + " plt.show()\n", + " print(\"AUC:\", auc)\n", + " return fpr, tpr, thresholds, auc" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/4/Q1.ipynb b/submissions_extracted/4/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..5e9d0ac4a7b7eca60cf73011d2b4202a03b135d9 --- /dev/null +++ b/submissions_extracted/4/Q1.ipynb @@ -0,0 +1,328 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q1-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "\n", + "import numpy as np\n", + "import pandas as pd\n", + "import matplotlib.pyplot as plt\n", + "import os\n", + "import kagglehub\n", + "\n", + "from sklearn.model_selection import train_test_split, StratifiedKFold, cross_val_score\n", + "from sklearn.preprocessing import StandardScaler, LabelEncoder\n", + "from sklearn.ensemble import RandomForestClassifier\n", + "from sklearn.metrics import classification_report, confusion_matrix, accuracy_score\n", + "\n", + "import warnings\n", + "warnings.filterwarnings('ignore')" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "import pandas as pd\n", + "import numpy as np\n", + "import matplotlib.pyplot as plt\n", + "import seaborn as sns\n", + "from sklearn.model_selection import train_test_split, KFold, cross_val_score\n", + "from sklearn.preprocessing import LabelEncoder, OneHotEncoder, StandardScaler\n", + "from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score, confusion_matrix\n", + "from sklearn.linear_model import LogisticRegression\n", + "from sklearn.tree import DecisionTreeClassifier\n", + "from sklearn.ensemble import RandomForestClassifier\n", + "from sklearn.svm import SVC\n", + "\n", + "print(\"Libraries imported successfully.\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "csv_file_path = os.path.join(path, 'Q1_data.csv')\n", + "\n", + "df = pd.read_csv(csv_file_path)\n", + "\n", + "print(f\"Shape: {df.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "df.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "df.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "plt.figure(figsize=(10, 5))\n", + "plt.hist(df['Delivery_Time'].dropna(), bins=30, edgecolor='black')\n", + "plt.title('deliverytime')\n", + "plt.xlabel('delivery time')\n", + "plt.ylabel('Frequency')\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "df.dropna(subset=['Order_ID'])" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "def check_missing_values(df):\n", + "\n", + " missing_values = df.isnull().sum()\n", + "\n", + " print(\"Missing Values per Column:\")\n", + " print(missing_values[missing_values > 0])" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "def check_duplicates(df):\n", + " duplicates = df.duplicated().sum()\n", + "\n", + " print(f\"Number of Duplicate Samples: {duplicates}\")\n", + " if duplicates > 0:\n", + " print(\"Dropping Duplicates...\")\n", + " df.drop_duplicates(inplace=True)\n", + " print(\"Duplicates Dropped.\")\n", + " else:\n", + " print(\"No Duplicate Samples Found.\")\n", + "\n", + "check_duplicates(df)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "def one_hot_encode(y, num_classes):\n", + " y = np.array(y)\n", + " m = len(y)\n", + " one_hot = np.zeros((m, num_classes))\n", + "\n", + " for i in range(m):\n", + " class_label = int(y[i])\n", + "\n", + " one_hot[i, class_label] = 1\n", + "\n", + " return one_hot" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "from sklearn.preprocessing import StandardScaler\n", + "\n", + "numerical_cols = df.select_dtypes(include=[\"int64\", \"float64\"]).columns.drop(\"Delivery_Time\")\n", + "\n", + "scaler = StandardScaler()\n", + "df[numerical_cols] = scaler.fit_transform(df[numerical_cols])\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 6: Write your code here:\n", + "def check_target_imbalance(df, target_column):\n", + " print(\"Target Distribution:\")\n", + "\n", + " df[target_column].hist()\n", + " plt.show()\n", + "\n", + "check_target_imbalance(df, \"Delivery_Time\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "print(\"Separating target variable and features...\")\n", + "X = df.drop(\"Delivery_Time\", axis=1)\n", + "y = df[\"Delivery_Time\"]\n", + "print(\"Applying Label Encoding to target variable 'y'...\")\n", + "label_encoder = LabelEncoder()\n", + "y_encoded = label_encoder.fit_transform(y)\n", + "\n", + "print(\"Applying One-Hot Encoding to feature DataFrame 'X'...\")\n", + "onehot_encoder = OneHotEncoder(handle_unknown='ignore', sparse_output=False)\n", + "X_encoded = pd.DataFrame(onehot_encoder.fit_transform(X), columns=onehot_encoder.get_feature_names_out(X.columns))\n", + "print(\"Splitting data into training and testing sets...\")\n", + "X_train, X_test, y_train, y_test = train_test_split(X_encoded, y_encoded, test_size=0.3, random_state=42)\n", + "\n", + "print(\"Data split successful.\")\n", + "print(f\"Shape of X_train: {X_train.shape}\")\n", + "print(f\"Shape of X_test: {X_test.shape}\")\n", + "print(f\"Shape of y_train: {y_train.shape}\")\n", + "print(f\"Shape of y_test: {y_test.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:\n", + "2\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42, stratify=y)\n", + "print(f\"Train: {X_train.shape}, Test: {X_test.shape}\")\n", + "print(f\"Legendary in train: {y_train.sum()}, in test: {y_test.sum()}\")\n", + "3\n", + "model = RandomForestClassifier(n_estimators=100, max_depth=15,\n", + " class_weight='balanced', random_state=42)\n", + "model.fit(X_train_scaled, y_train)\n", + "print(\"Model trained!\")\n", + "4\n", + "\n", + "5" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "importance = pd.DataFrame({\n", + " 'feature': feature_cols,\n", + " 'importance': model.feature_importances_\n", + "}).sort_values('importance', ascending=False)\n", + "\n", + "plt.figure(figsize=(10, 6))\n", + "plt.barh(importance['feature'], importance['importance'], color='purple')\n", + "plt.xlabel('Importance')\n", + "plt.title('Feature Importance')\n", + "plt.gca().invert_yaxis()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "# Plotting results\n", + "plt.figure(figsize=(7, 5))\n", + "\n", + "plt.plot(train_losses, label='Train Loss')\n", + "plt.plot(val_losses, label='Validation Loss')\n", + "plt.title('Loss over Epochs')\n", + "plt.xlabel('Epoch')\n", + "plt.ylabel('Loss')\n", + "plt.legend()\n", + "\n", + "plt.tight_layout()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/4/Q2.ipynb b/submissions_extracted/4/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..f13633fb485c71725d2b74e3326cecceb744caea --- /dev/null +++ b/submissions_extracted/4/Q2.ipynb @@ -0,0 +1,394 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import torch\n", + "import torch.nn as nn\n", + "from torchvision.datasets import MNIST\n", + "from torch.utils.data import DataLoader\n", + "from torch.optim import Adam\n", + "from torchvision.transforms.functional import to_tensor\n", + "import torch.nn.functional as F\n", + "import matplotlib.pyplot as plt" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "import pandas as pd\n", + "import torch\n", + "import torch.nn as nn\n", + "from torch.optim import AdamW\n", + "import matplotlib.pyplot as plt\n", + "import torch.nn.functional as F\n", + "from torch.utils.data import DataLoader, TensorDataset\n", + "from sklearn.model_selection import train_test_split\n", + "from sklearn.preprocessing import StandardScaler, LabelEncoder" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q2-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import os\n", + "import pandas as pd\n", + "import numpy as np\n", + "from PIL import Image\n", + "from sklearn.model_selection import train_test_split\n", + "\n", + "# Load Labels\n", + "labels_df = pd.read_csv(os.path.join(path, \"labels.csv\"))\n", + "img_dir = os.path.join(path, \"images\")\n", + "\n", + "images = []\n", + "ages = []\n", + "\n", + "# Load Images and Resize\n", + "print(\"Loading images...\")\n", + "for index, row in labels_df.iterrows():\n", + " img_name = row.iloc[0]\n", + " age = row.iloc[1]\n", + " img_path = os.path.join(img_dir, img_name)\n", + "\n", + " if os.path.exists(img_path):\n", + " img = Image.open(img_path).convert('RGB')\n", + " img_array = np.array(img) / 255.0 # Normalize pixel values to [0, 1]\n", + " images.append(img_array)\n", + " ages.append(age)\n", + "\n", + "X = np.array(images)\n", + "y = np.array(ages)\n", + "\n", + "# Transpose image dimensions to match PyTorch format (N, C, H, W)\n", + "X = np.transpose(X, (0, 3, 1, 2))\n", + "\n", + "# Split Data\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n", + "\n", + "print(f\"X_train shape: {X_train.shape}\")\n", + "print(f\"X_test shape: {X_test.shape}\")\n", + "print(f\"y_train shape: {y_train.shape}\")\n", + "print(f\"y_test shape: {y_test.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 1. Convert Numpy arrays to PyTorch Tensors\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42, stratify=y)\n", + "\n", + "X_train = torch.tensor(X_train.values, dtype=torch.float32)\n", + "X_test = torch.tensor(X_test.values, dtype=torch.float32)\n", + "y_train = torch.tensor(y_train.values, dtype=torch.long)\n", + "y_test = torch.tensor(y_test.values, dtype=torch.long)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 2. Create TensorDataset objects\n", + "train_dataset = TensorDataset(X_train, y_train)\n", + "test_dataset = TensorDataset(X_test, y_test)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 3. Create DataLoaders\n", + "train_loader = DataLoader(train_dataset, batch_size=32, shuffle=True)\n", + "test_loader = DataLoader(test_dataset, batch_size=32, shuffle=False)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 4. Print shape of one batch\n", + "print(\"Train dataset:\", len(train_dataset))\n", + "print(\"Test dataset:\", len(test_dataset))" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 5. Display sample images\n", + "X_batch, y_batch = next(iter(train_loader))\n", + "print(f\"Training batch input shape: {X_batch.shape}\")\n", + "print(f\"Training batch labels shape: {y_batch.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your model class here:\n", + "class NN4Layer(nn.Module):\n", + "\n", + " def __init__(self, input_dim, hidden_dim, output_dim):\n", + " super(NN4Layer, self).__init__()\n", + "\n", + " # First linear layer: input features -> hidden layer\n", + " self.layer1 = nn.Linear(input_dim, hidden_dim)\n", + "\n", + " # Second linear layer: hidden layer -> hidden layer\n", + " self.layer2 = nn.Linear(hidden_dim, hidden_dim)\n", + "\n", + " # Third linear layer: hidden layer -> hidden layer\n", + " self.layer3 = nn.Linear(hidden_dim, hidden_dim)\n", + "\n", + " # Output layer: hidden layer -> number of classes (logits)\n", + " self.layer4 = nn.Linear(hidden_dim, output_dim)\n", + "\n", + " # ReLU activation for non-linearity\n", + " self.relu = nn.ReLU()\n", + "\n", + " # Defines how input data flows through the network\n", + " def forward(self, x):\n", + " # First hidden layer\n", + " a1 = self.relu(self.layer1(x))\n", + "\n", + " # Second hidden layer\n", + " a2 = self.relu(self.layer2(a1))\n", + "\n", + " # Third hidden layer\n", + " a3 = self.relu(self.layer3(a2))\n", + "\n", + " # Output layer (raw scores / logits)\n", + " output = self.layer4(a3)\n", + "\n", + " return output" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your training loop here:\n", + "def train_one_epoch(model, optimizer, criterion, train_loader, device):\n", + " # Set the model to training mode\n", + " model.train()\n", + "\n", + " running_loss = 0.0\n", + "\n", + " for X_batch, y_batch in train_loader:\n", + " # Move batch to the selected device\n", + " X_batch = X_batch.to(device) # shape: (batch_size, num_features)\n", + " y_batch = y_batch.to(device) # shape: (batch_size,)\n", + "\n", + " # Forward pass (outputs are logits)\n", + " outputs = model(X_batch) # shape: (batch_size, num_classes)\n", + " loss = criterion(outputs, y_batch)\n", + "\n", + " # Backward pass & optimization\n", + " optimizer.zero_grad() # Clear previous gradients\n", + " loss.backward() # Compute gradients\n", + " optimizer.step() # Update model parameters\n", + "\n", + " running_loss += loss.item()\n", + "\n", + " # Average loss over all batches\n", + " avg_loss = running_loss / len(train_loader)\n", + "\n", + " return avg_loss" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your validation loop here:\n", + "def validate(model, criterion, test_loader, device):\n", + " # Set the model to evaluation mode\n", + " model.eval()\n", + "\n", + " running_loss = 0.0\n", + " correct = 0\n", + " total = 0\n", + "\n", + " with torch.no_grad():\n", + " for X_batch, y_batch in test_loader:\n", + " # Move data to device\n", + " X_batch = X_batch.to(device) # shape: (batch_size, num_features)\n", + " y_batch = y_batch.to(device) # shape: (batch_size,)\n", + "\n", + " # Forward pass\n", + " outputs = model(X_batch) # shape: (batch_size, num_classes)\n", + " loss = criterion(outputs, y_batch)\n", + " running_loss += loss.item()\n", + "\n", + " # Apply Softmax to get probabilities\n", + " probabilities = F.softmax(outputs, dim=1)\n", + "\n", + " # Pick the classes with highest probabilities\n", + " predicted = torch.argmax(probabilities, dim=1)\n", + "\n", + " # Accuracy calculation\n", + " correct += (predicted == y_batch).sum().item()\n", + " total += y_batch.size(0)\n", + "\n", + " avg_loss = running_loss / len(test_loader)\n", + " accuracy = correct / total\n", + "\n", + " return avg_loss, accuracy" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Define device, model, loss, optimizer:\n", + "# Device setup\n", + "device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\n", + "print(f\"Using device: {device}\")\n", + "\n", + "model = model.to(device)\n", + "\n", + "# Model parameters\n", + "input_dim = X_train.shape[1]\n", + "hidden_dim = 14\n", + "output_dim = 4" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Start training for 20 epochs:\n", + "num_epochs = 20\n", + "learning_rate = 0.001\n", + "\n", + "# Define criterion (loss function) - using CrossEntropyLoss as model now outputs logits\n", + "criterion = nn.CrossEntropyLoss()\n", + "# Define optimizer\n", + "optimizer = Adam(model.parameters(), learning_rate)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "train_losses = []\n", + "val_losses = []\n", + "val_accuracies = []\n", + "\n", + "print('Starting Training...')\n", + "for epoch in range(num_epochs):\n", + " # Train one epoch\n", + " train_loss = train_one_epoch(model, optimizer, criterion, train_loader, device)\n", + "\n", + " # Validate\n", + " val_loss, val_accuracy = validate(model, criterion, test_loader, device)\n", + "\n", + " train_losses.append(train_loss)\n", + " val_losses.append(val_loss)\n", + " val_accuracies.append(val_accuracy)\n", + "\n", + " print(f'Epoch [{epoch+1}/{num_epochs}], Train Loss: {train_loss:.4f}, Val Loss: {val_loss:.4f}, Val Accuracy: {val_accuracy:.4f}')\n", + "\n", + "print('Training Complete!')" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2 (Bonus): Write your code here:\n", + "# Get some test images\n", + "model.eval()\n", + "\n", + "test_images, test_labels = next(iter(test_loader))\n", + "test_images = test_images.to(device)\n", + "\n", + "with torch.no_grad():\n", + " reconstructed = model(test_images)\n", + "\n", + "# Move to CPU for plotting\n", + "test_images = test_images.cpu()\n", + "reconstructed = reconstructed.cpu()\n", + "\n", + "# Plot original vs reconstructed\n", + "n_images = 9\n", + "fig, axes = plt.subplots(2, n_images, figsize=(18, 6))\n", + "\n", + "for i in range(n_images):\n", + " # Original\n", + " axes[0, i].imshow(test_images[i].squeeze(), cmap='gray')\n", + " axes[0, i].axis('off')\n", + " axes[0, i].set_title(f'Original - \"{test_labels[i]}\"', fontsize=12)\n", + "\n", + " # Reconstructed\n", + " axes[1, i].imshow(reconstructed[i].squeeze(), cmap='gray')\n", + " axes[1, i].axis('off')\n", + " axes[1, i].set_title(f'Reconstructed - \"{test_labels[i]}\"', fontsize=12)\n", + "\n", + "plt.suptitle('Original vs Reconstructed Images', fontsize=14)\n", + "plt.tight_layout()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/4/Q3.ipynb b/submissions_extracted/4/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..cb762cce18fd2e3f6fd4ba686b99095e985a407f --- /dev/null +++ b/submissions_extracted/4/Q3.ipynb @@ -0,0 +1,272 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import pandas as pd\n", + "import numpy as np\n", + "import matplotlib.pyplot as plt\n", + "import seaborn as sns\n", + "from sklearn.model_selection import train_test_split, KFold, cross_val_score\n", + "from sklearn.preprocessing import LabelEncoder, OneHotEncoder, StandardScaler\n", + "from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score, confusion_matrix\n", + "from sklearn.linear_model import LogisticRegression\n", + "from sklearn.tree import DecisionTreeClassifier\n", + "from sklearn.ensemble import RandomForestClassifier\n", + "from sklearn.svm import SVC\n", + "\n", + "print(\"Libraries imported successfully.\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "\n", + "\n", + "# Download latest version\n", + "\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q3-exam-data\")\n", + "\n", + "\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "csv_file_path = os.path.join(path, 'Q3_data.csv')\n", + "\n", + "df = pd.read_csv(csv_file_path)\n", + "\n", + "print(f\"Shape: {df.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "df.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "df.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "def check_missing_values(df):\n", + "\n", + " missing_values = df.isnull().sum()\n", + "\n", + " print(\"Missing Values per Column:\")\n", + " print(missing_values[missing_values > 0])" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "def check_duplicates(df):\n", + " duplicates = df.duplicated().sum()\n", + "\n", + " print(f\"Number of Duplicate Samples: {duplicates}\")\n", + " if duplicates > 0:\n", + " print(\"Dropping Duplicates...\")\n", + " df.drop_duplicates(inplace=True)\n", + " print(\"Duplicates Dropped.\")\n", + " else:\n", + " print(\"No Duplicate Samples Found.\")\n", + "\n", + "check_duplicates(df)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "def one_hot_encode(y, num_classes):\n", + " y = np.array(y)\n", + " m = len(y)\n", + " one_hot = np.zeros((m, num_classes))\n", + "\n", + " for i in range(m):\n", + " class_label = int(y[i])\n", + "\n", + " one_hot[i, class_label] = 1\n", + "\n", + " return one_hot" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "from sklearn.preprocessing import StandardScaler\n", + "\n", + "numerical_cols = df.select_dtypes(include=[\"int64\", \"float64\"]).columns.drop(\"Delivery_Time\")\n", + "\n", + "scaler = StandardScaler()\n", + "df[numerical_cols] = scaler.fit_transform(df[numerical_cols])\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "# Task 6: Write your code here:\n", + "def check_target_imbalance(df, target_column):\n", + " print(\"Target Distribution:\")\n", + "\n", + " df[target_column].hist()\n", + " plt.show()\n", + "\n", + "check_target_imbalance(df, \"Delivery_Time\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "print(\"Separating target variable and features...\")\n", + "X = df.drop(\"Delivery_Time\", axis=1)\n", + "y = df[\"Delivery_Time\"]\n", + "print(\"Applying Label Encoding to target variable 'y'...\")\n", + "label_encoder = LabelEncoder()\n", + "y_encoded = label_encoder.fit_transform(y)\n", + "\n", + "print(\"Applying One-Hot Encoding to feature DataFrame 'X'...\")\n", + "onehot_encoder = OneHotEncoder(handle_unknown='ignore', sparse_output=False)\n", + "X_encoded = pd.DataFrame(onehot_encoder.fit_transform(X), columns=onehot_encoder.get_feature_names_out(X.columns))\n", + "print(\"Splitting data into training and testing sets...\")\n", + "X_train, X_test, y_train, y_test = train_test_split(X_encoded, y_encoded, test_size=0.3, random_state=42)\n", + "\n", + "print(\"Data split successful.\")\n", + "print(f\"Shape of X_train: {X_train.shape}\")\n", + "print(f\"Shape of X_test: {X_test.shape}\")\n", + "print(f\"Shape of y_train: {y_train.shape}\")\n", + "print(f\"Shape of y_test: {y_test.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:\n", + "2\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42, stratify=y)\n", + "print(f\"Train: {X_train.shape}, Test: {X_test.shape}\")\n", + "print(f\"Legendary in train: {y_train.sum()}, in test: {y_test.sum()}\")\n", + "3\n", + "model = RandomForestClassifier(n_estimators=100, max_depth=15,\n", + " class_weight='balanced', random_state=42)\n", + "model.fit(X_train_scaled, y_train)\n", + "print(\"Model trained!\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "# Task 1: Write your code here:\n", + "importance = pd.DataFrame({\n", + " 'feature': feature_cols,\n", + " 'importance': model.feature_importances_\n", + "}).sort_values('importance', ascending=False)\n", + "\n", + "plt.figure(figsize=(10, 6))\n", + "plt.barh(importance['feature'], importance['importance'], color='purple')\n", + "plt.xlabel('Importance')\n", + "plt.title('Feature Importance')\n", + "plt.gca().invert_yaxis()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/40/Q1.ipynb b/submissions_extracted/40/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..f89997ac9c2080ca42474bbb43771604a99b1c10 --- /dev/null +++ b/submissions_extracted/40/Q1.ipynb @@ -0,0 +1,173 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q1-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 6: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/40/Q2.ipynb b/submissions_extracted/40/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..c8937ff34d658b6340ef5c82e1d71e84083e0ea8 --- /dev/null +++ b/submissions_extracted/40/Q2.ipynb @@ -0,0 +1,192 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q2-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import os\n", + "import pandas as pd\n", + "import numpy as np\n", + "from PIL import Image\n", + "from sklearn.model_selection import train_test_split\n", + "\n", + "# Load Labels\n", + "labels_df = pd.read_csv(os.path.join(path, \"labels.csv\"))\n", + "img_dir = os.path.join(path, \"images\")\n", + "\n", + "images = []\n", + "ages = []\n", + "\n", + "# Load Images and Resize\n", + "print(\"Loading images...\")\n", + "for index, row in labels_df.iterrows():\n", + " img_name = row.iloc[0]\n", + " age = row.iloc[1]\n", + " img_path = os.path.join(img_dir, img_name)\n", + "\n", + " if os.path.exists(img_path):\n", + " img = Image.open(img_path).convert('RGB')\n", + " img_array = np.array(img) / 255.0 # Normalize pixel values to [0, 1]\n", + " images.append(img_array)\n", + " ages.append(age)\n", + "\n", + "X = np.array(images)\n", + "y = np.array(ages)\n", + "\n", + "# Transpose image dimensions to match PyTorch format (N, C, H, W)\n", + "X = np.transpose(X, (0, 3, 1, 2))\n", + "\n", + "# Split Data\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n", + "\n", + "print(f\"X_train shape: {X_train.shape}\")\n", + "print(f\"X_test shape: {X_test.shape}\")\n", + "print(f\"y_train shape: {y_train.shape}\")\n", + "print(f\"y_test shape: {y_test.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 1. Convert Numpy arrays to PyTorch Tensors\n", + "\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 2. Create TensorDataset objects\n", + "\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 3. Create DataLoaders\n", + "\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 4. Print shape of one batch\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 5. Display sample images\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your model class here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your training loop here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your validation loop here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Define device, model, loss, optimizer:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Start training for 20 epochs:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2 (Bonus): Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/40/Q3.ipynb b/submissions_extracted/40/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..c97832709061629f03a86d1f40306ca8a3e2a744 --- /dev/null +++ b/submissions_extracted/40/Q3.ipynb @@ -0,0 +1,160 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "\n", + "\n", + "# Download latest version\n", + "\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q3-exam-data\")\n", + "\n", + "\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/400/Q1.ipynb b/submissions_extracted/400/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..f5e869391e3c573608e0862308cb3ed6530280df --- /dev/null +++ b/submissions_extracted/400/Q1.ipynb @@ -0,0 +1,283 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "import pandas as pd\n", + "import numpy as np\n", + "import matplotlib.pyplot as plt\n", + "from sklearn.preprocessing import LabelEncoder\n", + "from sklearn.preprocessing import StandardScaler\n", + "from sklearn.model_selection import StratifiedKFold\n", + "from sklearn.model_selection import KFold\n", + "from sklearn.ensemble import RandomForestRegressor\n", + "from sklearn.metrics import mean_squared_error, mean_absolute_error\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q1-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "\n", + "df=pd.read_csv(f\"{path}/Q1_data.csv\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "df.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "df.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "def check_target_distribution(df, target_column):\n", + " df[target_column].hist(bins=30, edgecolor='black')\n", + "\n", + " plt.title(f\"Target Distribution ({target_column})\")\n", + " plt.xlabel(target_column)\n", + " plt.ylabel(\"Frequency\")\n", + " plt.grid(False)\n", + "\n", + " plt.show()\n", + "\n", + "check_target_distribution(df, \"Delivery_Time\")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "df_clean= df.drop(columns=['Order_ID'])\n", + "df_clean.isnull().sum()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "print(\"Missing values:\")\n", + "print(df_clean.isnull().sum()) #finding number of null values in each column\n", + "for col in ['Weather', 'Time_of_Day', 'Traffic_Level']:#making objective coloumn as unknown because these columns contirbute in the target predtiction\n", + " df_clean[col] = df_clean[col].fillna('unknown')\n", + "\n", + "df_clean['Courier_Experience_yrs']=df_clean['Courier_Experience_yrs'].fillna(0)\n", + "df_clean['Delivery_Time']=df_clean['Delivery_Time'].fillna(df['Delivery_Time'].mean()) # we cant loose data about the target so we replace it with mean of the target\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "def check_duplicates(df):\n", + " duplicates = df.duplicated().sum()\n", + " print(f\"Number of Duplicate Samples: {duplicates}\")\n", + " if duplicates > 0:\n", + " print(\"Dropping Duplicates...\")\n", + " df.drop_duplicates(inplace=True)\n", + " print(\"Duplicates Dropped.\")\n", + " else:\n", + " print(\"No Duplicate Samples Found.\")\n", + "\n", + "check_duplicates(df_clean)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "categorical_cols = df_clean.select_dtypes(include=[\"object\"]).columns\n", + "\n", + "for col in categorical_cols:\n", + " le = LabelEncoder()\n", + " df_clean[col] = le.fit_transform(df[col])\n", + "df_clean.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "numerical_cols = df_clean.select_dtypes(include=[\"int64\", \"float64\"]).columns.drop(\"Delivery_Time\") # DON'T SCALE THE TARGET\n", + "\n", + "scaler = StandardScaler()\n", + "df_clean[numerical_cols] = scaler.fit_transform(df_clean[numerical_cols])\n", + "df_clean.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 6: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "X = df_clean.drop(\"Delivery_Time\", axis=1).astype(float) #spliting dataset into features X and target y\n", + "y = df_clean['Delivery_Time'].astype(float)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:\n", + "n_splits=5\n", + "losses=[]\n", + "kf = KFold(n_splits=5, shuffle=True, random_state=42)\n", + "model=RandomForestRegressor(n_estimators=200)\n", + "for fold_idx, (train_index, test_index) in enumerate(kf.split(X)):# k-fold makes each fold validation for an iteration\n", + " print(f\"\\nFold {fold_idx + 1}/{n_splits}\")\n", + "\n", + " X_train, X_test = X.iloc[train_index], X.iloc[test_index] #each time loop iterate we have a new fold as validation\n", + " y_train, y_test = y.iloc[train_index], y.iloc[test_index]\n", + "\n", + " model.fit(X_train,y_train)\n", + " y_pred= model.predict(X_test)\n", + "\n", + "\n", + " mae = mean_absolute_error(y_test, y_pred)\n", + " losses.append(mae)\n", + "\n", + "\n", + "avg_loss=np.mean(losses) # caluclating avg loss across the fold\n", + "\n", + "print(avg_loss)\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "feature_cols=['Distance_km', 'Weather', 'Traffic_Level','Time_of_Day','Vehicle_Type','Preparation_Time_min','Courier_Experience_yrs']\n", + "feature_importance = pd.DataFrame({\n", + " 'feature': feature_cols,\n", + " 'importance': model.feature_importances_\n", + "}).sort_values('importance', ascending=False)\n", + "\n", + "plt.figure(figsize=(10, 6))\n", + "plt.barh(feature_importance['feature'], feature_importance['importance'])\n", + "plt.xlabel('Importance')\n", + "plt.title('Feature Importance')\n", + "plt.gca().invert_yaxis()\n", + "plt.show()\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "# Scatter plot: Predicted vs Actual\n", + "plt.figure(figsize=(8, 6))\n", + "\n", + "# Plot: Predicted vs Actual scatter\n", + "plt.scatter(y_test, y_pred.flatten(), alpha=0.5, s=10, c='steelblue')\n", + "\n", + "# Add perfect prediction line\n", + "min_val = min(y_test.min(), y_pred.min())\n", + "max_val = max(y_test.max(), y_pred.max())\n", + "plt.plot([min_val, max_val], [min_val, max_val], 'r--', lw=2, label='Perfect Prediction')\n", + "\n", + "plt.xlabel('Actual time ', fontsize=12)\n", + "plt.ylabel('Predicted time ($)', fontsize=12)\n", + "plt.title('Predicted vs Actual delvery time', fontsize=14)\n", + "plt.legend()\n", + "plt.grid(True, alpha=0.3)\n", + "\n", + "plt.tight_layout()\n", + "plt.show()\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:\n" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/400/Q2.ipynb b/submissions_extracted/400/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..1081c9495c76538f945d4b1c6e17c6e9a970fa87 --- /dev/null +++ b/submissions_extracted/400/Q2.ipynb @@ -0,0 +1,430 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "import torch\n", + "import torch.nn as nn\n", + "from torch.utils.data import DataLoader, TensorDataset\n", + "import matplotlib.pyplot as plt\n", + "from torch.optim import AdamW\n", + "from sklearn.metrics import mean_squared_error, r2_score\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q2-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import os\n", + "import pandas as pd\n", + "import numpy as np\n", + "from PIL import Image\n", + "from sklearn.model_selection import train_test_split\n", + "\n", + "# Load Labels\n", + "labels_df = pd.read_csv(os.path.join(path, \"labels.csv\"))\n", + "img_dir = os.path.join(path, \"images\")\n", + "\n", + "images = []\n", + "ages = []\n", + "\n", + "# Load Images and Resize\n", + "print(\"Loading images...\")\n", + "for index, row in labels_df.iterrows():\n", + " img_name = row.iloc[0]\n", + " age = row.iloc[1]\n", + " img_path = os.path.join(img_dir, img_name)\n", + "\n", + " if os.path.exists(img_path):\n", + " img = Image.open(img_path).convert('RGB')\n", + " img_array = np.array(img) / 255.0 # Normalize pixel values to [0, 1]\n", + " images.append(img_array)\n", + " ages.append(age)\n", + "\n", + "X = np.array(images)\n", + "y = np.array(ages)\n", + "\n", + "# Transpose image dimensions to match PyTorch format (N, C, H, W)\n", + "X = np.transpose(X, (0, 3, 1, 2))\n", + "\n", + "# Split Data\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n", + "\n", + "print(f\"X_train shape: {X_train.shape}\")\n", + "print(f\"X_test shape: {X_test.shape}\")\n", + "print(f\"y_train shape: {y_train.shape}\")\n", + "print(f\"y_test shape: {y_test.shape}\")\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 1. Convert Numpy arrays to PyTorch Tensors\n", + "X_train= torch.tensor(X_train,dtype=torch.float32)\n", + "X_test= torch.tensor(X_test, dtype= torch.float32)\n", + "y_train=torch.tensor(y_train, dtype= torch.float32)\n", + "y_test= torch.tensor(y_test, dtype = torch.float32)\n", + "\n", + "\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 2. Create TensorDataset objects\n", + "train_dataset= TensorDataset(X_train, y_train)\n", + "test_dataset = TensorDataset(X_test, y_test)\n", + "\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 3. Create DataLoaders\n", + "train_loader = DataLoader(\n", + " train_dataset,\n", + " batch_size=32,\n", + " shuffle=True,\n", + " num_workers=2\n", + ")\n", + "# DataLoader for test/validation data\n", + "test_loader = DataLoader(\n", + " test_dataset,\n", + " batch_size=32,\n", + " shuffle=False,\n", + " num_workers=2\n", + ")\n", + "\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 4. Print shape of one batch\n", + "X_batch, y_batch = next(iter(train_loader))\n", + "print(f\"Training batch input shape: {X_batch.shape}\")\n", + "print(f\"Training batch labels shape: {y_batch.shape}\")\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 5. Display sample images\n", + "images, labels = next(iter(train_loader))\n", + "\n", + "# Display the first 6 images in the batch\n", + "plt.figure(figsize=(8, 4))\n", + "\n", + "for i in range(6):\n", + " plt.subplot(2, 3, i + 1)\n", + " plt.imshow(images[i].squeeze())\n", + " plt.title(f\"Label: {labels[i].item()}\")\n", + " plt.axis('off')\n", + "\n", + "plt.tight_layout()\n", + "plt.show()\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your model class here:\n", + "class NN4Layer(nn.Module):\n", + "\n", + " def __init__(self, input_dim, hidden_dim):\n", + " super(NN4Layer, self).__init__()\n", + "\n", + " # First linear layer: input features -> hidden layer\n", + " self.layer1 = nn.Linear(input_dim, hidden_dim)\n", + "\n", + " # Second linear layer: hidden layer -> hidden layer\n", + " self.layer2 = nn.Linear(hidden_dim, hidden_dim)\n", + "\n", + " # third layer: hidden layer\n", + " self.layer3 = nn.Linear(hidden_dim, hidden_dim)\n", + "\n", + " #Output layer: hidden layer -> 1 (age)\n", + " self.layer4= nn.Linear(hidden_dim, 1)\n", + "\n", + " # ReLU activation for non-linearity\n", + " self.relu = nn.ReLU()\n", + "\n", + " # Defines how input data flows through the network\n", + " def forward(self, x):\n", + " # input layer\n", + " z1 = self.layer1(x)\n", + " a1 = self.relu(z1)\n", + "\n", + " # first hidden layer\n", + " z2 = self.layer2(a1)\n", + " a2 = self.relu(z2)\n", + "\n", + " #second hidden layer\n", + " z3 = self.layer3(a2)\n", + " a3=self.relu(z3)\n", + "\n", + " #output layer(regression output)\n", + " output=self.layer4(a3)\n", + "\n", + "\n", + " return output\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "#X_batch.view(X_batch.size(0), -1)\n", + "y_batch.view(-1, 1)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your training loop here:\n", + "def train_one_epoch(model, optimizer, criterion, train_loader, device):\n", + " # Set the model to training mode\n", + " model.train()\n", + "\n", + " running_loss = 0.0\n", + "\n", + " for X_batch, y_batch in train_loader:\n", + " # Move batch to the selected device\n", + " X_batch = X_batch.view(X_batch.size(0), -1).to(device) # shape: (batch_size, num_features)\n", + " y_batch = y_batch.view(-1, 1).to(device) # shape: (batch_size,)\n", + "\n", + " # Forward pass (outputs are logits)\n", + " outputs = model(X_batch) # shape: (batch_size, num_classes)\n", + " loss = criterion(outputs, y_batch)\n", + "\n", + " # Backward pass & optimization\n", + " optimizer.zero_grad() # Clear previous gradients\n", + " loss.backward() # Compute gradients\n", + " optimizer.step() # Update model parameters\n", + "\n", + " running_loss += loss.item()\n", + "\n", + " # Average loss over all batches\n", + " avg_loss = running_loss / len(train_loader)\n", + "\n", + " return avg_loss\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "y_batch.view(-)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your validation loop here:\n", + "def validate(model, criterion, test_loader, device):\n", + " # Set the model to evaluation mode\n", + " model.eval()\n", + "\n", + " running_loss = 0.0\n", + " correct = 0\n", + " total = 0\n", + "\n", + " with torch.no_grad():\n", + " for X_batch, y_batch in test_loader:\n", + " # Move data to device\n", + " X_batch = X_batch.view(X_batch.size(0), -1).to(device) # shape: (batch_size, num_features)\n", + " y_batch = y_batch.view(-1, 1).to(device) # shape: (batch_size,)\n", + "\n", + " # Forward pass\n", + " outputs = model(X_batch) # shape: (batch_size, num_classes)\n", + " loss = criterion(outputs, y_batch)\n", + " running_loss += loss.item()\n", + "\n", + "\n", + " avg_loss = running_loss / len(test_loader)\n", + "\n", + " return avg_loss" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Define device, model, loss, optimizer:\n", + "device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n", + "num_epochs = 20\n", + "learning_rate = 0.01\n", + "\n", + "# Model parameters\n", + "\n", + "input_dim = 3*36*36\n", + "hidden_dim = 128\n", + "\n", + "# Instantiate model\n", + "model = NN4Layer(input_dim, hidden_dim).to(device)\n", + "\n", + "# Print the model architecture\n", + "print(\"Model Architecture:\\n\")\n", + "print(model)\n", + "\n", + "# Calculate the total number of trainable parameters\n", + "total_params = sum(p.numel() for p in model.parameters() if p.requires_grad)\n", + "print(f\"\\nTotal trainable parameters: {total_params}\")\n", + "\n", + "criterion = nn.MSELoss() #since its a regression problem\n", + "optimizer = AdamW(model.parameters(), learning_rate) # the best optimizer\n", + "\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Start training for 20 epochs:\n", + "train_losses = []\n", + "val_losses = []\n", + "print('Starting Training...')\n", + "for epoch in range(num_epochs):\n", + " # Train one epoch\n", + " train_loss = train_one_epoch(model, optimizer, criterion, train_loader, device)\n", + "\n", + " # Validate\n", + " val_loss = validate(model, criterion, test_loader, device)\n", + "\n", + " train_losses.append(train_loss)\n", + " val_losses.append(val_loss)\n", + "\n", + " if (epoch + 1) % 5 == 0:\n", + " print(\n", + " f'Epoch [{epoch+1}/{num_epochs}], '\n", + " f'Train Loss: {train_loss:.4f}, '\n", + " f'Val Loss: {val_loss:.4f}'\n", + " )\n", + "\n", + "print('Training Complete!')\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "plt.figure(figsize=(7, 5))\n", + "\n", + "plt.plot(train_losses, label='Train Loss')\n", + "plt.plot(val_losses, label='Validation Loss')\n", + "plt.title('Loss over Epochs')\n", + "plt.xlabel('Epoch')\n", + "plt.ylabel('Loss (MSE)')\n", + "plt.legend()\n", + "\n", + "plt.tight_layout()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2 (Bonus): Write your code here:\n", + "\n", + "plt.figure(figsize=(8, 6))\n", + "\n", + "# Plot: Predicted vs Actual scatter\n", + "plt.scatter(y_test, y_pred.flatten(), alpha=0.5, s=10, c='steelblue')\n", + "\n", + "# Add perfect prediction line\n", + "min_val = min(y_test.min(), y_pred.min())\n", + "max_val = max(y_test.max(), y_pred.max())\n", + "plt.plot([min_val, max_val], [min_val, max_val], 'r--', lw=2, label='Perfect Prediction')\n", + "\n", + "plt.xlabel('Actual age', fontsize=12)\n", + "plt.ylabel('Predicted age', fontsize=12)\n", + "plt.title('Predicted vs Actual delvery time', fontsize=14)\n", + "plt.legend()\n", + "plt.grid(True, alpha=0.3)\n", + "\n", + "plt.tight_layout()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/400/Q3.ipynb b/submissions_extracted/400/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..4cd6dcb2d61750fe7edf7a22ba5b0087eb5c092f --- /dev/null +++ b/submissions_extracted/400/Q3.ipynb @@ -0,0 +1,221 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "import pandas as pd\n", + "from sklearn.preprocessing import StandardScaler, LabelEncoder\n", + "\n", + "\n", + "\n", + "\n", + "# Download latest version\n", + "\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q3-exam-data\")\n", + "\n", + "\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "df= pd.read_csv(f\"{path}/Q3_data.csv\")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "df.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "df.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "l= df.columns\n", + "missing_percentage = (df.isnull().sum() / len(df)) * 100\n", + "missing_data = pd.DataFrame({\n", + " 'Column': missing_percentage.index,\n", + " 'Missing_Percentage': missing_percentage.values\n", + "})\n", + "missing_data = missing_data[missing_data['Missing_Percentage'] > 0].sort_values('Missing_Percentage', ascending=False)\n", + "\n", + "print(\"Missing Data Analysis:\")\n", + "missing_data.head(10)\n", + "\n", + "df=df.drop(columns=['D_76', 'D_142', 'D_53', 'D_42', 'D_82','B_17', 'D_56', 'S_9', 'D_105', 'D_50']) #dropped all the columns which had nan more than 50 %\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "def check_duplicates(df):\n", + " duplicates = df.duplicated().sum()\n", + " print(f\"Number of Duplicate Samples: {duplicates}\")\n", + " if duplicates > 0:\n", + " print(\"Dropping Duplicates...\")\n", + " df.drop_duplicates(inplace=True)\n", + " print(\"Duplicates Dropped.\")\n", + " else:\n", + " print(\"No Duplicate Samples Found.\")\n", + "\n", + "check_duplicates(df)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "standard_scaler = StandardScaler()\n", + "features= df.columns.drop('Target') #never scale the target\n", + "features=standard_scaler.fit_transform(df[features])" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "print(f\"Legendary: {df['Target'].sum()}\")\n", + "print(f\"Normal: {(df['Target'] == 0).sum()}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "X = df.drop(\"Target\", axis=1).astype(float)\n", + "y = df['Target']" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:\n", + "from sklearn.model_selection import KFold\n", + "from sklearn.model_selection import StratifiedKFold\n", + "from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score\n", + "from catboost import CatBoostClassifier\n", + "from tqdm import tqdm\n", + "n_splits = 5 # K=5 Folds\n", + "model= CatBoostClassifier(\n", + " verbose=0,\n", + " n_estimators=320,\n", + " max_depth=4)\n", + "\n", + "\n", + "# Stratified 5-Fold Cross-Validation, shuffled\n", + "skf = StratifiedKFold(n_splits=n_splits, shuffle=True, random_state=42)\n", + "for fold_idx, (train_index, test_index) in enumerate(skf.split(X, y)):\n", + " print(f\"\\nFold {fold_idx + 1}/{n_splits}\")\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", + " y_pred=model.predict(X_test)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/401/Q1.ipynb b/submissions_extracted/401/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..80dc7aa550f88cbd9f8a20849075a59ccd6bb111 --- /dev/null +++ b/submissions_extracted/401/Q1.ipynb @@ -0,0 +1,204 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import numpy as np\n", + "import matplotlib.pyplot as plt\n", + "import os\n", + "import pandas as pd\n", + "import kagglehub\n", + "\n", + "from sklearn.model_selection import train_test_split, StratifiedKFold, cross_val_score\n", + "from sklearn.preprocessing import StandardScaler, LabelEncoder\n", + "from sklearn.ensemble import RandomForestClassifier\n", + "from sklearn.metrics import classification_report, confusion_matrix, accuracy_score\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q1-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "\n", + "\n", + "Q1_path = os.path.join(path, 'Q1_data.csv')\n", + "df_q1 = pd.read_csv(Q1_path)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "print(f\"Shape: {df_q1.shape}\")\n", + "df_q1.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "df_q1.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "df_q1.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "print(f\"Time: {df_q1['Delivery_Time'].sum()}\")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "df_q1.drop(columns=['Order_ID'])" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "print(\"Missin values\")\n", + "print(df_q1.isnull().sum())" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "df_q1.drop_duplicates()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "\n", + "le = LabelEncoder()\n", + "df_q1['Distance_km'] = le.fit_transform(df_q1['Distance_km'])\n", + "df_q1['Preparation_Time_min'] = le.fit_transform(df_q1['Preparation_Time_min'])\n", + "df_q1['Courier_Experience_yrs'] = le.fit_transform(df_q1['Courier_Experience_yrs'])\n", + "df_q1['Delivery_Time'] = le.fit_transform(df_q1['Delivery_Time'])" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "\n", + "feature_cols = [\t'Distance_km',\t'Preparation_Time_min',\t'Courier_Experience_yrs']\n", + "X = df_q1[feature_cols]\n", + "y = df_q1['Delivery_Time']\n", + "\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n", + "scaler = StandardScaler()\n", + "X_train = scaler.fit_transform(X_train)\n", + "X_test = scaler.transform(X_test)\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "df_q1.value_counts()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "X = df_q1[feature_cols]\n", + "y = df_q1['Delivery_Time']" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42, stratify=y)\n", + "print(f\"Train: {X_train.shape}, Test: {X_test.shape}\")\n", + "print(f\"Delivery_Time in train: {y_train.sum()}, in test: {y_test.sum()}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/402/Q1.ipynb b/submissions_extracted/402/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..c0d12848ecada7bde7fc1ae54474dd04a0a7d28e --- /dev/null +++ b/submissions_extracted/402/Q1.ipynb @@ -0,0 +1,401 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest versionظ\n", + "\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q1-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import pandas as pd\n", + "import os\n", + "\n", + "\n", + "# Task 1: Write your code here:\n", + "# Load the dataset\n", + "pokemon_path = os.path.join(path, 'Q1_data.csv')\n", + "df = pd.read_csv(pokemon_path)\n", + "\n", + "print(f\"Dataset shape: {df.shape}\")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "df.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "df.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "\n", + "import matplotlib.pyplot as plt\n", + "\n", + "# 1. What does our target variable (charges) look like?\n", + "def check_target_distribution(df, target_column):\n", + " df[target_column].hist(bins=30, edgecolor='black')\n", + "\n", + " plt.title(f\"Target Distribution ({target_column})\")\n", + " plt.xlabel(target_column)\n", + " plt.ylabel(\"Frequency\")\n", + " plt.grid(False)\n", + "\n", + " plt.show()\n", + "\n", + "check_target_distribution(df, \"Delivery_Time\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "df = df.drop(\"Order_ID\", axis = 1)\n", + "\n", + "df.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "\n", + "# 2. Do we have missing values?\n", + "def check_missing_values(df):\n", + " missing_values = df.isnull().sum()\n", + " print(\"Missing Values per Column:\")\n", + " print(missing_values[missing_values > 0])\n", + " if missing_values.any():\n", + " print(\"\\nHandle Missing Values as needed.\")\n", + " else:\n", + " print(\"\\nNo Missing Values Found.\")\n", + "\n", + "check_missing_values(df)\n", + "\n", + "# handleing them after Encoding" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "def check_duplicates(df):\n", + " duplicates = df.duplicated().sum()\n", + " print(f\"Number of Duplicate Samples: {duplicates}\")\n", + " if duplicates > 0:\n", + " print(\"Dropping Duplicates...\")\n", + " df.drop_duplicates(inplace=True)\n", + " print(\"Duplicates Dropped.\")\n", + " else:\n", + " print(\"No Duplicate Samples Found.\")\n", + "\n", + "check_duplicates(df)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "\n", + "categorical_cols = df.select_dtypes(include=[\"object\"]).columns\n", + "\n", + "print(\"Categorical Columns:\", list(categorical_cols))\n", + "\n", + "# Encoder\n", + "from sklearn.preprocessing import LabelEncoder\n", + "\n", + "label_encoders = {}\n", + "for col in categorical_cols:\n", + " le = LabelEncoder()\n", + " df[col] = le.fit_transform(df[col])\n", + " label_encoders[col] = le\n", + "\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# to fill mode\n", + "def fill_with_mode(df, columns):\n", + " df_clean = df.copy()\n", + " for col in columns:\n", + " if col in df_clean.columns:\n", + " mode_value = df_clean[col].mode()\n", + " if len(mode_value) > 0:\n", + " df_clean[col] = df_clean[col].fillna(mode_value[0])\n", + " return df_clean\n", + "\n", + "\n", + "cols_to_mode = ['Weather', 'Traffic_Level', 'Time_of_Day', 'Vehicle_Type']\n", + "df_clean = fill_with_mode(df, cols_to_mode)\n", + "df_clean.info()\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "\n", + "from sklearn.preprocessing import StandardScaler # can be StandardScaler\n", + "\n", + "features = df_clean.columns.drop(\"Delivery_Time\") # DON'T SCALE THE TARGET\n", + "\n", + "scaler = StandardScaler() # can be StandardScaler()\n", + "df_clean[features] = scaler.fit_transform(df_clean[features])" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 6: Write your code here:\n", + "\n", + "# 1. What does our target variable (charges) look like?\n", + "def check_target_distribution(df, target_column):\n", + " df[target_column].hist(bins=30, edgecolor='black')\n", + "\n", + " plt.title(f\"Target Distribution ({target_column})\")\n", + " plt.xlabel(target_column)\n", + " plt.ylabel(\"Frequency\")\n", + " plt.grid(False)\n", + "\n", + " plt.show()\n", + "\n", + "check_target_distribution(df, \"Delivery_Time\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 6: Write your code here:\n", + "\n", + "# 1. What does our target variable (charges) look like?\n", + "def check_target_distribution(df, target_column):\n", + " df[target_column].hist(bins=30, edgecolor='black')\n", + "\n", + " plt.title(f\"Stata Distribution ({target_column})\")\n", + " plt.xlabel(target_column)\n", + " plt.ylabel(\"Frequency\")\n", + " plt.grid(False)\n", + "\n", + " plt.show()\n", + "\n", + "check_target_distribution(df, \"Weather\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 6: Write your code here:\n", + "\n", + "# 1. What does our target variable (charges) look like?\n", + "def check_target_distribution(df, target_column):\n", + " df[target_column].hist(bins=30, edgecolor='black')\n", + "\n", + " plt.title(f\"Stata Distribution ({target_column})\")\n", + " plt.xlabel(target_column)\n", + " plt.ylabel(\"Frequency\")\n", + " plt.grid(False)\n", + "\n", + " plt.show()\n", + "\n", + "check_target_distribution(df, \"Preparation_Time_min\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "\n", + "# X, y initilize\n", + "\n", + "X = df.drop(\"Delivery_Time\", axis=1).astype(float)\n", + "y = df['Delivery_Time'].astype(float)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:\n", + "from sklearn.model_selection import train_test_split, KFold\n", + "from sklearn.metrics import mean_squared_error as mean_absolute_error\n", + "from sklearn.ensemble import RandomForestRegressor\n", + "import numpy as np\n", + "\n", + "\n", + "model = RandomForestRegressor(n_estimators=200)\n", + "\n", + "\n", + "mae_results = []\n", + "\n", + "\n", + "\n", + "kf = KFold(n_splits=5, shuffle=True, random_state=42)\n", + "\n", + "for fold_idx, (train_index, test_index) in enumerate(kf.split(X)):\n", + " print(f\"\\nFold {fold_idx + 1}/{5}\")\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", + "\n", + " model.fit(X_train, y_train)\n", + "\n", + " y_pred = model.predict(X_test)\n", + "\n", + " mae = mean_absolute_error(y_test, y_pred)\n", + "\n", + " mae_results.append(mae)\n", + "\n", + "print(f\" MAE: {np.mean(mae_results):.4f}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "# Feature importance\n", + "feature_cols = ['Distance_km', 'Weather', 'Traffic_Level', 'Time_of_Day',\n", + " 'Vehicle_Type', 'Preparation_Time_min', 'Courier_Experience_yrs']\n", + "\n", + "feature_importance = pd.DataFrame({\n", + " 'feature': feature_cols,\n", + " 'importance': model.feature_importances_\n", + "}).sort_values('importance', ascending=False)\n", + "\n", + "plt.figure(figsize=(10, 6))\n", + "plt.barh(feature_importance['feature'], feature_importance['importance'])\n", + "plt.xlabel('Importance')\n", + "plt.title('Feature Importance')\n", + "plt.gca().invert_yaxis()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "# Plot predicted delivery time histogram\n", + "\n", + "# Plot Predictions vs Ground Truth\n", + "plt.figure(figsize=(6, 4))\n", + "plt.scatter(y_test, y_pred, alpha=0.6)\n", + "plt.plot(\n", + " [y_test.min(), y_test.max()],\n", + " [y_test.min(), y_test.max()],\n", + " \"r--\",\n", + " linewidth=2\n", + ")\n", + "\n", + "plt.xlabel(\"Actual Exam Scores (Ground Truth)\")\n", + "plt.ylabel(\"Predicted Exam Scores\")\n", + "plt.title(\"Linear Regression: Predictions vs Ground Truth\")\n", + "plt.grid(True)\n", + "\n", + "plt.tight_layout()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/402/Q2.ipynb b/submissions_extracted/402/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..a26684498b2a1c5b4b8a91b1423dcc83fa9ee6d0 --- /dev/null +++ b/submissions_extracted/402/Q2.ipynb @@ -0,0 +1,408 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q2-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import os\n", + "import pandas as pd\n", + "import numpy as np\n", + "from PIL import Image\n", + "from sklearn.model_selection import train_test_split\n", + "\n", + "# Load Labels\n", + "labels_df = pd.read_csv(os.path.join(path, \"labels.csv\"))\n", + "img_dir = os.path.join(path, \"images\")\n", + "\n", + "images = []\n", + "ages = []\n", + "\n", + "# Load Images and Resize\n", + "print(\"Loading images...\")\n", + "for index, row in labels_df.iterrows():\n", + " img_name = row.iloc[0]\n", + " age = row.iloc[1]\n", + " img_path = os.path.join(img_dir, img_name)\n", + "\n", + " if os.path.exists(img_path):\n", + " img = Image.open(img_path).convert('RGB')\n", + " img_array = np.array(img) / 255.0 # Normalize pixel values to [0, 1]\n", + " images.append(img_array)\n", + " ages.append(age)\n", + "\n", + "X = np.array(images)\n", + "y = np.array(ages)\n", + "\n", + "# Transpose image dimensions to match PyTorch format (N, C, H, W)\n", + "X = np.transpose(X, (0, 3, 1, 2))\n", + "\n", + "# Split Data\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n", + "\n", + "print(f\"X_train shape: {X_train.shape}\")\n", + "print(f\"X_test shape: {X_test.shape}\")\n", + "print(f\"y_train shape: {y_train.shape}\")\n", + "print(f\"y_test shape: {y_test.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "from torchvision.transforms.functional import to_tensor\n", + "from torch.utils.data import DataLoader\n", + "import matplotlib.pyplot as plt\n", + "import torch.nn as nn\n", + "from torch.utils.data import TensorDataset\n", + "import torch.nn.functional as F\n", + "import torch\n", + "from torch.optim import AdamW" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 1. Convert Numpy arrays to PyTorch Tensors\n", + "\n", + "\n", + "\n", + "\n", + "# transform to tensors\n", + "X_train = torch.tensor(X_train, dtype=torch.float32)\n", + "X_test = torch.tensor(X_test, dtype=torch.float32)\n", + "y_train = torch.tensor(y_train, dtype=torch.float32)\n", + "y_test = torch.tensor(y_test, dtype=torch.float32)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 2. Create TensorDataset objects\n", + "# TensorDataset pairs input features (X) with their corresponding labels (y)\n", + "# Each item in the dataset is returned as (X[i], y[i])\n", + "train_dataset = TensorDataset(X_train, y_train)\n", + "test_dataset = TensorDataset(X_test, y_test)\n", + "\n", + "# Create Dataloaders to train and test data in batches\n", + "train_loader = DataLoader(train_dataset, batch_size=32, shuffle=True)\n", + "test_loader = DataLoader(test_dataset, batch_size=32, shuffle=False)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 4. Print shape of one batch\n", + "\n", + "# Access a single sample from the dataset\n", + "# This helps verify the shape of one data sample\n", + "first_sample, _ = train_dataset[0]\n", + "print(f\"Shape of one sample: {first_sample.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 5. Display sample images\n", + "import matplotlib.pyplot as plt\n", + "\n", + "# Get one batch of images and labels\n", + "images, labels = next(iter(train_loader))\n", + "\n", + "# Display the first 6 images in the batch\n", + "plt.figure(figsize=(8, 4))\n", + "\n", + "for i in range(6):\n", + " plt.subplot(2, 3, i + 1)\n", + "\n", + " # Convert from (C, H, W) to (H, W, C) for matplotlib\n", + " img = images[i].permute(1, 2, 0)\n", + "\n", + " plt.imshow(img)\n", + " plt.title(f\"Label: {labels[i].item()}\")\n", + " plt.axis('off')\n", + "\n", + "plt.tight_layout()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your model class here:\n", + "#Create a model class with 4 linear layers\n", + "\n", + "class NN4Layer(nn.Module):\n", + "\n", + " def __init__(self, input_dim, hidden_dim, output_dim):\n", + " super(NN4Layer, self).__init__()\n", + "\n", + " # TODO: What are the dimensions of the first layer? (hint: features? hidden neurons?)\n", + " self.layer1 = nn.Linear(input_dim, hidden_dim)\n", + "\n", + " # TODO: What are the dimensions from previous and next layer?\n", + " self.layer2 = nn.Linear(hidden_dim, hidden_dim)\n", + "\n", + " # TODO: What are the dimensions from previous and next layer?\n", + " self.layer3 = nn.Linear(hidden_dim, hidden_dim)\n", + "\n", + " # TODO: What are the dimensions from previous and next layer?\n", + " self.layer4 = nn.Linear(hidden_dim, output_dim)\n", + "\n", + " # activation function for non-linearity\n", + " self.relu = nn.ReLU()\n", + "\n", + " # Defines how input data flows through the network\n", + " def forward(self, x):\n", + " # Layer 1: TODO\n", + " z1 = self.layer1(x)\n", + " a1 = self.relu(z1)\n", + "\n", + " # Layer 2 TODO\n", + " z2 = self.layer2(a1)\n", + " a2 = self.relu(z2)\n", + "\n", + " # Layer 3 TODO\n", + " z3 = self.layer3(a2)\n", + " a3 = self.relu(z3)\n", + "\n", + " # Output layer TODO\n", + " z5 = self.layer4(a3)\n", + "\n", + " # TODO: are we missing output activation function? (hint: Loss Function)\n", + "\n", + " return z5" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your training loop here:\n", + "# Create a training loop function\n", + "\n", + "def train_one_epoch(model, optimizer, criterion, train_loader, device):\n", + " # Set the model to training mode\n", + " model.train()\n", + "\n", + " running_loss = 0.0\n", + "\n", + " for X_batch, y_batch in train_loader:\n", + " # Move batch to the selected device\n", + " X_batch = X_batch.view(X_batch.size(0), -1).to(device)\n", + " y_batch = y_batch.to(device)\n", + "\n", + " # Forward pass\n", + " # TODO: make predictions\n", + " outputs = model(X_batch) # shape: (batch_size, 10)\n", + " # TODO: compute loss\n", + " loss = criterion(outputs, y_batch)\n", + "\n", + " # Backward pass & optimization\n", + " optimizer.zero_grad() # Clear previous gradients\n", + " loss.backward() # Compute gradients\n", + " optimizer.step() # Update model parameters\n", + "\n", + " running_loss += loss.item()\n", + "\n", + " # Average loss over all batches\n", + " avg_loss = running_loss / len(train_loader)\n", + "\n", + " return avg_loss" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your validation loop here:\n", + "def validate(model, criterion, test_loader, device):\n", + " # Set the model to evaluation mode\n", + " model.eval()\n", + "\n", + " running_loss = 0.0\n", + "\n", + "\n", + " with torch.no_grad():\n", + " for X_batch, y_batch in test_loader:\n", + " # Move data to device\n", + " X_batch = X_batch.view(X_batch.size(0), -1).to(device)\n", + " y_batch = y_batch.to(device)\n", + "\n", + " # Forward pass\n", + " # TODO: make predictions\n", + " outputs = model(X_batch) # shape: (batch_size, 10)\n", + " # TODO: compute loss\n", + " loss = criterion(outputs, y_batch)\n", + " running_loss += loss.item()\n", + "\n", + "\n", + "\n", + "\n", + " avg_loss = running_loss / len(test_loader)\n", + "\n", + " return avg_loss\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Define device, model, loss, optimizer:\n", + "# Device setup\n", + "device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n", + "\n", + "# Model parameters\n", + "# TODO: What are input features ? (hint: flatten using channel, height, width)\n", + "input_dim = 3 * 36 * 36 # CIFAR-10 images flattened (RGB)\n", + "\n", + "# TODO: choose number of hidden neurons\n", + "hidden_dim = 64 # Design choice\n", + "\n", + "# TODO: what are the number of classes ?\n", + "output_dim = 1 # CIFAR-10 classes\n", + "\n", + "# TODO: Instantiate model (what are the model class inputs?)\n", + "model = NN4Layer(input_dim, hidden_dim, output_dim).to(device)\n", + "\n", + "# TODO: Print the model architecture\n", + "print(\"Model Architecture:\\n\")\n", + "print(model)\n", + "\n", + "# Calculate the total number of trainable parameters\n", + "total_params = sum(p.numel() for p in model.parameters() if p.requires_grad)\n", + "print(f\"\\nTotal trainable parameters: {total_params}\")\n", + "\n", + "# TODO: Define criterion (loss function) (hint: what loss do we use for multiclass ?)\n", + "criterion = nn.MSELoss()\n", + "\n", + "learning_rate = 0.001\n", + "# TODO: Define optimizer(what is updated during training?)\n", + "optimizer = AdamW(model.parameters(), learning_rate)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "\n", + "# Task 5: Start training for 20 epochs:\n", + "\n", + "# TODO: choose number of epochs, increase it if you have gpus :)\n", + "num_epochs = 20\n", + "# TODO: choose a learning rate (try different values and evaluate results)\n", + "learning_rate = 0.001\n", + "\n", + "\n", + "# Run Training\n", + "train_losses = []\n", + "val_losses = []\n", + "val_accuracies = []\n", + "\n", + "print('Starting Training...')\n", + "for epoch in range(num_epochs):\n", + " # Train one epoch\n", + " train_loss = train_one_epoch(model, optimizer, criterion, train_loader, device)\n", + "\n", + " # Validate\n", + " val_loss = validate(model, criterion, test_loader, device)\n", + "\n", + " train_losses.append(train_loss)\n", + " val_losses.append(val_loss)\n", + "\n", + " print(f'Epoch [{epoch+1}/{num_epochs}], Train Loss: {train_loss:.4f}, Val Loss: {val_loss:.4f}')\n", + "\n", + "print('Training Complete!')" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "# Plotting results\n", + "plt.figure(figsize=(7, 5))\n", + "\n", + "plt.plot(train_losses, label='Train Loss')\n", + "plt.plot(val_losses, label='Validation Loss')\n", + "plt.title('Loss over Epochs')\n", + "plt.xlabel('Epoch')\n", + "plt.ylabel('Loss')\n", + "plt.legend()\n", + "\n", + "plt.tight_layout()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2 (Bonus): Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/402/Q3.ipynb b/submissions_extracted/402/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..97633875ed2b58cba995db88afb5b90f184689b2 --- /dev/null +++ b/submissions_extracted/402/Q3.ipynb @@ -0,0 +1,358 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "from IPython.display import clear_output\n", + "\n", + "%pip install kagglehub catboost xgboost tqdm -q\n", + "\n", + "clear_output()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "import numpy as np\n", + "import pandas as pd\n", + "import matplotlib.pyplot as plt\n", + "import os\n", + "import seaborn as sns\n", + "from tqdm import tqdm\n", + "from catboost import CatBoostClassifier\n", + "from sklearn.model_selection import train_test_split, StratifiedKFold\n", + "from sklearn.preprocessing import StandardScaler, LabelEncoder\n", + "from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Download latest version\n", + "\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q3-exam-data\")\n", + "\n", + "\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "\n", + "data_path = os.path.join(path, 'Q3_data.csv')\n", + "df = pd.read_csv(data_path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "df.head()\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "df.info()\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "print(df.shape) #samples and featuers count\n", + "df.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here(Handle missing values appropriately):\n", + "# Missing values\n", + "print(\"Missing values:\")\n", + "print(df.isnull().sum())\n", + "\n", + "all_cols = df.columns\n", + "print(list(all_cols))\n", + "df = df.dropna(subset=[all_cols])\n", + "\n", + "print(\"-\"*40)\n", + "\n", + "print(\"Missing values:\")\n", + "print(df.isnull().sum())" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 2. Do we have duplicate samples?\n", + "def check_duplicates(df):\n", + " duplicates = df.duplicated().sum()\n", + " print(f\"Number of Duplicate Samples: {duplicates}\")\n", + " if duplicates > 0:\n", + " print(\"Dropping Duplicates...\")\n", + " df.drop_duplicates(inplace=True)\n", + " print(\"Duplicates Dropped.\")\n", + " else:\n", + " print(\"No Duplicate Samples Found.\")\n", + "\n", + "check_duplicates(df)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "# 3. Do we have categorical columns?\n", + "categorical_cols = df.select_dtypes(include=[\"object\"]).columns\n", + "print(\"Do we have categorical columns?\")\n", + "print(\"Categorical Columns:\", list(categorical_cols))" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "from sklearn.preprocessing import StandardScaler\n", + "\n", + "numerical_cols = df.select_dtypes(include=[\"number\"]).columns.drop(\"Target\")\n", + "\n", + "scaler = StandardScaler()\n", + "\n", + "# scale\n", + "df[numerical_cols] = scaler.fit_transform(df[numerical_cols])\n", + "\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "fig, axes = plt.subplots(1, 3, figsize=(18, 5))\n", + "\n", + "axes[0].hist(df['Target'], bins=50, edgecolor='black', color='skyblue')\n", + "axes[0].set_title('Target Distribution (look imbalanced)')\n", + "axes[0].set_xlabel('Target')\n", + "axes[0].set_ylabel('Frequency')\n", + "\n", + "axes[1].hist(df['P_2'], bins=50, edgecolor='black', color='salmon')\n", + "axes[1].set_title('P_2 Distribution')\n", + "axes[1].set_xlabel('P_2')\n", + "axes[1].set_ylabel('Frequency')\n", + "\n", + "axes[2].hist(df['D_87'], bins=30, edgecolor='black', color='lightgreen')\n", + "axes[2].set_title('D_87 Distribution (almost all NAN)')\n", + "axes[2].set_xlabel('D_87')\n", + "axes[2].set_ylabel('Frequency')\n", + "\n", + "plt.tight_layout() # This stops the titles from overlapping\n", + "plt.show()\n", + "\n", + "print(\"Rule of thumb: If class distributions are not equal, then our data is imbalanced. \")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "# X, y initilize\n", + "\n", + "X = df.drop(\"Target\", axis=1).astype(float)\n", + "y = df['Target'].astype(float) # play around with this float to get different accuracym, might be higher" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:\n", + "from sklearn.model_selection import StratifiedKFold\n", + "from catboost import CatBoostRegressor\n", + "\n", + "models = {\n", + " \"CatBoost\": CatBoostRegressor(verbose=0)\n", + "}\n", + "\n", + "\n", + "\n", + "# cl train\n", + "\n", + "all_results = {}\n", + "\n", + "for name in models:\n", + " all_results[name] = {'accuracy': [], 'precision': [], 'recall': [], 'f1': []}\n", + "\n", + "\n", + "n_splits = 5 # K\n", + "\n", + "# Stratified 5-Fold Cross-Validation, shuffled\n", + "skf = StratifiedKFold(n_splits=n_splits, shuffle=True, random_state=42)\n", + "\n", + "for fold_idx, (train_index, test_index) in enumerate(skf.split(X, y)):\n", + " print(f\"\\nFold {fold_idx + 1}/{n_splits}\")\n", + "\n", + " # 1. Split data\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", + " # 2. Train & Validate sklearn models\n", + " for model_name, model in models.items():\n", + " print(f\"Training {model_name}...\")\n", + " model.fit(X_train, y_train) # train\n", + " y_pred = model.predict(X_test) # validate\n", + "\n", + " # 3. Save metrics for that model in this fold\n", + " accuracy = accuracy_score(y_test, y_pred)\n", + " precision = precision_score(y_test, y_pred, zero_division=0)\n", + " recall = recall_score(y_test, y_pred, zero_division=0)\n", + " f1 = f1_score(y_test, y_pred, zero_division=0)\n", + "\n", + " #------ in multi class we use theesee:\n", + " accuracy = accuracy_score(y_test, y_pred)\n", + " precision = precision_score(y_test, y_pred, average='weighted', zero_division=0)\n", + " recall = recall_score(y_test, y_pred, average='weighted', zero_division=0)\n", + " f1 = f1_score(y_test, y_pred, average='weighted', zero_division=0)\n", + "\n", + " all_results[model_name]['accuracy'].append(accuracy)\n", + " all_results[model_name]['precision'].append(precision)\n", + " all_results[model_name]['recall'].append(recall)\n", + " all_results[model_name]['f1'].append(f1)\n", + "\n", + "\n", + " accuracy = accuracy_score(y_test, y_pred)\n", + " precision_macro = precision_score(y_test, y_pred, average='macro', zero_division=0)\n", + " recall_macro = recall_score(y_test, y_pred, average='macro', zero_division=0)\n", + " f1_macro = f1_score(y_test, y_pred, average='macro', zero_division=0)\n", + "\n", + "\n", + "# show results\n", + "for model_name in all_results:\n", + " print(f\"\\n{model_name}:\")\n", + " print(f\" Accuracy: {np.mean(all_results[model_name]['accuracy']):.4f}\")\n", + " print(f\" Precision: {np.mean(all_results[model_name]['precision']):.4f}\")\n", + " print(f\" Recall: {np.mean(all_results[model_name]['recall']):.4f}\")\n", + " print(f\" F1-Score: {np.mean(all_results[model_name]['f1']):.4f}\")\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "feature_cols = df.drop(\"Target\", axis=1).columns\n", + "print(list(feature_cols))" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "\n", + "# Task 1: Write your code here:\n", + "# Feature importance\n", + "feature_cols = df.drop(\"Target\", axis=1).columns\n", + "print(list(feature_cols))\n", + "\n", + "feature_importance = pd.DataFrame({\n", + " 'feature': feature_cols,\n", + " 'importance': model.feature_importances_\n", + "}).sort_values('importance', ascending=False)\n", + "\n", + "plt.figure(figsize=(22, 12))\n", + "plt.barh(feature_importance['feature'], feature_importance['importance'])\n", + "plt.xlabel('Importance')\n", + "plt.title('Feature Importance')\n", + "plt.gca().invert_yaxis()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "print(\"P_2 is the golden feature\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/403/Q1.ipynb b/submissions_extracted/403/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..ffbd571a4c4d87c22cbd286a95ebe9955a650257 --- /dev/null +++ b/submissions_extracted/403/Q1.ipynb @@ -0,0 +1,337 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q1-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import pandas as pd\n", + "import numpy as np\n", + "import os\n", + "import matplotlib.pyplot as plt\n", + "import seaborn as sns\n", + "from sklearn.model_selection import train_test_split\n", + "from sklearn.preprocessing import StandardScaler\n", + "from sklearn.linear_model import LogisticRegression\n", + "from sklearn.metrics import accuracy_score, confusion_matrix, classification_report" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "foodDel_path = os.path.join(path, 'Q1_data.csv')\n", + "df = pd.read_csv(foodDel_path)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "df.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "df.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "plt.figure(figsize=(10, 5))\n", + "plt.hist(df['Delivery_Time'].dropna(), bins=30, edgecolor='black')\n", + "plt.title('Delivery Time')\n", + "plt.xlabel('Time')\n", + "plt.ylabel('Frequency')\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "df.drop(columns=['Order_ID'], inplace=True)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "# Analyze missing values\n", + "missing_percentage = (df.isnull().sum() / len(df)) * 100\n", + "missing_data = pd.DataFrame({\n", + " 'Column': missing_percentage.index,\n", + " 'Missing_Percentage': missing_percentage.values\n", + "})\n", + "missing_data = missing_data[missing_data['Missing_Percentage'] > 0].sort_values('Missing_Percentage', ascending=False)\n", + "\n", + "print(\"Missing Data Analysis :\")\n", + "missing_data.head(10)\n", + "\n", + "#df_clean['type2'] = df_clean['type2'].fillna('none')\n", + "#df['col'].fillna(df['col'].mean())\n", + "df['Delivery_Time']= df['Delivery_Time'].fillna(df['Delivery_Time']).mean()\n", + "df['Weather'] =df['Weather'].fillna(df['Weather']).mode()\n", + "df['Traffic_Level'] = df['Traffic_Level'].fillna(df['Traffic_Level']).mode()\n", + "df['Time_of_Day'] = df['Time_of_Day'].fillna(df['Time_of_Day']).mode()\n", + "df['Courier_Experience_yrs'] = df['Courier_Experience_yrs'].fillna(df['Courier_Experience_yrs']).mode()\n", + "print(\"Missing Data Analysis:\")\n", + "missing_data.head(10)\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "#df = df.drop_duplicates\n", + "missing_data.head(10)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "cols = ['Distance_km', 'Weather','Traffic_Level',\t'Time_of_Day',\t'Vehicle_Type', 'Preparation_Time_min', 'Preparation_Time_min', 'Courier_Experience_yrs','Delivery_Tim']\n", + "df_clean = df.copy()\n", + "#df_clean\n", + "#df_clean.drop(columns=['Delivery_Time'], inplace=True)\n", + "df_clean.info()\n", + "\n", + "\n", + "'''\n", + " Distance_km 1663 non-null float64\n", + " 2 Weather 1608 non-null object\n", + " 3 Traffic_Level 1612 non-null object\n", + " 4 Time_of_Day 1613 non-null object\n", + " 5 Vehicle_Type 1663 non-null object\n", + " 6 Preparation_Time_min 1663 non-null int64\n", + " 7 Courier_Experience_yrs 1614 non-null float64\n", + " 8 Delivery_Time\n", + "'''\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "from sklearn.preprocessing import StandardScaler, LabelEncoder\n", + "\n", + "categorical_cols = ['Distance_km', 'Weather',\t'Traffic_Level',\t'Time_of_Day',\t'Vehicle_Type']\n", + "for col in categorical_cols:\n", + " le = LabelEncoder()\n", + " df_clean[col] = le.fit_transform(df_clean[col].astype(str))\n", + "\n", + "df_clean.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "#X = df_clean\n", + "#y = df['Delivery_Time']\n", + "\n", + "# Train-test split (80% train, 20% test)\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n", + "print(f\"Train: {X_train.shape}, Test: {X_test.shape}\")\n", + "\n", + "scaler = StandardScaler()\n", + "X_train_scaled = scaler.fit_transform(X_train)\n", + "X_test_scaled = scaler.transform(X_test)\n", + "\n", + "print(f\"\\nScaled ranges - Min: {X_train_scaled.min():.2f}, Max: {X_train_scaled.max():.2f}\")\n", + "pd.DataFrame(X_train_scaled, columns=X_train.columns).head(3)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 6: Write your code here:\n", + "def check_target_imbalance(df, target_column):\n", + " print(\"Target Distribution:\")\n", + " print(df[target_column].value_counts(normalize=True))\n", + " sns.countplot(x=df[target_column])\n", + " plt.title(\"Target Distribution\")\n", + " plt.show()\n", + "\n", + "check_target_imbalance(df, \"Delivery_Time\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "#X = df_clean\n", + "#y = df['Delivery_Time']\n", + "feature_cols = ['Distance_km', 'Weather','Traffic_Level',\t'Time_of_Day',\t'Vehicle_Type', 'Preparation_Time_min', 'Preparation_Time_min', 'Courier_Experience_yrs']\n", + "\n", + "X = df_clean[feature_cols]\n", + "y = df_clean['Delivery_Time']\n", + "\n", + "# Stratified split\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42, stratify=y)\n", + "print(f\"Train: {X_train.shape}, Test: {X_test.shape}\")\n", + "print(f\"Legendary in train: {y_train.sum()}, in test: {y_test.sum()}\")\n", + "\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n", + "print(f\"Train: {X_train.shape}, Test: {X_test.shape}\")\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "!pip install RandomForest" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "from sklearn.metrics import mean_absolute_error, mean_squared_error\n", + "# Task 2,3,4,5: Write your code here:\n", + "\n", + "\n", + "from sklearn.model_selection import train_test_split, StratifiedKFold, cross_val_score\n", + "from sklearn.ensemble import RandomForestRegressor\n", + "#sklearn.ensemble.RandomForest\n", + "#sklearn.ensemble.RandomForest\n", + "n_splits = 5 # K=5 Folds\n", + "\n", + "# Stratified 5-Fold Cross-Validation, shuffled\n", + "skf = StratifiedKFold(n_splits=n_splits, shuffle=True, random_state=42)\n", + "\n", + "model = RandomForestRegressor(n_estimators=100, max_depth=20, random_state=42, n_jobs=-1)\n", + "model.fit(X_train_scaled, y_train)\n", + "print(\"Model trained!\")\n", + "\n", + "y_pred = model.predict(X_test_scaled)\n", + "\n", + "mae = mean_absolute_error(y_test, y_pred)\n", + "\n", + "\n", + "print(f\"MAE: ${mae:,.2f}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "# Feature importance\n", + "feature_importance = pd.DataFrame({\n", + " 'feature': feature_cols,\n", + " 'importance': model.feature_importances_\n", + "}).sort_values('importance', ascending=False)\n", + "\n", + "plt.figure(figsize=(10, 6))\n", + "plt.barh(feature_importance['feature'], feature_importance['importance'])\n", + "plt.xlabel('Importance')\n", + "plt.title('Feature Importance')\n", + "plt.gca().invert_yaxis()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/403/Q2.ipynb b/submissions_extracted/403/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..98a1330c732408bc0b77f3cc6248c3027ce0570d --- /dev/null +++ b/submissions_extracted/403/Q2.ipynb @@ -0,0 +1,357 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q2-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import os\n", + "import pandas as pd\n", + "import numpy as np\n", + "from PIL import Image\n", + "from sklearn.model_selection import train_test_split\n", + "\n", + "# Load Labels\n", + "labels_df = pd.read_csv(os.path.join(path, \"labels.csv\"))\n", + "img_dir = os.path.join(path, \"images\")\n", + "\n", + "images = []\n", + "ages = []\n", + "\n", + "# Load Images and Resize\n", + "print(\"Loading images...\")\n", + "for index, row in labels_df.iterrows():\n", + " img_name = row.iloc[0]\n", + " age = row.iloc[1]\n", + " img_path = os.path.join(img_dir, img_name)\n", + "\n", + " if os.path.exists(img_path):\n", + " img = Image.open(img_path).convert('RGB')\n", + " img_array = np.array(img) / 255.0 # Normalize pixel values to [0, 1]\n", + " images.append(img_array)\n", + " ages.append(age)\n", + "\n", + "X = np.array(images)\n", + "y = np.array(ages)\n", + "\n", + "# Transpose image dimensions to match PyTorch format (N, C, H, W)\n", + "X = np.transpose(X, (0, 3, 1, 2))\n", + "\n", + "# Split Data\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n", + "\n", + "print(f\"X_train shape: {X_train.shape}\")\n", + "print(f\"X_test shape: {X_test.shape}\")\n", + "print(f\"y_train shape: {y_train.shape}\")\n", + "print(f\"y_test shape: {y_test.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import torch\n", + "import torch.nn as nn\n", + "import torch.optim as optim\n", + "from torch.utils.data import DataLoader, TensorDataset\n", + "import pandas as pd\n", + "from sklearn.model_selection import train_test_split\n", + "from sklearn.preprocessing import StandardScaler\n", + "from sklearn.datasets import fetch_california_housing\n", + "import torch.nn.functional as F" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 1. Convert Numpy arrays to PyTorch Tensors\n", + "X_train = torch.tensor(X_train, dtype=torch.float32)\n", + "X_test = torch.tensor(X_test, dtype=torch.float32)\n", + "y_train = torch.tensor(y_train, dtype=torch.long)\n", + "y_test = torch.tensor(y_test, dtype=torch.long)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 2. Create TensorDataset objects\n", + "\n", + "train_dataset = TensorDataset(X_train, y_train)\n", + "test_dataset = TensorDataset(X_test, y_test)\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 3. Create DataLoaders\n", + "train_loader = DataLoader(train_dataset, batch_size=32, shuffle=True)\n", + "test_loader = DataLoader(test_dataset, batch_size=32, shuffle=False)\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 4. Print shape of one batch\n", + "X_batch, y_batch = next(iter(train_loader))\n", + "print(f\"Training batch input shape: {X_batch.shape}\")\n", + "print(f\"Training batch labels shape: {y_batch.shape}\")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 5. Display sample images\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your model class here:\n", + "class NN4Layer(nn.Module):\n", + "\n", + " def __init__(self, input_dim, hidden_dim, output_dim):\n", + " super(NN4Layer, self).__init__()\n", + "\n", + " # First linear layer: input features -> hidden layer\n", + " self.layer1 = nn.Linear(input_dim, hidden_dim)\n", + "\n", + " # Second linear layer: hidden layer -> hidden layer\n", + " self.layer2 = nn.Linear(hidden_dim, hidden_dim)\n", + "\n", + " # Third linear layer: hidden layer -> hidden layer\n", + " self.layer3 = nn.Linear(hidden_dim, hidden_dim)\n", + "\n", + " # Output layer: hidden layer -> number of classes (logits)\n", + " self.layer4 = nn.Linear(hidden_dim, output_dim)\n", + "\n", + " # ReLU activation for non-linearity\n", + " self.relu = nn.ReLU()\n", + "\n", + " # Defines how input data flows through the network\n", + " def forward(self, x):\n", + " # First hidden layer\n", + " a1 = self.relu(self.layer1(x))\n", + "\n", + " # Second hidden layer\n", + " a2 = self.relu(self.layer2(a1))\n", + "\n", + " # Third hidden layer\n", + " a3 = self.relu(self.layer3(a2))\n", + "\n", + " # Output layer (raw scores / logits)\n", + " output = self.layer4(a3) # we said we'll use softmax, where is it? ¯\\(ツ)/¯\n", + "\n", + " return output" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your training loop here:\n", + "def train_one_epoch(model, optimizer, criterion, train_loader, device):\n", + " # Set the model to training mode\n", + " model.train()\n", + "\n", + " running_loss = 0.0\n", + "\n", + " for X_batch, y_batch in train_loader:\n", + " # Move batch to the selected device\n", + " X_batch = X_batch.to(device) # shape: (batch_size, num_features)\n", + " y_batch = y_batch.to(device) # shape: (batch_size,)\n", + "\n", + " # Forward pass (outputs are logits)\n", + " outputs = model(X_batch) # shape: (batch_size, num_classes)\n", + " loss = criterion(outputs, y_batch)\n", + "\n", + " # Backward pass & optimization\n", + " optimizer.zero_grad() # Clear previous gradients\n", + " loss.backward() # Compute gradients\n", + " optimizer.step() # Update model parameters\n", + "\n", + " running_loss += loss.item()\n", + "\n", + " # Average loss over all batches\n", + " avg_loss = running_loss / len(train_loader)\n", + "\n", + " return avg_loss" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your validation loop here:\n", + "\n", + "def validate(model, criterion, test_loader, device):\n", + " # Set the model to evaluation mode\n", + " model.eval()\n", + "\n", + " running_loss = 0.0\n", + " correct = 0\n", + " total = 0\n", + "\n", + " with torch.no_grad():\n", + " for X_batch, y_batch in test_loader:\n", + " # Move data to device\n", + " X_batch = X_batch.to(device) # shape: (batch_size, num_features)\n", + " y_batch = y_batch.to(device) # shape: (batch_size,)\n", + "\n", + " # Forward pass\n", + " outputs = model(X_batch) # shape: (batch_size, num_classes)\n", + " loss = criterion(outputs, y_batch)\n", + " running_loss += loss.item()\n", + "\n", + " # Apply Softmax to get probabilities\n", + " probabilities = F.softmax(outputs, dim=1)\n", + "\n", + " # Pick the classes with highest probabilities\n", + " predicted = torch.argmax(probabilities, dim=1)\n", + "\n", + " # Accuracy calculation\n", + " correct += (predicted == y_batch).sum().item()\n", + " total += y_batch.size(0)\n", + "\n", + " avg_loss = running_loss / len(test_loader)\n", + " accuracy = correct / total\n", + "\n", + " return avg_loss, accuracy" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Define device, model, loss, optimizer:\n", + "from torch.optim import AdamW\n", + "device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n", + "\n", + "# Model parameters\n", + "input_dim = X_train.shape[1] # Number of tabular features\n", + "hidden_dim = 9 # Design choice\n", + "output_dim = 4 # Weather classes: Rainy, Sunny, Cloudy, Snowy\n", + "\n", + "# Instantiate model\n", + "model = NN4Layer(input_dim, hidden_dim, output_dim).to(device)\n", + "\n", + "# Print the model architecture\n", + "print(\"Model Architecture:\\n\")\n", + "print(model)\n", + "\n", + "# Calculate the total number of trainable parameters\n", + "total_params = sum(p.numel() for p in model.parameters() if p.requires_grad)\n", + "print(f\"\\nTotal trainable parameters: {total_params}\")\n", + "\n", + "num_epochs = 1\n", + "learning_rate = 0.001\n", + "\n", + "# Define criterion (loss function) - using CrossEntropyLoss as model now outputs logits\n", + "criterion = nn.CrossEntropyLoss()\n", + "# Define optimizer\n", + "optimizer = AdamW(model.parameters(), learning_rate)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Start training for 20 epochs:\n", + "# Run Training\n", + "train_losses = []\n", + "val_losses = []\n", + "val_accuracies = []\n", + "\n", + "print('Starting Training...')\n", + "for epoch in range(num_epochs):\n", + " # Train one epoch\n", + " train_loss = train_one_epoch(model, optimizer, criterion, train_loader, device)\n", + "\n", + " # Validate\n", + " val_loss, val_accuracy = validate(model, criterion, test_loader, device)\n", + "\n", + " train_losses.append(train_loss)\n", + " val_losses.append(val_loss)\n", + " val_accuracies.append(val_accuracy)\n", + "\n", + " #print(f'Epoch [{epoch+1}/{num_epochs}], Train Loss: {train_loss:.4f}, Val Loss: {val_loss:.4f}, Val Accuracy: {val_accuracy:.4f}')\n", + "\n", + "print('Training Complete!')" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2 (Bonus): Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/403/Q3.ipynb b/submissions_extracted/403/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..a50417e9cd84e117c9dba93f53bfe3cb44dea04c --- /dev/null +++ b/submissions_extracted/403/Q3.ipynb @@ -0,0 +1,213 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import pandas as pd\n", + "import numpy as np\n", + "import os\n", + "import matplotlib.pyplot as plt\n", + "import seaborn as sns\n", + "from sklearn.model_selection import train_test_split\n", + "from sklearn.preprocessing import StandardScaler\n", + "from sklearn.linear_model import LogisticRegression\n", + "from sklearn.metrics import accuracy_score, confusion_matrix, classification_report" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "\n", + "\n", + "# Download latest version\n", + "\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q3-exam-data\")\n", + "\n", + "\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "data_path = os.path.join(path, 'Q3_data.csv')\n", + "df = pd.read_csv(data_path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "df.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "df.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "missing_percentage = (df.isnull().sum() / len(df)) * 100\n", + "missing_data = pd.DataFrame({\n", + " 'Column': missing_percentage.index,\n", + " 'Missing_Percentage': missing_percentage.values\n", + "})\n", + "missing_data = missing_data[missing_data['Missing_Percentage'] > 0].sort_values('Missing_Percentage', ascending=False)\n", + "\n", + "print(\"Missing Data Analysis:\")\n", + "missing_data.head(10)\n", + "\n", + "# there are 10 columns that almost empty so im gonna drop it\n", + "df.drop(columns=['D_87','D_88','D_39','D_110','D_111','D_108','D_42','D_73','D_135','D_136'], inplace=True)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "#df = df.drop_duplicates" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "#there are no categorical features so no encoding needed" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "X = df\n", + "#df_clean = df\n", + "#df_clean.drop()\n", + "y = df['Target']\n", + "\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n", + "print(f\"Train: {X_train.shape}, Test: {X_test.shape}\")\n", + "\n", + "scaler = StandardScaler()\n", + "X_train_scaled = scaler.fit_transform(X_train)\n", + "X_test_scaled = scaler.transform(X_test)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "plt.figure(figsize=(10, 5))\n", + "plt.hist(df['Target'].dropna(), bins=30, edgecolor='black')\n", + "plt.title('Target Frquency')\n", + "plt.xlabel('Target')\n", + "plt.ylabel('Frequency')\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/404/Q1.ipynb b/submissions_extracted/404/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..364dd8a45999c3f8ddcda38f928950e12f848c6b --- /dev/null +++ b/submissions_extracted/404/Q1.ipynb @@ -0,0 +1,301 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q1-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "import pandas as pd\n", + "import os\n", + "csv_path = os.path.join(path, \"Q1_data.csv\")\n", + "\n", + "df = pd.read_csv(csv_path)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "df.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "df.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "import seaborn as sns\n", + "\n", + "sns.histplot(df['Delivery_Time'])" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "df_dropped_id = df.drop('Order_ID',axis=1)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "n =df_dropped_id.isnull().sum()\n", + "print(n)\n", + "#i will fill every thing with the 0\n", + "df['Traffic_Level'] = df['Traffic_Level'].fillna(df['Traffic_Level'].mode()[0])\n", + "df['Time_of_Day'] = df['Time_of_Day'].fillna(df['Time_of_Day'].mode()[0])\n", + "df['Courier_Experience_yrs'] = df['Courier_Experience_yrs'].fillna(df['Courier_Experience_yrs'].mode()[0])\n", + "df['Delivery_Time'] = df['Delivery_Time'].fillna(df['Delivery_Time'].mode()[0])\n", + "\n", + "\n", + "df.head()\n", + "\n", + "df.info()\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "def check_duplicates(df):\n", + "\n", + " # Checks the duplicates in the dataframe\n", + " duplicates = df.duplicated().sum()\n", + "\n", + " if duplicates > 0:\n", + " print(\"There are duplicates: \" + str(duplicates))\n", + " df=df.drop_duplicates()\n", + " duplicates = df.duplicated().sum()\n", + "\n", + " print(\"duplicates after handling: \" + str(duplicates))\n", + " else:\n", + " print(\"There are no duplicates\")\n", + "\n", + "check_duplicates(df)\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "from sklearn.preprocessing import LabelEncoder\n", + "\n", + "# To find Categorical columns:\n", + "categorical_cols = df.select_dtypes(include=[\"object\"]).columns\n", + "\n", + "# There are three, we will use LabelEncoder() for each of them:\n", + "for categorical in categorical_cols:\n", + " le = LabelEncoder()\n", + " df[categorical] = le.fit_transform(df[categorical])\n", + "\n", + "\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "from sklearn.preprocessing import StandardScaler\n", + "import numpy as np\n", + "\n", + "# Defining the scaler\n", + "scaler = StandardScaler()\n", + "\n", + "\n", + "# Choosing the numerical columns\n", + "numerical_cols = df.select_dtypes(include=[\"Float64\",\"int64\"]).columns.drop(\"Delivery_Time\")\n", + "df[numerical_cols] = scaler.fit_transform(df[numerical_cols])\n", + "\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 6: Write your code here:\n", + "import seaborn as sns\n", + "# Takes in the dataframe + the target column which we will check\n", + "def imbalance_func(df, target_col):\n", + "\n", + " # checking the number of entries of each class in the target\n", + " print(df[target_col].value_counts(normalize=True))\n", + "\n", + " #Visualizing the results\n", + " sns.countplot(x=df[target_col])\n", + "\n", + "\n", + "imbalance_func(df, \"Delivery_Time\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "import numpy as np\n", + "X = df.drop(\"Delivery_Time\", axis=1)\n", + "y = df[\"Delivery_Time\"]\n", + "print(np.shape(X))\n", + "print(np.shape(y))" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:\n", + "from sklearn.model_selection import KFold, StratifiedKFold, cross_val_score\n", + "from sklearn.ensemble import RandomForestRegressor\n", + "from sklearn.metrics import mean_absolute_error\n", + "import numpy as np\n", + "\n", + "scores_time = []\n", + "scores_avg =0\n", + "\n", + "skf = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)\n", + "\n", + "for train_index, test_index in skf.split(X, y):\n", + " # Split data into training and testing sets using the indices defined by the KFold\n", + " X_Train, X_Test = X.loc[train_index, :], X.loc[test_index, :]\n", + " y_Train, y_Test = y.iloc[train_index], y.iloc[test_index]\n", + "\n", + " # Train the model on the training data\n", + " model = RandomForestRegressor(n_estimators=150, max_depth=20, random_state=42).fit(X_Train, y_Train)\n", + "\n", + " # Predict on the test set\n", + " y_pred = model.predict(X_Test)\n", + "\n", + " # Metric from the sklearn.metrics package\n", + " scores_time.append(mean_absolute_error(y_Test, y_pred))\n", + "scores_avg= np.mean(scores_time)\n", + "print(f\"MAE: {(scores_avg):.2f}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import matplotlib.pyplot as plt\n", + "feature_importance = pd.DataFrame({\n", + " 'feature': X.columns,\n", + " 'importance': model.feature_importances_\n", + "}).sort_values('importance', ascending=True)\n", + "\n", + "plt.figure(figsize=(10, 8))\n", + "plt.barh(feature_importance['feature'], feature_importance['importance'])\n", + "plt.xlabel('Importance')\n", + "plt.title('Feature Importance')\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 6: Write your code here:\n", + "import seaborn as sns\n", + "# Takes in the dataframe + the target column which we will check\n", + "def imbalance_func(df, target_col):\n", + "\n", + " # checking the number of entries of each class in the target\n", + " print(df[target_col].value_counts(normalize=True))\n", + "\n", + " #Visualizing the results\n", + " sns.countplot(x=df[target_col])\n", + "\n", + "\n", + "imbalance_func(df, \"Delivery_Time\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/404/Q2.ipynb b/submissions_extracted/404/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..61f0ad8dfee295b396227fbca1bd117f1cdf5f80 --- /dev/null +++ b/submissions_extracted/404/Q2.ipynb @@ -0,0 +1,379 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q2-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import os\n", + "import pandas as pd\n", + "import numpy as np\n", + "from PIL import Image\n", + "from sklearn.model_selection import train_test_split\n", + "from torch import torch, torch_version\n", + "import torch.nn as nn\n", + "import kagglehub\n", + "import pandas as pd\n", + "import torch\n", + "import torch.nn as nn\n", + "from torch.optim import AdamW\n", + "import matplotlib.pyplot as plt\n", + "import torch.nn.functional as F\n", + "from torch.utils.data import DataLoader, TensorDataset\n", + "from sklearn.model_selection import train_test_split\n", + "from sklearn.preprocessing import StandardScaler, LabelEncoder\n", + "\n", + "\n", + "# Load Labels\n", + "labels_df = pd.read_csv(os.path.join(path, \"labels.csv\"))\n", + "img_dir = os.path.join(path, \"images\")\n", + "\n", + "images = []\n", + "ages = []\n", + "\n", + "# Load Images and Resize\n", + "print(\"Loading images...\")\n", + "for index, row in labels_df.iterrows():\n", + " img_name = row.iloc[0]\n", + " age = row.iloc[1]\n", + " img_path = os.path.join(img_dir, img_name)\n", + "\n", + " if os.path.exists(img_path):\n", + " img = Image.open(img_path).convert('RGB')\n", + " img_array = np.array(img) / 255.0 # Normalize pixel values to [0, 1]\n", + " images.append(img_array)\n", + " ages.append(age)\n", + "\n", + "X = np.array(images)\n", + "y = np.array(ages)\n", + "\n", + "# Transpose image dimensions to match PyTorch format (N, C, H, W)\n", + "X = np.transpose(X, (0, 3, 1, 2))\n", + "\n", + "# Split Data\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n", + "\n", + "print(f\"X_train shape: {X_train.shape}\")\n", + "print(f\"X_test shape: {X_test.shape}\")\n", + "print(f\"y_train shape: {y_train.shape}\")\n", + "print(f\"y_test shape: {y_test.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 1. Convert Numpy arrays to PyTorch Tensors\n", + "\n", + "\n", + "\n", + "X_train = torch.from_numpy(X_train)\n", + "X_test = torch.from_numpy(X_test)\n", + "y_train = torch.from_numpy(y_train)\n", + "y_test = torch.from_numpy(y_test)\n", + "\n", + "X_train = X_train.to(torch.float32)\n", + "print(X_train.dtype)\n", + "X_test = X_test.to(torch.float32)\n", + "print(X_test.dtype)\n", + "y_train = y_train.to(torch.float32)\n", + "print(y_train.dtype)\n", + "y_test = y_test.to(torch.float32)\n", + "print(y_test.dtype)\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 2. Create TensorDataset objects\n", + "\n", + "train_dataset = TensorDataset(X_train, y_train)\n", + "test_dataset = TensorDataset(X_test, y_test)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 3. Create DataLoaders\n", + "train_loader = DataLoader(train_dataset, batch_size=32, shuffle=True,num_workers=6)\n", + "test_loader = DataLoader(test_dataset, batch_size=32, shuffle=False,num_workers=6)\n", + "\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 4. Print shape of one batch\n", + "X_batch, y_batch = next(iter(train_loader))\n", + "print(f\"Training batch input shape: {X_batch.shape}\")\n", + "print(f\"Training batch labels shape: {y_batch.shape}\")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 5. Display sample images\n", + "images, labels = next(iter(train_loader))\n", + "\n", + "# Display the first 6 images in the batch\n", + "plt.figure(figsize=(8, 4))\n", + "\n", + "for i in range(6):\n", + " plt.subplot(2, 3, i + 1)\n", + "\n", + " # Convert from (C, H, W) to (H, W, C) for matplotlib\n", + " img = images[i].permute(1, 2, 0)\n", + "\n", + " plt.imshow(img)\n", + " plt.title(f\"Label: {labels[i].item()}\")\n", + " plt.axis('off')\n", + "\n", + "plt.tight_layout()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your model class here:\n", + "class NN4Layer(nn.Module):\n", + "\n", + " def __init__(self, input_dim, hidden_dim, output_dim):\n", + " super(NN4Layer, self).__init__()\n", + "\n", + " # First linear layer: input features -> hidden layer\n", + " self.layer1 = nn.Linear(input_dim, hidden_dim)\n", + "\n", + " # Second linear layer: hidden layer -> hidden layer\n", + " self.layer2 = nn.Linear(hidden_dim, hidden_dim)\n", + "\n", + " self.layer3 = nn.Linear(hidden_dim, hidden_dim)\n", + "\n", + " # Output layer: hidden layer -> number of classes (logits)\n", + " self.layer4 = nn.Linear(hidden_dim, output_dim)\n", + "\n", + " # ReLU activation for non-linearity\n", + " self.relu = nn.ReLU()\n", + "\n", + " # Defines how input data flows through the network\n", + " def forward(self, x):\n", + " # First hidden layer\n", + " z1 = self.layer1(x)\n", + " a1 = self.relu(z1)\n", + "\n", + " # Second hidden layer\n", + " z2 = self.layer2(a1)\n", + " a2 = self.relu(z2)\n", + "\n", + " z3 = self.layer3(a2)\n", + " a3 = self.relu(z3)\n", + "\n", + " # Output layer (raw scores / logits)\n", + " output = self.layer4(a3) # there is something missing here, remember? :)\n", + "\n", + " return output" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your training loop here:\n", + "def train_one_epoch(model, optimizer, criterion, train_loader, device):\n", + " # Set the model to training mode\n", + " model.train()\n", + "\n", + " running_loss = 0.0\n", + "\n", + " for X_batch, y_batch in train_loader:\n", + " # Move batch to the selected device\n", + " X_batch = X_batch.view(X_batch.size(0), -1).to(device)\n", + " y_batch = y_batch.to(device)\n", + "\n", + " # Forward pass\n", + " outputs = model(X_batch) # shape: (batch_size, 10)\n", + " loss = criterion(outputs, y_batch)\n", + "\n", + " # Backward pass & optimization\n", + " optimizer.zero_grad() # Clear previous gradients\n", + " loss.backward() # Compute gradients\n", + " optimizer.step() # Update model parameters\n", + "\n", + " running_loss += loss.item()\n", + "\n", + " # Average loss over all batches\n", + " avg_loss = running_loss / len(train_loader)\n", + "\n", + " return avg_loss" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your validation loop here:\n", + "def validate(model, criterion, test_loader, device):\n", + " # Set the model to evaluation mode\n", + " model.eval()\n", + "\n", + " running_loss = 0.0\n", + "\n", + "\n", + " with torch.no_grad():\n", + " for X_batch, y_batch in test_loader:\n", + " # Move data to device\n", + " X_batch = X_batch.view(X_batch.size(0), -1).to(device)\n", + " y_batch = y_batch.to(device)\n", + " # Forward pass\n", + " outputs = model(X_batch) # shape: (batch_size, 10)\n", + " loss = criterion(outputs, y_batch)\n", + " running_loss += loss.item()\n", + "\n", + "\n", + "\n", + " avg_loss = running_loss / len(test_loader)\n", + "\n", + "\n", + " return avg_loss\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Define device, model, loss, optimizer:\n", + "# Device setup\n", + "device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n", + "print(device)\n", + "# Model parameters\n", + "input_dim = 3* 36*36 # MNIST images flattened\n", + "hidden_dim = 64 # Design choice\n", + "output_dim = 1 # Digits 0–9\n", + "\n", + "# Instantiate model\n", + "model = NN4Layer(input_dim, hidden_dim, output_dim).to(device)\n", + "\n", + "# Print the model architecture\n", + "print(\"Model Architecture:\\n\")\n", + "print(model)\n", + "\n", + "# Calculate the total number of trainable parameters\n", + "total_params = sum(p.numel() for p in model.parameters() if p.requires_grad)\n", + "print(f\"\\nTotal trainable parameters: {total_params}\")\n", + "\n", + "lr= 0.001\n", + "criterion = nn.MSELoss()\n", + "optimizer = torch.optim.AdamW(model.parameters(), lr=lr)\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Start training for 20 epochs:\n", + "num_epochs = 20\n", + "train_losses = []\n", + "val_losses = []\n", + "\n", + "print('Starting Training...')\n", + "for epoch in range(num_epochs):\n", + " # Train one epoch\n", + " train_loss = train_one_epoch(model, optimizer, criterion, train_loader, device)\n", + "\n", + " # Validate\n", + " val_loss = validate(model, criterion, test_loader, device)\n", + "\n", + " train_losses.append(train_loss)\n", + " val_losses.append(val_loss)\n", + "\n", + "\n", + " print(f'Epoch [{epoch+1}/{num_epochs}], Train Loss: {train_loss:.4f}, Val Loss: {val_loss:.4f}')\n", + "\n", + "print('Training Complete!')" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "plt.figure(figsize=(7, 5))\n", + "\n", + "plt.plot(train_losses, label='Train Loss')\n", + "plt.plot(val_losses, label='Validation Loss')\n", + "plt.title('Loss over Epochs')\n", + "plt.xlabel('Epoch')\n", + "plt.ylabel('Loss')\n", + "plt.legend()\n", + "\n", + "plt.tight_layout()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2 (Bonus): Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/404/Q3.ipynb b/submissions_extracted/404/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..87cc8e0e9b37b3e6b8893810f389de38d2cc9556 --- /dev/null +++ b/submissions_extracted/404/Q3.ipynb @@ -0,0 +1,275 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "\n", + "\n", + "# Download latest version\n", + "\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q3-exam-data\")\n", + "\n", + "\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "# Task 1: Write your code here:\n", + "import pandas as pd\n", + "import os\n", + "csv_path = os.path.join(path, \"Q3_data.csv\")\n", + "\n", + "df = pd.read_csv(csv_path)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "df.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "df.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "n =df.isnull().sum()\n", + "print(n)\n", + "df = df.fillna(0)\n", + "print(\"\\n\")\n", + "n =df.isnull().sum()\n", + "print(n)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "def check_duplicates(df):\n", + "\n", + " # Checks the duplicates in the dataframe\n", + " duplicates = df.duplicated().sum()\n", + "\n", + " if duplicates > 0:\n", + " print(\"There are duplicates\" + str(duplicates))\n", + " else:\n", + " print(\"There are no duplicates\")\n", + "\n", + "check_duplicates(df)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "from sklearn.preprocessing import LabelEncoder\n", + "\n", + "# To find Categorical columns:\n", + "categorical_cols = df.select_dtypes(include=[\"object\"]).columns\n", + "print(categorical_cols)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "from sklearn.preprocessing import StandardScaler\n", + "import numpy as np\n", + "\n", + "# Defining the scaler\n", + "scaler = StandardScaler()\n", + "\n", + "\n", + "# Choosing the numerical columns\n", + "numerical_cols = df.select_dtypes(include=[\"Float64\",\"int64\"]).columns.drop(\"Target\")\n", + "df[numerical_cols] = scaler.fit_transform(df[numerical_cols])\n", + "\n", + "df" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "import seaborn as sns\n", + "# Takes in the dataframe + the target column which we will check\n", + "def imbalance_func(df, target_col):\n", + "\n", + " # checking the number of entries of each class in the target\n", + " print(df[target_col].value_counts(normalize=True))\n", + "\n", + " #Visualizing the results\n", + " sns.countplot(x=df[target_col])\n", + "\n", + "\n", + "imbalance_func(df, \"Target\")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "X = df.drop(\"Target\", axis=1)\n", + "y = df[\"Target\"]\n", + "print(np.shape(X))\n", + "print(np.shape(y))" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "!pip install catboost" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:\n", + "from sklearn.model_selection import KFold, StratifiedKFold, cross_val_score\n", + "from catboost import CatBoostClassifier\n", + "from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score\n", + "import numpy as np\n", + "\n", + "scores_accuracy = []\n", + "scores_f1 = []\n", + "\n", + "# Stratified 5-Fold Cross-Validation initiation\n", + "skf = StratifiedKFold(n_splits=5, shuffle=False)\n", + "for train_index, test_index in skf.split(X, y):\n", + " # Split data into training and testing sets using the indices defined by the KFold\n", + " X_Train, X_Test = X.loc[train_index, :], X.loc[test_index, :]\n", + " y_Train, y_Test = y.iloc[train_index], y.iloc[test_index]\n", + "\n", + " # Train the model on the training data\n", + " model = CatBoostClassifier(n_estimators=100, max_depth=5, verbose=0).fit(X_Train, y_Train)\n", + "\n", + " # Predict on the test set\n", + " y_pred = model.predict(X_Test)\n", + "\n", + " # Metric from the sklearn.metrics package\n", + " scores_accuracy.append(accuracy_score(y_Test, y_pred))\n", + " scores_f1.append(f1_score(y_Test, y_pred, average='weighted'))" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "print(f\"F1 Score: {np.mean(scores_f1):.4f} (+/- {np.std(scores_f1):.4f})\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import matplotlib.pyplot as plt\n", + "feature_importance = pd.DataFrame({\n", + " 'feature': X.columns,\n", + " 'importance': model.feature_importances_\n", + "}).sort_values('importance', ascending=True,)\n", + "\n", + "plt.figure(figsize=(10, 25))\n", + "plt.barh(feature_importance['feature'], feature_importance['importance'])\n", + "plt.xlabel('Importance')\n", + "plt.title('Feature Importance')\n", + "plt.show()\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "maxi=feature_importance.sort_values('importance', ascending=False,)\n", + "\n", + "print(maxi)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/405/Q1.ipynb b/submissions_extracted/405/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..7634ad1d5b69845a2aed9e5e2e27930b14650c66 --- /dev/null +++ b/submissions_extracted/405/Q1.ipynb @@ -0,0 +1,360 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q1-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "import pandas as pd\n", + "import os\n", + "new_path = os.path.join(path, 'Q1_data.csv')\n", + "\n", + "df = pd.read_csv(new_path)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "df.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "df.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "df[\"Delivery_Time\"].hist()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "df = df.drop(columns=\"Order_ID\", axis=1)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "def check_missing_values(df):\n", + " missing_values = df.isnull().sum()\n", + " print(\"Missing Values per Column:\")\n", + " print(missing_values[missing_values > 0])\n", + " if missing_values.any():\n", + " print(\"\\nHandle Missing Values as needed.\")\n", + " else:\n", + " print(\"\\nNo Missing Values Found.\")\n", + "\n", + "check_missing_values(df)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "#Task 2 countinue\n", + "#we will select all the cat data and fill it with the \"unknown\"\n", + "#if the acc bad we will change it mode or etc\n", + "for col in df.select_dtypes(include=[\"object\"]).columns:\n", + " df[col] = df[col].fillna('unknown')\n", + "\n", + "\n", + "df.head()\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import numpy as np\n", + "\n", + "num_col=df.select_dtypes(include=[\"number\"]).columns\n", + "df[num_col]=df[num_col].fillna(np.mean(df[num_col]))\n", + "check_missing_values(df)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "def check_duplicates(df):\n", + " duplicates = df.duplicated().sum()\n", + " print(f\"Number of Duplicate Samples: {duplicates}\")\n", + " if duplicates > 0:\n", + " print(\"Dropping Duplicates...\")\n", + " df.drop_duplicates(inplace=True)\n", + " print(\"Duplicates Dropped.\")\n", + " else:\n", + " print(\"No Duplicate Samples Found.\")\n", + "\n", + "check_duplicates(df)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "from sklearn.preprocessing import LabelEncoder\n", + "le=LabelEncoder()\n", + "\n", + "for col in df.select_dtypes(include=[\"object\"]).columns:\n", + " df[col] = le.fit_transform(df[col].astype(str))\n", + "\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "from sklearn.preprocessing import StandardScaler\n", + "Scaler=StandardScaler()\n", + "features = df.columns.drop(\"Delivery_Time\")\n", + "\n", + "df[features]=Scaler.fit_transform(df[features])\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 6: Write your code here:\n", + "df[\"Delivery_Time\"].hist()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "feature=df.columns.drop(\"Delivery_Time\")\n", + "X=df[feature]\n", + "y=df[\"Delivery_Time\"]" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "X.head(\n", + ")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "y.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:\n", + "# split ratio (80% train, 20% test)\n", + "from sklearn.model_selection import train_test_split\n", + "\n", + "X_train, X_test, y_train, y_test = train_test_split(\n", + " X, y,\n", + " test_size=0.2, # 20% for test, remaining 80% for train\n", + " random_state=42, # reproducible output\n", + " shuffle=True, # representative splits\n", + ")\n", + "\n", + "print(\"X_train shape:\", X_train.shape)\n", + "print(\"X_test shape:\", X_test.shape)\n", + "print(\"y_train shape:\", y_train.shape)\n", + "print(\"y_test shape:\", y_test.shape)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "from sklearn.model_selection import KFold\n", + "from sklearn.ensemble import RandomForestRegressor\n", + "from sklearn.metrics import mean_absolute_error\n", + "\n", + "\n", + "kf = KFold(n_splits=5, shuffle=True, random_state=42)\n", + "model=RandomForestRegressor()\n", + "mae_scores = []\n", + "# Iterate through folds\n", + "for fold, (train_idx, test_idx) in enumerate(kf.split(X), start=1):\n", + " # indexing for each fold\n", + " X_train, X_test = X.iloc[train_idx], X.iloc[test_idx]\n", + " y_train, y_test = y.iloc[train_idx], y.iloc[test_idx]\n", + "\n", + " # Train model\n", + " model.fit(X_train, y_train)\n", + "\n", + " # Predict\n", + " y_pred = model.predict(X_test)\n", + "\n", + " # Evaluation metrics\n", + " mae_scores.append(mean_absolute_error(y_test, y_pred))\n", + "\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Print Evaluation Metrics\n", + "print(\"\\nModel Evaluation Metrics (K-Fold)\\n\" + \"-\"*40)\n", + "print(f\"MAE : {np.mean(mae_scores):.2f}\")\n", + "print(\"-\"*40)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "\n", + "# Feature importance\n", + "feature_importance = pd.DataFrame({\n", + " 'feature': feature,\n", + " 'importance': model.feature_importances_\n", + "}).sort_values('importance', ascending=False)\n", + "\n", + "plt.figure(figsize=(10, 6))\n", + "plt.barh(feature_importance['feature'], feature_importance['importance'])\n", + "plt.xlabel('Importance')\n", + "plt.title('Feature Importance')\n", + "plt.gca().invert_yaxis()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "\n", + "import matplotlib.pyplot as plt\n", + "\n", + "# Plot Predictions vs Ground Truth\n", + "plt.figure(figsize=(6, 4))\n", + "plt.scatter(y_test, y_pred, alpha=0.6)\n", + "plt.plot(\n", + " [y_test.min(), y_test.max()],\n", + " [y_test.min(), y_test.max()],\n", + " \"r--\",\n", + " linewidth=2\n", + ")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/405/Q2.ipynb b/submissions_extracted/405/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..846802ac61f02f549a1b54b193706a73060a5dd2 --- /dev/null +++ b/submissions_extracted/405/Q2.ipynb @@ -0,0 +1,376 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q2-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import os\n", + "import pandas as pd\n", + "import numpy as np\n", + "from PIL import Image\n", + "from sklearn.model_selection import train_test_split\n", + "\n", + "# Load Labels\n", + "labels_df = pd.read_csv(os.path.join(path, \"labels.csv\"))\n", + "img_dir = os.path.join(path, \"images\")\n", + "\n", + "images = []\n", + "ages = []\n", + "\n", + "# Load Images and Resize\n", + "print(\"Loading images...\")\n", + "for index, row in labels_df.iterrows():\n", + " img_name = row.iloc[0]\n", + " age = row.iloc[1]\n", + " img_path = os.path.join(img_dir, img_name)\n", + "\n", + " if os.path.exists(img_path):\n", + " img = Image.open(img_path).convert('RGB')\n", + " img_array = np.array(img) / 255.0 # Normalize pixel values to [0, 1]\n", + " images.append(img_array)\n", + " ages.append(age)\n", + "\n", + "X = np.array(images)\n", + "y = np.array(ages)\n", + "\n", + "# Transpose image dimensions to match PyTorch format (N, C, H, W)\n", + "X = np.transpose(X, (0, 3, 1, 2))\n", + "\n", + "# Split Data\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n", + "\n", + "print(f\"X_train shape: {X_train.shape}\")\n", + "print(f\"X_test shape: {X_test.shape}\")\n", + "print(f\"y_train shape: {y_train.shape}\")\n", + "print(f\"y_test shape: {y_test.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 1. Convert Numpy arrays to PyTorch Tensors\n", + "from sklearn.model_selection import train_test_split\n", + "from sklearn.preprocessing import StandardScaler\n", + "from torch.utils.data import TensorDataset\n", + "from torch.utils.data import DataLoader\n", + "import torch\n", + "# transform to tensors\n", + "X_train = torch.tensor(X_train, dtype=torch.float32)\n", + "X_test = torch.tensor(X_test, dtype=torch.float32)\n", + "y_train = torch.tensor(y_train, dtype=torch.float32)\n", + "y_test = torch.tensor(y_test, dtype=torch.float32)\n", + "\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 2. Create TensorDataset objects\n", + "train_dataset = TensorDataset(X_train, y_train)\n", + "test_dataset = TensorDataset(X_test, y_test)\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 3. Create DataLoaders\n", + "\n", + "# DataLoader for training data\n", + "train_loader = DataLoader(\n", + " train_dataset,\n", + " batch_size=32,\n", + " shuffle=True,\n", + " num_workers=2\n", + ")\n", + "# DataLoader for test/validation data\n", + "test_loader = DataLoader(\n", + " test_dataset,\n", + " batch_size=32,\n", + " shuffle=False,\n", + " num_workers=2\n", + ")\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 4. Print shape of one batch\n", + "x,_=next(iter(train_loader))\n", + "x.shape\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import matplotlib.pyplot as plt\n", + "\n", + "\n", + "images, labels = next(iter(train_loader))\n", + "\n", + "# Display the first 6 images in the batch\n", + "plt.figure(figsize=(8, 4))\n", + "\n", + "for i in range(6):\n", + " plt.subplot(2, 3, i + 1)\n", + "\n", + " # Convert from (C, H, W) to (H, W, C) for matplotlib\n", + " img = images[i].permute(1, 2, 0)\n", + "\n", + " plt.imshow(img)\n", + " plt.title(f\"Label: {labels[i].item()}\")\n", + " plt.axis('off')\n", + "\n", + "plt.tight_layout()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your model class here:\n", + "import torch.nn as nn\n", + "from torch.optim import AdamW\n", + "import torch.nn.functional as F\n", + "\n", + "class NN5Layer(nn.Module):\n", + "\n", + " def __init__(self, input_dim, hidden_dim, output_dim):\n", + " super(NN5Layer, self).__init__()\n", + "\n", + " self.layer1 = nn.Linear(input_dim, hidden_dim)\n", + "\n", + " self.layer2 = nn.Linear(hidden_dim, hidden_dim)\n", + "\n", + " self.layer3 = nn.Linear(hidden_dim, hidden_dim)\n", + "\n", + " self.layer4 = nn.Linear(hidden_dim, hidden_dim)\n", + "\n", + "\n", + " self.relu = nn.ReLU()\n", + "\n", + " def forward(self, x):\n", + " # Layer 1:\n", + " z1 = self.layer1(x)\n", + " a1 = self.relu(z1)\n", + "\n", + " # Layer 2\n", + " z2 = self.layer2(a1)\n", + " a2 = self.relu(z2)\n", + "\n", + " # Layer 3\n", + " z3 = self.layer3(a2)\n", + " a3 = self.relu(z3)\n", + "\n", + " # Layer 4\n", + " z4 = self.layer4(a3)\n", + "\n", + "\n", + " return z4" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "def train_one_epoch(model, optimizer, criterion, train_loader, device):\n", + " # Set the model to training mode\n", + " model.train()\n", + "\n", + " running_loss = 0.0\n", + "\n", + " for X_batch, y_batch in train_loader:\n", + " # Move batch to the selected device\n", + " X_batch = X_batch.view(X_batch.size(0), -1).to(device)\n", + " y_batch = y_batch.to(device)\n", + "\n", + " # Forward pass\n", + " # make predictions\n", + " outputs = model(X_batch)\n", + " # TODO: compute loss\n", + " loss = criterion(outputs, y_batch)\n", + "\n", + " # Backward pass & optimization\n", + " optimizer.zero_grad() # Clear previous gradients\n", + " loss.backward() # Compute gradients\n", + " optimizer.step() # Update model parameters\n", + "\n", + " running_loss += loss.item()\n", + "\n", + " # Average loss over all batches\n", + " avg_loss = running_loss / len(train_loader)\n", + "\n", + " return avg_loss" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your validation loop here:\n", + "def validate(model, criterion, test_loader, device):\n", + " # Set the model to evaluation mode\n", + " model.eval()\n", + "\n", + " running_loss = 0.0\n", + " correct = 0\n", + " total = 0\n", + "\n", + " with torch.no_grad():\n", + " for X_batch, y_batch in test_loader:\n", + " # Move data to device\n", + " X_batch = X_batch.view(X_batch.size(0), -1).to(device)\n", + " y_batch = y_batch.to(device)\n", + "\n", + " # Forward pass\n", + " outputs = model(X_batch)\n", + " loss = criterion(outputs, y_batch)\n", + " running_loss += loss.item()\n", + "\n", + " running_loss += loss.item()\n", + "\n", + " # Average loss over all batches\n", + " avg_loss = running_loss / len(train_loader)\n", + "\n", + " return avg_loss\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Define device, model, loss, optimizer:\n", + "# Device setup\n", + "device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n", + "\n", + "# Model parameters\n", + "input_dim =x.flatten(start_dim=1).shape[1] # images flattened (RGB)\n", + "\n", + "#choose number of hidden neurons\n", + "hidden_dim = 64 # Design choice\n", + "\n", + "#what are the number of classes ?\n", + "output_dim = 1 #one classes regression\n", + "\n", + "# TODO: Instantiate model (what are the model class inputs?)\n", + "model = NN5Layer(input_dim, hidden_dim, output_dim).to(device)\n", + "\n", + "# TODO: Print the model architecture\n", + "print(\"Model Architecture:\\n\")\n", + "print(model)\n", + "\n", + "# Calculate the total number of trainable parameters\n", + "total_params = sum(p.numel() for p in model.parameters() if p.requires_grad)\n", + "print(f\"\\nTotal trainable parameters: {total_params}\")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Start training for 20 epochs:\n", + "num_epochs = 20\n", + "learning_rate = 0.001\n", + "\n", + "\n", + "criterion = nn.MSELoss()\n", + "optimizer = AdamW(model.parameters(), learning_rate)\n", + "\n", + "# Run Training\n", + "train_losses = []\n", + "val_losses = []\n", + "val_accuracies = []\n", + "\n", + "print('Starting Training...')\n", + "for epoch in range(num_epochs):\n", + " # Train one epoch\n", + " train_loss = train_one_epoch(model, optimizer, criterion, train_loader, device)\n", + "\n", + " # Validate\n", + " val_loss, val_accuracy = validate(model, criterion, test_loader, device)\n", + "\n", + " train_losses.append(train_loss)\n", + " val_losses.append(val_loss)\n", + " val_accuracies.append(val_accuracy)\n", + "\n", + " print(f'Epoch [{epoch+1}/{num_epochs}], Train Loss: {train_loss:.4f}, Val Loss: {val_loss:.4f}, Val Accuracy: {val_accuracy:.4f}')\n", + "\n", + "print('Training Complete!')" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2 (Bonus): Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/405/Q3.ipynb b/submissions_extracted/405/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..6315c36b7408eabf76267d927a549af13a7fab7e --- /dev/null +++ b/submissions_extracted/405/Q3.ipynb @@ -0,0 +1,324 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "\n", + "\n", + "# Download latest version\n", + "\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q3-exam-data\")\n", + "\n", + "\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "\n", + "# Task 1: Write your code here:\n", + "import pandas as pd\n", + "import os\n", + "new_path = os.path.join(path, 'Q3_data.csv')\n", + "\n", + "df = pd.read_csv(new_path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "df.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "\n", + "df.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "import numpy as np\n", + "\n", + "def check_missing_values(df):\n", + " missing_values = df.isnull().sum()\n", + " print(\"Missing Values per Column:\")\n", + " print(missing_values[missing_values > 0])\n", + " if missing_values.any():\n", + " print(\"\\nHandle Missing Values as needed.\")\n", + " else:\n", + " print(\"\\nNo Missing Values Found.\")\n", + "print(\"before\")\n", + "check_missing_values(df)\n", + "\n", + "for col in df.select_dtypes(include=[\"object\"]).columns:\n", + " df[col] = df[col].fillna('unknown')\n", + "\n", + "print(\"after\")\n", + "num_col=df.select_dtypes(include=[\"number\"]).columns\n", + "df[num_col]=df[num_col].fillna(np.mean(df[num_col]))\n", + "check_missing_values(df)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "def check_duplicates(df):\n", + " duplicates = df.duplicated().sum()\n", + " print(f\"Number of Duplicate Samples: {duplicates}\")\n", + " if duplicates > 0:\n", + " print(\"Dropping Duplicates...\")\n", + " df.drop_duplicates(inplace=True)\n", + " print(\"Duplicates Dropped.\")\n", + " else:\n", + " print(\"No Duplicate Samples Found.\")\n", + "\n", + "check_duplicates(df)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "from sklearn.preprocessing import LabelEncoder\n", + "le=LabelEncoder()\n", + "\n", + "for col in df.select_dtypes(include=[\"object\"]).columns:\n", + " df[col] = le.fit_transform(df[col].astype(str))\n", + "\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "from sklearn.preprocessing import StandardScaler\n", + "Scaler=StandardScaler()\n", + "features = df.columns.drop(\"Target\")\n", + "\n", + "df[features]=Scaler.fit_transform(df[features])\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "#so the data is unbalanced\n", + "df[\"Target\"].hist()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "feature=df.columns.drop(\"Target\")\n", + "X=df[feature]\n", + "y=df[\"Target\"]\n", + "from sklearn.model_selection import train_test_split\n", + "\n", + "X_train, X_test, y_train, y_test = train_test_split(\n", + " X, y,\n", + " test_size=0.2, # 20% for test, remaining 80% for train\n", + " random_state=42, # reproducible output\n", + " shuffle=True, # representative splits\n", + " stratify=y\n", + ")\n", + "\n", + "print(\"X_train shape:\", X_train.shape)\n", + "print(\"X_test shape:\", X_test.shape)\n", + "print(\"y_train shape:\", y_train.shape)\n", + "print(\"y_test shape:\", y_test.shape)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "!pip install catboost" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "from catboost import CatBoostClassifier\n", + "from sklearn.model_selection import KFold\n", + "from sklearn.metrics import f1_score,accuracy_score\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "l=[]\n", + "l.append(1)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:\n", + "\n", + "kf = KFold(n_splits=5, shuffle=True, random_state=42)\n", + "model=CatBoostClassifier()\n", + "f1Scores = []\n", + "accScores = []\n", + "# Iterate through folds\n", + "for fold, (train_idx, test_idx) in enumerate(kf.split(X), start=1):\n", + " # indexing for each fold\n", + " X_train, X_test = X.iloc[train_idx], X.iloc[test_idx]\n", + " y_train, y_test = y.iloc[train_idx], y.iloc[test_idx]\n", + "\n", + " # Train model\n", + " model.fit(X_train, y_train)\n", + "\n", + " # Predict\n", + " y_pred = model.predict(X_test)\n", + "\n", + " # Evaluation metrics\n", + " accuracy = accuracy_score(y_test, y_pred)\n", + " f1 = f1_score(y_test, y_pred, average='macro')\n", + " f1Scores.append(f1)\n", + " accScores.append(accuracy)\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "print(f\" Accuracy: {np.mean(accScores):.4f}\")\n", + "print(f\" F1-Score: {np.mean(f1Scores):.4f}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import matplotlib.pyplot as plt\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "feature=df.columns.drop(\"Target\")\n", + "feature_importance = pd.DataFrame({\n", + " 'feature': feature,\n", + " 'importance': model.feature_importances_\n", + "}).sort_values('importance', ascending=False)\n", + "\n", + "plt.figure(figsize=(10, 6))\n", + "plt.barh(feature_importance['feature'][:10], feature_importance['importance'][:10])\n", + "plt.xlabel('Importance')\n", + "plt.title('Feature Importance')\n", + "plt.gca().invert_yaxis()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/406/Q1.ipynb b/submissions_extracted/406/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..dfb8126dd434f611646cbcf436f6cd681c6b4c47 --- /dev/null +++ b/submissions_extracted/406/Q1.ipynb @@ -0,0 +1,315 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "import pandas as pd\n", + "import numpy as np\n", + "import matplotlib.pyplot as plt\n", + "import seaborn as sns\n", + "import kagglehub\n", + "import os\n", + "from tqdm import tqdm\n", + "\n", + "%matplotlib inline\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q1-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "\n", + "csv_path = os.path.join(path, \"Q1_data.csv\")\n", + "\n", + "df = pd.read_csv(csv_path)\n", + "#df = df.drop(columns=\"Unnamed: 0\", axis=1)\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "df.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "df.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "df[\"Delivery_Time\"].hist()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "df=df.drop(\"Order_ID\", axis=1)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "\n", + "# Task 2: Write your code here:\n", + "def check_missing_values(df):\n", + " missing_values = df.isnull().sum()\n", + " print(\"Missing Values per Column:\")\n", + " print(missing_values[missing_values > 0])\n", + " if missing_values.any():\n", + " print(\"\\nHandle Missing Values as needed.\")\n", + " else:\n", + " print(\"\\nNo Missing Values Found.\")\n", + "\n", + "check_missing_values(df)\n", + "\n", + "\n", + "df[\"Weather\"]=df[\"Weather\"].fillna(df[\"Weather\"].mode()[0])\n", + "df[\"Traffic_Level\"]=df[\"Traffic_Level\"].fillna(df[\"Traffic_Level\"].mode()[0])\n", + "df[\"Time_of_Day\"]=df[\"Time_of_Day\"].fillna(df[\"Time_of_Day\"].mode()[0])\n", + "df[\"Courier_Experience_yrs\"]=df[\"Courier_Experience_yrs\"].fillna(df[\"Courier_Experience_yrs\"].mean())\n", + "df[\"Delivery_Time\"]=df[\"Delivery_Time\"].fillna(df[\"Delivery_Time\"].mean())\n", + "df.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "def check_duplicates(df):\n", + " duplicates = df.duplicated().sum()\n", + " print(f\"Number of Duplicate Samples: {duplicates}\")\n", + " if duplicates > 0:\n", + " print(\"Dropping Duplicates...\")\n", + " df.drop_duplicates(inplace=True)\n", + " print(\"Duplicates Dropped.\")\n", + " else:\n", + " print(\"No Duplicate Samples Found.\")\n", + "\n", + "check_duplicates(df)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "from sklearn.preprocessing import LabelEncoder\n", + "# 3. Do we have categorical columns?\n", + "categorical_cols = df.select_dtypes(include=[\"object\"]).columns\n", + "\n", + "print(\"Categorical Columns:\", list(categorical_cols))\n", + "label_encoders = {}\n", + "for col in categorical_cols:\n", + " print(f\"Encoding column: {col}\")\n", + " le = LabelEncoder()\n", + " df[col] = le.fit_transform(df[col])\n", + "df" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "from sklearn.preprocessing import StandardScaler\n", + "\n", + "features = df.columns.drop(\"Delivery_Time\") # DON'T SCALE THE TARGET\n", + "\n", + "scaler = StandardScaler()\n", + "df[features] = scaler.fit_transform(df[features])\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 6: Write your code here:\n", + "def check_target_distribution(df, target_column):\n", + " df[target_column].hist(bins=30, edgecolor='black')\n", + "\n", + " plt.title(f\"Target Distribution ({target_column})\")\n", + " plt.xlabel(target_column)\n", + " plt.ylabel(\"Frequency\")\n", + " plt.grid(False)\n", + "\n", + " plt.show()\n", + "\n", + "check_target_distribution(df, \"Delivery_Time\")\n", + "#Delivery_Time is imbalanced" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "X = df.drop(\"Delivery_Time\", axis=1)\n", + "y = df['Delivery_Time']" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:\n", + "from sklearn.model_selection import KFold\n", + "from sklearn.metrics import mean_absolute_error\n", + "from sklearn.ensemble import RandomForestRegressor\n", + "models = {\n", + " \"Random Forest Regressor\": RandomForestRegressor(n_estimators=200),\n", + "\n", + "}\n", + "all_results = {}\n", + "for name in models:\n", + " all_results[name] = {'mae': []}\n", + "\n", + "kf = KFold(n_splits=5, shuffle=True, random_state=42)\n", + "n_splits = 5\n", + "for fold_idx, (train_index, test_index) in enumerate(kf.split(X)):\n", + " print(f\"\\nFold {fold_idx + 1}/{n_splits}\")\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", + " for model_name, model in models.items():\n", + " print(f\"Training {model_name}...\")\n", + "\n", + " # Train\n", + " model.fit(X_train, y_train)\n", + "\n", + " # Predict\n", + " y_pred = model.predict(X_test)\n", + "\n", + " # Calculate metrics\n", + " mae = mean_absolute_error(y_test, y_pred)\n", + " print(mae)\n", + "\n", + " # Store results\n", + " all_results[model_name][\"mae\"].append(mae)\n", + "for model_name in all_results:\n", + " print(f\"\\n{model_name}:\")\n", + " print(f\" MAE: {np.mean(all_results[model_name]['mae']):.4f}\")\n", + "\n", + "\n", + "\n", + "\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "# Gather importances from the models (from the last fold)\n", + "\n", + "\n", + "catboost_model = models[\"Random Forest Regressor\"]\n", + "catboost_importance = list(zip(X.columns, catboost_model.feature_importances_))\n", + "sorted_catboost_importance = sorted(catboost_importance, key=lambda x: x[1], reverse=True)\n", + "\n", + "# Extract features and their importances\n", + "features, importances = zip(*sorted_catboost_importance)\n", + "\n", + "# Plot feature importances\n", + "plt.figure(figsize=(10, 6))\n", + "plt.barh(features, importances, color='orange')\n", + "plt.xlabel('Importance Score')\n", + "plt.ylabel('Features')\n", + "plt.title('Random Forest Regressor Feature Importance')\n", + "plt.gca().invert_yaxis() # Invert y-axis to show the most important features at the top\n", + "plt.show()\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "plt.hist(y_pred,bins=100)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:\n" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/406/Q2.ipynb b/submissions_extracted/406/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..ab28208bb6b7fddd49caa5355f24b9732ecd57a8 --- /dev/null +++ b/submissions_extracted/406/Q2.ipynb @@ -0,0 +1,383 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q2-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import os\n", + "import pandas as pd\n", + "import numpy as np\n", + "from PIL import Image\n", + "from sklearn.model_selection import train_test_split\n", + "\n", + "# Load Labels\n", + "labels_df = pd.read_csv(os.path.join(path, \"labels.csv\"))\n", + "img_dir = os.path.join(path, \"images\")\n", + "\n", + "images = []\n", + "ages = []\n", + "\n", + "# Load Images and Resize\n", + "print(\"Loading images...\")\n", + "for index, row in labels_df.iterrows():\n", + " img_name = row.iloc[0]\n", + " age = row.iloc[1]\n", + " img_path = os.path.join(img_dir, img_name)\n", + "\n", + " if os.path.exists(img_path):\n", + " img = Image.open(img_path).convert('RGB')\n", + " img_array = np.array(img) / 255.0 # Normalize pixel values to [0, 1]\n", + " images.append(img_array)\n", + " ages.append(age)\n", + "\n", + "X = np.array(images)\n", + "y = np.array(ages)\n", + "\n", + "# Transpose image dimensions to match PyTorch format (N, C, H, W)\n", + "X = np.transpose(X, (0, 3, 1, 2))\n", + "\n", + "# Split Data\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n", + "\n", + "print(f\"X_train shape: {X_train.shape}\")\n", + "print(f\"X_test shape: {X_test.shape}\")\n", + "print(f\"y_train shape: {y_train.shape}\")\n", + "print(f\"y_test shape: {y_test.shape}\")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 1. Convert Numpy arrays to PyTorch Tensors\n", + "# transform to tensors\n", + "import kagglehub\n", + "import pandas as pd\n", + "import torch\n", + "import torch.nn as nn\n", + "from torch.optim import AdamW\n", + "import matplotlib.pyplot as plt\n", + "import torch.nn.functional as F\n", + "from torch.utils.data import DataLoader, TensorDataset\n", + "from sklearn.model_selection import train_test_split\n", + "from sklearn.preprocessing import StandardScaler, LabelEncoder\n", + "\n", + "X_train = torch.tensor(X_train, dtype=torch.float32)\n", + "X_test = torch.tensor(X_test, dtype=torch.float32)\n", + "y_train = torch.tensor(y_train, dtype=torch.float32)\n", + "y_test = torch.tensor(y_test, dtype=torch.float32)\n", + "\n", + "\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 2. Create TensorDataset objects\n", + "train_dataset = TensorDataset(X_train, y_train)\n", + "test_dataset = TensorDataset(X_test, y_test)\n", + "\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 3. Create DataLoaders\n", + "\n", + "# Create Dataloaders to train and test data in batches\n", + "train_loader = DataLoader(train_dataset, batch_size=32, shuffle=True)\n", + "test_loader = DataLoader(test_dataset, batch_size=32, shuffle=False)\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 4. Print shape of one batch\n", + "X_batch, y_batch = next(iter(train_loader))\n", + "print(f\"Training batch input shape: {X_batch.shape}\")\n", + "print(f\"Training batch labels shape: {y_batch.shape}\")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 5. Display sample images\n", + "# Get one batch of images and labels\n", + "images, labels = next(iter(train_loader))\n", + "print(images.shape)\n", + "# Display the first 6 images in the batch\n", + "plt.figure(figsize=(8, 4))\n", + "\n", + "for i in range(6):\n", + " plt.subplot(2, 3, i + 1)\n", + " print(images[i].squeeze().shape)\n", + " plt.imshow(images[i].permute(1, 2, 0), cmap='gray')\n", + " plt.title(f\"Label: {labels[i].item()}\")\n", + " plt.axis('off')\n", + "\n", + "plt.tight_layout()\n", + "plt.show()\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your model class here:\n", + "class NN4Layer(nn.Module):\n", + "\n", + " def __init__(self, input_dim, hidden_dim):\n", + " super(NN4Layer, self).__init__()\n", + "\n", + " # First linear layer: input features -> hidden layer\n", + " self.layer1 = nn.Linear(input_dim, hidden_dim)\n", + "\n", + " # Second linear layer: hidden layer -> hidden layer\n", + " self.layer2 = nn.Linear(hidden_dim, hidden_dim)\n", + "\n", + " # Third linear layer: hidden layer -> hidden layer\n", + " self.layer3 = nn.Linear(hidden_dim, hidden_dim)\n", + "\n", + " # Output layer: hidden layer -> number of classes (logits)\n", + " self.layer4 = nn.Linear(hidden_dim, 1)\n", + "\n", + " # ReLU activation for non-linearity\n", + " self.relu = nn.ReLU()\n", + "\n", + " # Defines how input data flows through the network\n", + " def forward(self, x):\n", + " # First hidden layer\n", + " a1 = self.relu(self.layer1(x))\n", + "\n", + " # Second hidden layer\n", + " a2 = self.relu(self.layer2(a1))\n", + "\n", + " # Third hidden layer\n", + " a3 = self.relu(self.layer3(a2))\n", + "\n", + "\n", + " output = self.layer4(a3)\n", + " return output\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your training loop here:\n", + "def train_one_epoch(model, optimizer, criterion, train_loader, device):\n", + " # Set the model to training mode\n", + " model.train()\n", + "\n", + " running_loss = 0.0\n", + "\n", + " for X_batch, y_batch in train_loader:\n", + " # Move batch to the selected device\n", + " X_batch = X_batch.view(X_batch.size(0), -1).to(device)\n", + " # shape: (batch_size, num_features)\n", + " y_batch = y_batch.to(device) # shape: (batch_size,)\n", + "\n", + " # Forward pass (outputs are logits)\n", + " outputs = model(X_batch) # shape: (batch_size, num_classes)\n", + " loss = criterion(outputs, y_batch)\n", + "\n", + " # Backward pass & optimization\n", + " optimizer.zero_grad() # Clear previous gradients\n", + " loss.backward() # Compute gradients\n", + " optimizer.step() # Update model parameters\n", + "\n", + " running_loss += loss.item()\n", + "\n", + " # Average loss over all batches\n", + " avg_loss = running_loss / len(train_loader)\n", + "\n", + " return avg_loss\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your validation loop here:\n", + "def validate(model, criterion, test_loader, device):\n", + " # Set the model to evaluation mode\n", + " model.eval()\n", + "\n", + " running_loss = 0.0\n", + " correct = 0\n", + " total = 0\n", + "\n", + " with torch.no_grad():\n", + " for X_batch, y_batch in test_loader:\n", + " # Move data to device\n", + " X_batch = X_batch.view(X_batch.size(0), -1).to(device) # shape: (batch_size, num_features)\n", + " y_batch = y_batch.to(device) # shape: (batch_size,)\n", + "\n", + " # Forward pass\n", + " outputs = model(X_batch) # shape: (batch_size, num_classes)\n", + " loss = criterion(outputs, y_batch)\n", + " running_loss += loss.item()\n", + "\n", + " # Apply Softmax to get probabilities\n", + " probabilities = F.softmax(outputs, dim=1)\n", + "\n", + " # Pick the classes with highest probabilities\n", + " predicted = torch.argmax(probabilities, dim=1)\n", + "\n", + " # Accuracy calculation\n", + " correct += (predicted == y_batch).sum().item()\n", + " total += y_batch.size(0)\n", + "\n", + " avg_loss = running_loss / len(test_loader)\n", + " accuracy = correct / total\n", + "\n", + " return avg_loss, accuracy" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Define device, model, loss, optimizer:\n", + "# Device setup\n", + "device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n", + "\n", + "# Model parameters\n", + "input_dim = 3*36*36 # Number of tabular features\n", + "print(input_dim)\n", + "\n", + "hidden_dim = 1024 # Design choice\n", + "\n", + "# Instantiate model\n", + "model = NN4Layer(input_dim, hidden_dim).to(device)\n", + "\n", + "# Print the model architecture\n", + "print(\"Model Architecture:\\n\")\n", + "print(model)\n", + "\n", + "# Calculate the total number of trainable parameters\n", + "total_params = sum(p.numel() for p in model.parameters() if p.requires_grad)\n", + "print(f\"\\nTotal trainable parameters: {total_params}\")\n", + "\n", + "learning_rate = 0.0001\n", + "\n", + "# Define criterion (loss function) - using CrossEntropyLoss as model now outputs logits\n", + "criterion = nn.MSELoss()\n", + "# Define optimizer\n", + "optimizer = AdamW(model.parameters(), learning_rate)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Start training for 20 epochs:\n", + "num_epochs = 20\n", + "# Run Training\n", + "train_losses = []\n", + "val_losses = []\n", + "val_accuracies = []\n", + "\n", + "print('Starting Training...')\n", + "for epoch in range(num_epochs):\n", + " # Train one epoch\n", + " train_loss = train_one_epoch(model, optimizer, criterion, train_loader, device)\n", + "\n", + " # Validate\n", + " val_loss, val_accuracy = validate(model, criterion, test_loader, device)\n", + "\n", + " train_losses.append(train_loss)\n", + " val_losses.append(val_loss)\n", + " val_accuracies.append(val_accuracy)\n", + "\n", + " print(f'Epoch [{epoch+1}/{num_epochs}], Train Loss: {train_loss:.4f}, Val Loss: {val_loss:.4f}, Val Accuracy: {val_accuracy:.4f}')\n", + "\n", + "print('Training Complete!')" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "# Plotting results\n", + "plt.figure(figsize=(7, 5))\n", + "\n", + "plt.plot(train_losses, label='Train Loss')\n", + "plt.plot(val_losses, label='Validation Loss')\n", + "plt.title('Loss over Epochs')\n", + "plt.xlabel('Epoch')\n", + "plt.ylabel('Loss')\n", + "plt.legend()\n", + "\n", + "plt.tight_layout()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2 (Bonus): Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/406/Q3.ipynb b/submissions_extracted/406/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..6cd50a35c3b5be3f69c066659925761f0e26171b --- /dev/null +++ b/submissions_extracted/406/Q3.ipynb @@ -0,0 +1,370 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "\n", + "import pandas as pd\n", + "import numpy as np\n", + "import matplotlib.pyplot as plt\n", + "import seaborn as sns\n", + "import kagglehub\n", + "import os\n", + "from tqdm import tqdm\n", + "\n", + "%matplotlib inline\n", + "\n", + "# Download latest version\n", + "from IPython.display import clear_output\n", + "\n", + "%pip install kagglehub catboost xgboost tqdm imbalanced-learn -q\n", + "\n", + "clear_output()\n", + "\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q3-exam-data\")\n", + "\n", + "\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "csv_path = os.path.join(path, \"Q3_data.csv\")\n", + "\n", + "df = pd.read_csv(csv_path)\n", + "#df = df.drop(columns=\"Unnamed: 0\", axis=1)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "df.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "df.describe()\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "\n", + "\n", + "def check_missing_values(df):\n", + " missing_values = df.isnull().sum()\n", + " print(\"Missing Values per Column:\")\n", + " print(missing_values[missing_values > 0])\n", + " if missing_values.any():\n", + " print(\"\\nHandle Missing Values as needed.\")\n", + " else:\n", + " print(\"\\nNo Missing Values Found.\")\n", + "\n", + "check_missing_values(df)\n", + "categorical_cols = df.select_dtypes(include=[\"object\"]).columns\n", + "for col in categorical_cols:\n", + " print(f\"Encoding column: {col}\")\n", + " df[col] =df[col].fillna(df[col].mode()[0])\n", + "number_cols = df.select_dtypes(include=[\"number\"]).drop(\"Target\",axis=1).columns\n", + "\n", + "for col in number_cols:\n", + " print(f\"Encoding column: {col}\")\n", + " df[col] =df[col].fillna(df[col].mean())\n", + "check_missing_values(df)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "def check_duplicates(df):\n", + " duplicates = df.duplicated().sum()\n", + " print(f\"Number of Duplicate Samples: {duplicates}\")\n", + " if duplicates > 0:\n", + " print(\"Dropping Duplicates...\")\n", + " df.drop_duplicates(inplace=True)\n", + " print(\"Duplicates Dropped.\")\n", + " else:\n", + " print(\"No Duplicate Samples Found.\")\n", + "\n", + "check_duplicates(df)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "from sklearn.preprocessing import LabelEncoder\n", + "# 3. Do we have categorical columns?\n", + "categorical_cols = df.select_dtypes(include=[\"object\"]).columns\n", + "\n", + "print(\"Categorical Columns:\", list(categorical_cols))\n", + "label_encoders = {}\n", + "for col in categorical_cols:\n", + " print(f\"Encoding column: {col}\")\n", + " le = LabelEncoder()\n", + " df[col] = le.fit_transform(df[col])\n", + "df" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "from sklearn.preprocessing import StandardScaler\n", + "\n", + "features = df.columns.drop(\"Target\") # DON'T SCALE THE TARGET\n", + "\n", + "scaler = StandardScaler()\n", + "df[features] = scaler.fit_transform(df[features])\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "def check_target_distribution(df, target_column):\n", + " df[target_column].hist(bins=30, edgecolor='black')\n", + "\n", + " plt.title(f\"Target Distribution ({target_column})\")\n", + " plt.xlabel(target_column)\n", + " plt.ylabel(\"Frequency\")\n", + " plt.grid(False)\n", + "\n", + " plt.show()\n", + "\n", + "check_target_distribution(df, \"Target\")\n", + "#Target is imbalanced" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "X = df.drop(\"Target\", axis=1)\n", + "y = df['Target']" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:\n", + "from sklearn.model_selection import StratifiedKFold, train_test_split\n", + "from sklearn.metrics import accuracy_score,f1_score\n", + "\n", + "\n", + "from catboost import CatBoostClassifier\n", + "\n", + "# Single model:\n", + "\n", + "models = {\n", + "\n", + " \"CatBoost\": CatBoostClassifier(verbose=0, n_estimators=200, max_depth=4)\n", + "}\n", + "\n", + "n_splits = 5\n", + "skf = StratifiedKFold(n_splits=n_splits, shuffle=True, random_state=42)\n", + "results = {}\n", + "\n", + "for model_name in models:\n", + " results[model_name] = {'accuracy': [], 'f1': [] }\n", + "\n", + "for fold_idx, (train_index, test_index) in enumerate(skf.split(X, y)):\n", + " print(f\"\\nFold {fold_idx + 1}/{n_splits}\")\n", + "\n", + " # Get the train & test split for this fold\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", + " # Train & Validate Models\n", + " for model_name, model in models.items():\n", + "\n", + " print(f\"Training {model_name}...\")\n", + "\n", + " # Fit the model on train data\n", + " model.fit(X_train, y_train)\n", + "\n", + " # Use the model to predict the test data\n", + " y_pred_test = model.predict(X_test)\n", + "\n", + "\n", + "\n", + " # Calculate evaluation metrics\n", + " accuracy = accuracy_score(y_test, y_pred_test)\n", + " f1 = f1_score(y_test, y_pred_test, average='macro') # for multiclass f1 score, you should set the average hyperparameter (\"macro\", \"micro\", \"weighted\")\n", + "\n", + "\n", + "\n", + "\n", + " results[model_name]['accuracy'].append(accuracy)\n", + " results[model_name]['f1'].append(f1)\n", + "for model_name in results:\n", + " print(f\"\\n{model_name}:\")\n", + " # Print the average of each evaluation metric across folds\n", + " print(f\" Accuracy: {np.mean(results[model_name]['accuracy']):.4f}\")\n", + " print(f\" F1-Score: {np.mean(results[model_name]['f1']):.4f}\")\n", + "" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "catboost_model = models[\"CatBoost\"]\n", + "catboost_importance = list(zip(X.columns, catboost_model.feature_importances_))\n", + "sorted_catboost_importance = sorted(catboost_importance, key=lambda x: x[1], reverse=True)\n", + "\n", + "# Extract features and their importances\n", + "features, importances = zip(*sorted_catboost_importance)\n", + "\n", + "# Plot feature importances\n", + "plt.figure(figsize=(10, 6))\n", + "plt.barh(features, importances, color='orange')\n", + "plt.xlabel('Importance Score')\n", + "plt.ylabel('Features')\n", + "plt.title('CatBoost Feature Importance')\n", + "plt.gca().invert_yaxis() # Invert y-axis to show the most important features at the top\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "print(features[0])" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# # Task Bonus: Write your code here:\n", + "X_new = df[\"P_2\"]\n", + "y_new = df['Target']\n", + " # Single model:\n", + "\n", + "models = {\n", + "\n", + " \"CatBoost\": CatBoostClassifier(verbose=0, n_estimators=200, max_depth=4)\n", + " }\n", + "\n", + "n_splits = 5\n", + "skf = StratifiedKFold(n_splits=n_splits, shuffle=True, random_state=42)\n", + "results_new = {}\n", + "\n", + "for model_name in models:\n", + " results_new[model_name] = {'accuracy_new': []}\n", + "\n", + "for fold_idx, (train_index, test_index) in enumerate(skf.split(X_new,y_new )):\n", + " print(f\"\\nFold {fold_idx + 1}/{n_splits}\")\n", + "\n", + " # Get the train & test split for this fold\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", + " # Train & Validate Models\n", + " for model_name, model in models.items():\n", + "\n", + " print(f\"Training {model_name}...\")\n", + "\n", + " # Fit the model on train data\n", + " model.fit(X_train, y_train)\n", + "\n", + " # Use the model to predict the test data\n", + " y_pred_test_new = model.predict(X_test)\n", + "\n", + "\n", + "\n", + " # Calculate evaluation metrics\n", + " accuracy = accuracy_score(y_test, y_pred_test_new)\n", + " # for multiclass f1 score, you should set the average hyperparameter (\"macro\", \"micro\", \"weighted\")\n", + "\n", + "\n", + "\n", + "\n", + " results_new[model_name]['accuracy_new'].append(accuracy)\n", + "\n", + "for model_name in results_new:\n", + " print(f\"\\n{model_name}:\")\n", + " # Print the average of each evaluation metric across folds\n", + " print(f\" accuracy_new: {np.mean(results_new[model_name]['accuracy_new']):.4f}\")\n", + "\n", + "\n", + "" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/407/Q1.ipynb b/submissions_extracted/407/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..56475359849c00c3b7b756f6a45369c90d2f947e --- /dev/null +++ b/submissions_extracted/407/Q1.ipynb @@ -0,0 +1,308 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Import Libraries\n", + "\n", + "import pandas as pd\n", + "import numpy as np\n", + "import matplotlib.pyplot as plt\n", + "import seaborn as sns\n", + "import kagglehub\n", + "from sklearn.preprocessing import StandardScaler\n", + "from sklearn.ensemble import RandomForestRegressor\n", + "from sklearn.model_selection import KFold\n", + "from sklearn.metrics import mean_absolute_error\n", + "import warnings\n", + "import os\n", + "from catboost import CatBoostRegressor\n", + "\n", + "\n", + "warnings.filterwarnings('ignore')\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q1-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Read the dataset\n", + "\n", + "df = pd.read_csv('/kaggle/input/q1-exam-data/Q1_data.csv')" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "\n", + "print(df.head())" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "\n", + "print(df.info())" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "\n", + "print(df.describe())" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "\n", + "plt.figure(figsize=(10, 6))\n", + "plt.hist(df['Delivery_Time'], bins=30, edgecolor='black')\n", + "plt.xlabel('Delivery Time')\n", + "plt.ylabel('Frequency')\n", + "plt.title('Distribution of Delivery Time')\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "\n", + "df = df.drop('Order_ID', axis=1)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "\n", + "# Drop rows\n", + "df = df.dropna(subset=['Delivery_Time'])\n", + "\n", + "# Fill missing values\n", + "df = df.dropna(subset=['Delivery_Time'])\n", + "df['Courier_Experience_yrs'].fillna(df['Courier_Experience_yrs'].median(), inplace=True)\n", + "df['Weather'].fillna(df['Weather'].mode()[0], inplace=True)\n", + "df['Traffic_Level'].fillna(df['Traffic_Level'].mode()[0], inplace=True)\n", + "df['Time_of_Day'].fillna(df['Time_of_Day'].mode()[0], inplace=True)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "\n", + "df = df.drop_duplicates()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "\n", + "df = pd.get_dummies(df, columns=['Weather', 'Traffic_Level', 'Time_of_Day', 'Vehicle_Type'], drop_first=True)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "\n", + "X = df.drop('Delivery_Time', axis=1)\n", + "y = df['Delivery_Time']\n", + "scaler = StandardScaler()\n", + "X_scaled = scaler.fit_transform(X)\n", + "X_scaled = pd.DataFrame(X_scaled, columns=X.columns)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 6: Write your code here:\n", + "\n", + "print(\" :) \")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "\n", + "print(f\"X shape: {X_scaled.shape}, y shape: {y.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:\n", + "\n", + "kfold = KFold(n_splits=5, shuffle=True, random_state=42)\n", + "mae_scores = []\n", + "\n", + "for fold, (train_idx, val_idx) in enumerate(kfold.split(X_scaled), 1):\n", + " X_train, X_val = X_scaled.iloc[train_idx], X_scaled.iloc[val_idx]\n", + " y_train, y_val = y.iloc[train_idx], y.iloc[val_idx]\n", + "\n", + " rf_model = RandomForestRegressor(n_estimators=100, random_state=42)\n", + " rf_model.fit(X_train, y_train)\n", + "\n", + " y_pred = rf_model.predict(X_val)\n", + " mae = mean_absolute_error(y_val, y_pred)\n", + " mae_scores.append(mae)\n", + " print(f\"Fold {fold} - MAE: {mae:.4f}\")\n", + "\n", + "avg_mae = np.mean(mae_scores)\n", + "print(f\"Average MAE: {avg_mae:.4f}\")\n", + "\n", + "final_model = RandomForestRegressor(n_estimators=100, random_state=42)\n", + "final_model.fit(X_scaled, y)\n", + "final_predictions = final_model.predict(X_scaled)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "\n", + "feature_importance = pd.DataFrame({\n", + " 'feature': X_scaled.columns,\n", + " 'importance': final_model.feature_importances_\n", + "}).sort_values('importance', ascending=False)\n", + "\n", + "plt.figure(figsize=(12, 8))\n", + "plt.barh(feature_importance['feature'], feature_importance['importance'])\n", + "plt.xlabel('Importance')\n", + "plt.ylabel('Feature')\n", + "plt.title('Feature Importance')\n", + "plt.gca().invert_yaxis()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "\n", + "plt.figure(figsize=(10, 6))\n", + "plt.hist(final_predictions, bins=30, edgecolor='black', color='orange')\n", + "plt.xlabel('Predicted Delivery Time')\n", + "plt.ylabel('Frequency')\n", + "plt.title('Distribution of Predicted Delivery Time')\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:\n", + "\n", + "\n", + "scores = []\n", + "kf = KFold(n_splits=5, shuffle=True, random_state=42)\n", + "\n", + "for i, (train_idx, val_idx) in enumerate(kf.split(X_scaled)):\n", + " X_train = X_scaled.iloc[train_idx]\n", + " X_val = X_scaled.iloc[val_idx]\n", + " y_train = y.iloc[train_idx]\n", + " y_val = y.iloc[val_idx]\n", + "\n", + " # first\n", + " model1 = RandomForestRegressor(n_estimators=100, random_state=42)\n", + " model1.fit(X_train, y_train)\n", + " pred1 = model1.predict(X_val)\n", + " # scond\n", + " model2 = CatBoostRegressor(iterations=100, random_state=42, verbose=0)\n", + " model2.fit(X_train, y_train)\n", + " pred2 = model2.predict(X_val)\n", + "\n", + " # combine predictions\n", + " final_pred = (pred1 + pred2) / 2\n", + "\n", + " # calculate error\n", + " error = mean_absolute_error(y_val, final_pred)\n", + " scores.append(error)\n", + " print(f\"Fold {i+1} MAE: {error:.4f}\")\n", + "\n", + "print(f\"\\nMean MAE: {np.mean(scores):.4f}\")" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/407/Q2.ipynb b/submissions_extracted/407/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..334d7c77c84bfe7b3b6faaabdbb3f9ececc7152c --- /dev/null +++ b/submissions_extracted/407/Q2.ipynb @@ -0,0 +1,327 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import os\n", + "import pandas as pd\n", + "import numpy as np\n", + "from PIL import Image\n", + "from sklearn.model_selection import train_test_split\n", + "import torch\n", + "import torch.nn as nn\n", + "import torch.optim as optim\n", + "from torch.utils.data import TensorDataset, DataLoader\n", + "import matplotlib.pyplot as plt\n", + "import warnings\n", + "warnings.filterwarnings('ignore')" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q2-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import os\n", + "import pandas as pd\n", + "import numpy as np\n", + "from PIL import Image\n", + "from sklearn.model_selection import train_test_split\n", + "\n", + "# Load Labels\n", + "labels_df = pd.read_csv(os.path.join(path, \"labels.csv\"))\n", + "img_dir = os.path.join(path, \"images\")\n", + "\n", + "images = []\n", + "ages = []\n", + "\n", + "# Load Images and Resize\n", + "print(\"Loading images...\")\n", + "for index, row in labels_df.iterrows():\n", + " img_name = row.iloc[0]\n", + " age = row.iloc[1]\n", + " img_path = os.path.join(img_dir, img_name)\n", + "\n", + " if os.path.exists(img_path):\n", + " img = Image.open(img_path).convert('RGB')\n", + " img_array = np.array(img) / 255.0 # Normalize pixel values to [0, 1]\n", + " images.append(img_array)\n", + " ages.append(age)\n", + "\n", + "X = np.array(images)\n", + "y = np.array(ages)\n", + "\n", + "# Transpose image dimensions to match PyTorch format (N, C, H, W)\n", + "X = np.transpose(X, (0, 3, 1, 2))\n", + "\n", + "# Split Data\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n", + "\n", + "print(f\"X_train shape: {X_train.shape}\")\n", + "print(f\"X_test shape: {X_test.shape}\")\n", + "print(f\"y_train shape: {y_train.shape}\")\n", + "print(f\"y_test shape: {y_test.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 1. Convert Numpy arrays to PyTorch Tensors\n", + "\n", + "import torch\n", + "X_train_tensor = torch.FloatTensor(X_train)\n", + "X_test_tensor = torch.FloatTensor(X_test)\n", + "y_train_tensor = torch.FloatTensor(y_train)\n", + "y_test_tensor = torch.FloatTensor(y_test)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 2. Create TensorDataset objects\n", + "\n", + "from torch.utils.data import TensorDataset, DataLoader\n", + "train_dataset = TensorDataset(X_train_tensor, y_train_tensor)\n", + "test_dataset = TensorDataset(X_test_tensor, y_test_tensor)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 3. Create DataLoaders\n", + "\n", + "train_loader = DataLoader(train_dataset, batch_size=32, shuffle=True)\n", + "test_loader = DataLoader(test_dataset, batch_size=32, shuffle=False)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 4. Print shape of one batch\n", + "\n", + "for batch_X, batch_y in train_loader:\n", + " print(f\"Batch X shape: {batch_X.shape}\")\n", + " print(f\"Batch y shape: {batch_y.shape}\")\n", + " break" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 5. Display sample images\n", + "\n", + "import matplotlib.pyplot as plt\n", + "fig, axes = plt.subplots(2, 4, figsize=(12, 6))\n", + "for i, ax in enumerate(axes.flat):\n", + " img = X_train[i].transpose(1, 2, 0)\n", + " ax.imshow(img)\n", + " ax.set_title(f\"Age: {y_train[i]}\")\n", + " ax.axis('off')\n", + "plt.tight_layout()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your model class here:\n", + "\n", + "import torch.nn as nn\n", + "class AgePredictor(nn.Module):\n", + " def __init__(self):\n", + " super(AgePredictor, self).__init__()\n", + " self.flatten = nn.Flatten()\n", + " self.fc1 = nn.Linear(3 * 128 * 128, 512)\n", + " self.fc2 = nn.Linear(512, 256)\n", + " self.fc3 = nn.Linear(256, 128)\n", + " self.fc4 = nn.Linear(128, 1)\n", + " self.relu = nn.ReLU()\n", + "\n", + " def forward(self, x):\n", + " x = self.flatten(x)\n", + " x = self.relu(self.fc1(x))\n", + " x = self.relu(self.fc2(x))\n", + " x = self.relu(self.fc3(x))\n", + " x = self.fc4(x)\n", + " return x" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your training loop here:\n", + "\n", + "def train_loop(model, loader, criterion, optimizer, device):\n", + " model.train()\n", + " running_loss = 0.0\n", + "\n", + " for inputs, targets in loader:\n", + " inputs = inputs.to(device)\n", + " targets = targets.to(device).view(-1, 1)\n", + "\n", + " optimizer.zero_grad()\n", + " outputs = model(inputs)\n", + " loss = criterion(outputs, targets)\n", + " loss.backward()\n", + " optimizer.step()\n", + "\n", + " running_loss += loss.item()\n", + "\n", + " return running_loss / len(loader)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your validation loop here:\n", + "\n", + "\n", + "def val_loop(model, loader, criterion, device):\n", + " model.eval()\n", + " running_loss = 0.0\n", + "\n", + " with torch.no_grad():\n", + " for inputs, targets in loader:\n", + " inputs = inputs.to(device)\n", + " targets = targets.to(device).view(-1, 1)\n", + "\n", + " outputs = model(inputs)\n", + " loss = criterion(outputs, targets)\n", + "\n", + " running_loss += loss.item()\n", + "\n", + " return running_loss / len(loader)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Define device, model, loss, optimizer:\n", + "\n", + "device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\n", + "model = AgePredictor().to(device)\n", + "criterion = nn.MSELoss()\n", + "optimizer = optim.Adam(model.parameters(), lr=0.001)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Start training for 20 epochs:\n", + "\n", + "train_losses = []\n", + "val_losses = []\n", + "\n", + "for epoch in range(20):\n", + " train_loss = train_loop(model, train_loader, criterion, optimizer, device)\n", + " val_loss = val_loop(model, test_loader, criterion, device)\n", + "\n", + " train_losses.append(train_loss)\n", + " val_losses.append(val_loss)\n", + "\n", + " print(f\"Epoch {epoch+1}/20 - Train Loss: {train_loss:.4f}, Val Loss: {val_loss:.4f}\")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "\n", + "plt.figure(figsize=(10, 6))\n", + "plt.plot(range(1, 21), train_losses, label='Training Loss', marker='o')\n", + "plt.plot(range(1, 21), val_losses, label='Validation Loss', marker='s')\n", + "plt.xlabel('Epoch')\n", + "plt.ylabel('Loss')\n", + "plt.title('Training and Validation Loss')\n", + "plt.legend()\n", + "plt.grid(True)\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2 (Bonus): Write your code here:\n", + "\n", + "model.eval()\n", + "with torch.no_grad():\n", + " sample_inputs = X_test_tensor[:8].to(device)\n", + " predictions = model(sample_inputs).cpu().numpy().flatten()\n", + "\n", + "fig, axes = plt.subplots(2, 4, figsize=(14, 7))\n", + "for i, ax in enumerate(axes.flat):\n", + " img = X_test[i].transpose(1, 2, 0)\n", + " ax.imshow(img)\n", + " ax.set_title(f\"Actual: {y_test[i]:.1f}\\nPredicted: {predictions[i]:.1f}\")\n", + " ax.axis('off')\n", + "plt.tight_layout()\n", + "plt.show()Claude is AI and can make mistakes. Please double-check responses." + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/407/Q3.ipynb b/submissions_extracted/407/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..ddef203c6836d2e73ffe86e19becbc5f2f86c7d3 --- /dev/null +++ b/submissions_extracted/407/Q3.ipynb @@ -0,0 +1,272 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import pandas as pd\n", + "import numpy as np\n", + "import matplotlib.pyplot as plt\n", + "import seaborn as sns\n", + "from sklearn.preprocessing import StandardScaler\n", + "from sklearn.model_selection import StratifiedKFold\n", + "from sklearn.metrics import f1_score\n", + "import warnings\n", + "warnings.filterwarnings('ignore')" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "\n", + "\n", + "# Download latest version\n", + "\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q3-exam-data\")\n", + "\n", + "\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "\n", + "df = pd.read_csv(f'{path}/Q3_data.csv')" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "\n", + "print(df.head())\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "print(df.info())" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "\n", + "print(df.describe())" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "\n", + "df = df.drop_duplicates()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "\n", + "categorical_cols = df.select_dtypes(include=['object']).columns.tolist()\n", + "if 'Target' in categorical_cols:\n", + " categorical_cols.remove('Target')\n", + "if len(categorical_cols) > 0:\n", + " df = pd.get_dummies(df, columns=categorical_cols, drop_first=True)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "\n", + "X = df.drop('Target', axis=1)\n", + "y = df['Target']\n", + "scaler = StandardScaler()\n", + "X_scaled = scaler.fit_transform(X)\n", + "X_scaled = pd.DataFrame(X_scaled, columns=X.columns)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "\n", + "print(\"Target distribution:\")\n", + "print(y.value_counts())\n", + "print(f\"\\nTarget imbalance ratio: {y.value_counts()[0] / y.value_counts()[1]:.2f}\")\n", + "if y.value_counts()[0] / y.value_counts()[1] > 1.5:\n", + " print(\"The target is IMBALANCED\")\n", + "else:\n", + " print(\"The target is BALANCED\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "\n", + "print(f\"X shape: {X_scaled.shape}, y shape: {y.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:\n", + "\n", + "skfold = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)\n", + "f1_scores = []\n", + "\n", + "for fold, (train_idx, val_idx) in enumerate(skfold.split(X_scaled, y), 1):\n", + " X_train, X_val = X_scaled.iloc[train_idx], X_scaled.iloc[val_idx]\n", + " y_train, y_val = y.iloc[train_idx], y.iloc[val_idx]\n", + "\n", + " model = CatBoostClassifier(iterations=100, random_state=42, verbose=0)\n", + " model.fit(X_train, y_train)\n", + "\n", + " y_pred = model.predict(X_val)\n", + " f1 = f1_score(y_val, y_pred)\n", + " f1_scores.append(f1)\n", + " print(f\"Fold {fold} - F1 Score: {f1:.4f}\")\n", + "\n", + "avg_f1 = np.mean(f1_scores)\n", + "print(f\"Average F1 Score: {avg_f1:.4f}\")\n", + "\n", + "# Train final model for feature importance\n", + "final_model = CatBoostClassifier(iterations=100, random_state=42, verbose=0)\n", + "final_model.fit(X_scaled, y)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "\n", + "\n", + "feature_importance = pd.DataFrame({\n", + " 'feature': X_scaled.columns,\n", + " 'importance': final_model.feature_importances_\n", + "}).sort_values('importance', ascending=False)\n", + "\n", + "plt.figure(figsize=(12, 8))\n", + "plt.barh(feature_importance['feature'][:20], feature_importance['importance'][:20])\n", + "plt.xlabel('Importance')\n", + "plt.ylabel('Feature')\n", + "plt.title('Top 20 Feature Importance')\n", + "plt.gca().invert_yaxis()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "\n", + "golden_feature = feature_importance.iloc[0]['feature']\n", + "print(f\"The Golden Feature is: {golden_feature}\")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:\n", + "\n", + "\n", + "# Create new X with only golden feature\n", + "X_golden = X_scaled[[golden_feature]]\n", + "\n", + "# Run KFold with single feature\n", + "golden_f1_scores = []\n", + "\n", + "for fold, (train_idx, val_idx) in enumerate(skfold.split(X_golden, y), 1):\n", + " X_train, X_val = X_golden.iloc[train_idx], X_golden.iloc[val_idx]\n", + " y_train, y_val = y.iloc[train_idx], y.iloc[val_idx]\n", + "\n", + " model = CatBoostClassifier(iterations=100, random_state=42, verbose=0)\n", + " model.fit(X_train, y_train)\n", + "\n", + " y_pred = model.predict(X_val)\n", + " f1 = f1_score(y_val, y_pred)\n", + " golden_f1_scores.append(f1)\n", + " print(f\"Fold {fold} - Golden Feature F1: {f1:.4f}\")\n", + "\n", + "avg_golden_f1 = np.mean(golden_f1_scores)\n", + "print(f\"\\nAverage F1 Score with Golden Feature Only: {avg_golden_f1:.4f}\")\n", + "print(f\"Average F1 Score with All Features: {avg_f1:.4f}\")\n", + "print(f\"Difference: {avg_f1 - avg_golden_f1:.4f}\")Claude is AI and can make mistakes. Please double-check responses." + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/408/Q1.ipynb b/submissions_extracted/408/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..02041399fb1061d628d7f83d4e92fd059d0af9ee --- /dev/null +++ b/submissions_extracted/408/Q1.ipynb @@ -0,0 +1,480 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q1-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "import pandas as pd\n", + "df = pd.read_csv(f\"{path}/Q1_data.csv\") # using pandas library to read the csv path" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "df.head() # inspecting the first 5 rows with .head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "df.info() #using .info() to check columns, non nukk count, and dtypes" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "df.describe() # statistical description using describe -- from here we can tell what needs scaling too" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "#using a function that takes in our dataframe and target column which is 'Delivery_Time'\n", + "import matplotlib.pyplot as plt # importing matplotlib to be able to visualize\n", + "def check_target_distribution(df, target_column):\n", + " df[target_column].hist(bins=30, edgecolor='black') #specifying the number of bins in the hsitogram and the edge color to black\n", + "\n", + " plt.title(f\"Target Distribution ({target_column})\")\n", + " plt.xlabel(target_column)\n", + " plt.ylabel(\"Frequency\")\n", + " plt.grid(False)\n", + "\n", + " plt.show()\n", + "\n", + "check_target_distribution(df, \"Delivery_Time\") #passing the data frame and the target column name into the function" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "#order id is an irrelevent column for our task therefore will be dropped (we already have indexing from 0 to n)\n", + "df = df.drop(columns=['Order_ID'])" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "# first ill check for missing values\n", + "df.isnull().sum() # this will give me the sum of nulls for each column. if i added an extra .sum() it would give me the total null values\n", + "# THIS HAD NULLS IN IT but i reran the notebook!! they trend was the null values came from the categorical columns. and\n", + "# also the target column had the most nulls" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# weather is categorical so i'll use fillna(df['Weather'].mode()[0])\n", + "df['Weather'].fillna(df['Weather'].mode()[0])\n", + "df.isnull().sum()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# i realized that the columns with missing values are mostly categorical. maybe if i encode them first it'll be better.\n", + "# now i will fill our target\n", + "df['Delivery_Time'].fillna(df['Delivery_Time'].mean()) # i wanted to use mode but it wouldnt work\n", + "df.isnull().sum()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "df" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# double checking\n", + "df.isnull().sum().sum() # checking for any null values anywhere not in a specififc column" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "df['Delivery_Time'].fillna(df['Delivery_Time'].mean())" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# im having a lot of issues with dropping the rows.not sure why." + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "# checking for duplicates\n", + "def check_duplicates(df):\n", + " duplicates = df.duplicated().sum()\n", + " print(f\"Number of Duplicate Samples: {duplicates}\")\n", + " if duplicates > 0:\n", + " print(\"Dropping Duplicates...\")\n", + " df.drop_duplicates(inplace=True)\n", + " print(\"Duplicates Dropped.\")\n", + " else:\n", + " print(\"No Duplicate Samples Found.\")\n", + "\n", + "check_duplicates(df)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "# checking if we have categorical columns (we do but just good practice)\n", + "categorical_cols = df.select_dtypes(include=[\"object\"]).columns\n", + "\n", + "print(\"Categorical Columns:\", list(categorical_cols))" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Encode Categorical Features\n", + "# label encoder is used for ordinal data and the data thats present has some ordinal features\n", + "from sklearn.preprocessing import LabelEncoder #import LabelEncoder\n", + "\n", + "#print('data before encoding:\\n', df) #show before encoding\n", + "\n", + "##label_encoder = LabelEncoder() # Instantiate LabelEncoder\n", + "#df = label_encoder.fit_transform(df) # Apply fit_transform to the column\n", + "\n", + "#print('\\nData after encoding:\\n', df) #show after encoding\n", + "# i tried one hot but it completely messed up my code\n", + "\n", + "\n", + "#from sklearn.preprocessing import OneHotEncoder #import OneHotEncoder\n", + "\n", + "#print('data before encoding:\\n', df) #show before encoding\n", + "\n", + "#onehot_encoder = OneHotEncoder(sparse_output=False) # Instantiate OneHotEncoder\n", + "#df1 = onehot_encoder.fit_transform(df) # Apply fit_transform to the copied\n", + "\n", + "#print('\\nData after encoding:\\n', df1) #show after encoding\n", + "\n", + "le = LabelEncoder()\n", + "df['Weather'] = le.fit_transform(df['Weather'])\n", + "df['Traffic_Level'] = le.fit_transform(df['Traffic_Level'])\n", + "df['Time_of_Day'] = le.fit_transform(df['Time_of_Day'])\n", + "df['Vehicle_Type'] = le.fit_transform(df['Vehicle_Type'])" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "## Task 5: Write your code here:\n", + "# applying feature scaling using standard scaler\n", + "from sklearn.preprocessing import StandardScaler #import StandardScaler\n", + "\n", + "print('data before scaling:\\n', df) #show before scaling\n", + "standard_scaler = StandardScaler() # Instantiate StandardScaler\n", + "df_s = standard_scaler.fit_transform(df) # Apply fit_transform\n", + "\n", + "print('\\nData after scaling:\\n', df_s) #show after scaling\n", + "\n", + "# I did the scaling but couldnt figure out why my split woulnt work. the output is below, but the rest of the code is not scaled.\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 6: Write your code here:\n", + "# checking for target imbalance\n", + "# we already check the distribution and it is slightly skewed. in these cases we should use log transform\n", + "# im going to use stratifed kflod to address any possible problem that could occur" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "df" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "X = df.drop(\"Delivery_Time\", axis=1).astype(float) # drop the target column\n", + "y = df['Delivery_Time'].astype(float) # only use the target column" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:\n", + "# using stratified kfold for imblances so it is properly trained and tested with the same ratios.\n", + "from sklearn.model_selection import StratifiedKFold\n", + "\n", + "# Use previously generated random classification data\n", + "X, y = X.copy(), y.copy()\n", + "\n", + "# Show full dataset class distribution\n", + "full_ratio = (y.value_counts(normalize=True) * 100).sort_index()\n", + "print(\"Full Dataset Class Distribution\")\n", + "print(\" y class percentages:\", {k: f\"{v:.2f}%\" for k, v in full_ratio.items()})\n", + "print(\"-\" * 40)\n", + "\n", + "# Define Stratified K-Fold\n", + "skf = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)\n", + "\n", + "print(\"Stratified K-Fold Cross Validation\\n\" + \"-\"*40)\n", + "\n", + "for fold, (train_idx, test_idx) in enumerate(skf.split(X, y), start=1):\n", + " # indexing for each fold\n", + " X_train, X_test = X.iloc[train_idx], X.iloc[test_idx]\n", + " y_train, y_test = y.iloc[train_idx], y.iloc[test_idx]\n", + "\n", + " print(f\"Fold {fold}\")\n", + " print(\" X_train shape:\", X_train.shape)\n", + " print(\" X_test shape :\", X_test.shape)\n", + " print(\" y_train shape:\", y_train.shape)\n", + " print(\" y_test shape :\", y_test.shape)\n", + "\n", + " # showing class distribution\n", + " train_ratio = (y_train.value_counts(normalize=True) * 100).sort_index()\n", + " test_ratio = (y_test.value_counts(normalize=True) * 100).sort_index()\n", + "\n", + " print(\" y_train class percentages:\", {k: f\"{v:.2f}%\" for k, v in train_ratio.items()})\n", + " print(\" y_test class percentages :\", {k: f\"{v:.2f}%\" for k, v in test_ratio.items()})\n", + "\n", + " print(\"-\" * 40)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# train a radom forest model\n", + "from sklearn.ensemble import RandomForestClassifier" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "sklearn_models = {\n", + "\n", + " \"Random Forest\": RandomForestClassifier(\n", + " n_estimators=320, # Number of trees\n", + " max_depth=4\n", + " )\n", + "}" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "all_results = {}\n", + "\n", + "for name in sklearn_models:\n", + " all_results[name] = {'accuracy': [], 'precision': [], 'recall': [], 'f1': []}" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "n_splits = 5 # K\n", + "\n", + "# Stratified 5-Fold Cross-Validation, shuffled\n", + "skf = StratifiedKFold(n_splits=n_splits, shuffle=True, random_state=42)\n", + "for fold_idx, (train_index, test_index) in enumerate(skf.split(X, y)):\n", + " print(f\"\\nFold {fold_idx + 1}/{n_splits}\")\n", + "\n", + " # 1. Split data\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", + " # 2. Train & Validate sklearn models\n", + " for model_name, model in sklearn_models.items():\n", + " print(f\"Training {model_name}...\")\n", + " model.fit(X_train, y_train) # train\n", + " y_pred = model.predict(X_test) # validate\n", + "\n", + " # 3. Save metrics for that model in this fold\n", + " accuracy = accuracy_score(y_test, y_pred)\n", + " precision = precision_score(y_test, y_pred, zero_division=0)\n", + " recall = recall_score(y_test, y_pred, zero_division=0)\n", + " f1 = f1_score(y_test, y_pred, zero_division=0)\n", + "\n", + " all_results[model_name]['accuracy'].append(accuracy)\n", + " all_results[model_name]['precision'].append(precision)\n", + " all_results[model_name]['recall'].append(recall)\n", + " all_results[model_name]['f1'].append(f1)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "#MAE\n", + "from sklearn.metrics import mean_absolute_error, mean_squared_error\n", + "mae = mean_absolute_error(y_test, y_pred)\n", + "\n", + "print(f\"MAE: ${mae:,.2f}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "# the coefficients of ridge and lasso would tell us the feature importance. so the larger the value the more important the feature is.\n", + "\n", + "coeffs = {}\n", + "\n", + "coeffs['Lasso'] = models['LASSO Regression'].coef_ # weights for each feature\n", + "coeffs['Ridge'] = models['Ridge Regression'].coef_ # weights for each feature\n", + "\n", + "fig, axes = plt.subplots(1, 2, figsize=(15, 6))\n", + "axes = axes.flatten()\n", + "features = X.columns\n", + "\n", + "for i, (model_name, coef) in enumerate(coeffs.items()):\n", + " # Sort features by absolute coefficient value\n", + " absolute_coef = np.abs(coef)\n", + " sorted_idx = np.argsort(absolute_coef)\n", + "\n", + " ax = axes[i]\n", + " ax.barh(features[sorted_idx], coef[sorted_idx])\n", + " ax.set_title(f\"{model_name} Coefficients\")\n", + " ax.set_xlabel(\"Coefficient Value (Impact)\")\n", + "\n", + "plt.tight_layout()\n", + "plt.show()\n", + "\n", + "# Ridge will smoothly shrink coefficients but rarely actually sets them to 0 this is called weight decay\n", + "# Lasso would push some to zero, so if i could run the cell properly the ridge would probably have more feature importance given" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/408/Q2.ipynb b/submissions_extracted/408/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..4de8b9749e07f955a36f4f33d902db5d274a7d81 --- /dev/null +++ b/submissions_extracted/408/Q2.ipynb @@ -0,0 +1,397 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q2-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import os\n", + "import pandas as pd\n", + "import numpy as np\n", + "from PIL import Image\n", + "from sklearn.model_selection import train_test_split\n", + "\n", + "# Load Labels\n", + "labels_df = pd.read_csv(os.path.join(path, \"labels.csv\"))\n", + "img_dir = os.path.join(path, \"images\")\n", + "\n", + "images = []\n", + "ages = []\n", + "\n", + "# Load Images and Resize\n", + "print(\"Loading images...\")\n", + "for index, row in labels_df.iterrows():\n", + " img_name = row.iloc[0]\n", + " age = row.iloc[1]\n", + " img_path = os.path.join(img_dir, img_name)\n", + "\n", + " if os.path.exists(img_path):\n", + " img = Image.open(img_path).convert('RGB')\n", + " img_array = np.array(img) / 255.0 # Normalize pixel values to [0, 1]\n", + " images.append(img_array)\n", + " ages.append(age)\n", + "\n", + "X = np.array(images)\n", + "y = np.array(ages)\n", + "\n", + "# Transpose image dimensions to match PyTorch format (N, C, H, W)\n", + "X = np.transpose(X, (0, 3, 1, 2))\n", + "\n", + "# Split Data\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n", + "\n", + "print(f\"X_train shape: {X_train.shape}\")\n", + "print(f\"X_test shape: {X_test.shape}\")\n", + "print(f\"y_train shape: {y_train.shape}\")\n", + "print(f\"y_test shape: {y_test.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import pandas as pd\n", + "import numpy as np\n", + "import torch\n", + "import torch.nn as nn\n", + "from torch.optim import AdamW\n", + "import matplotlib.pyplot as plt\n", + "from torch.utils.data import DataLoader, TensorDataset\n", + "from sklearn.model_selection import train_test_split\n", + "from sklearn.preprocessing import StandardScaler, LabelEncoder\n", + "from sklearn.metrics import mean_absolute_error, mean_squared_error, r2_score" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 1. Convert Numpy arrays to PyTorch Tensors\n", + "\n", + "X_train = torch.tensor(X_train, dtype=torch.float32)\n", + "X_test = torch.tensor(X_test, dtype=torch.float32)\n", + "y_train = torch.tensor(y_train, dtype=torch.float32)\n", + "y_test = torch.tensor(y_test, dtype=torch.float32)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 2. Create TensorDataset objects\n", + "train_dataset = TensorDataset(X_train, y_train)\n", + "test_dataset = TensorDataset(X_test, y_test)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 3. Create DataLoaders\n", + "train_loader = DataLoader(train_dataset, batch_size=32, shuffle=True)\n", + "test_loader = DataLoader(test_dataset, batch_size=32, shuffle=False) # test is always shuffle = false" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 4. Print shape of one batch\n", + "# Print dataset sizes\n", + "print(\"Train dataset:\", len(train_dataset))\n", + "print(\"Test dataset:\", len(test_dataset))\n", + "\n", + "# Get the first batch from the training DataLoader\n", + "# both done but only printing one as required\n", + "X_batch, y_batch = next(iter(train_loader))\n", + "print(f\"Training batch input shape: {X_batch.shape}\")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 5. Display sample images\n", + "\n", + "# Get one batch of images and labels\n", + "images, labels = next(iter(train_loader))\n", + "\n", + "# Display the first 6 images in the batch\n", + "plt.figure(figsize=(8, 4))\n", + "\n", + "for i in range(6):\n", + " plt.subplot(2, 3, i + 1)\n", + "\n", + " # Convert from (C, H, W) to (H, W, C) for matplotlib\n", + " img = images[i].permute(1, 2, 0)\n", + "\n", + " plt.imshow(img)\n", + " plt.title(f\"Label: {labels[i].item()}\")\n", + " plt.axis('off')\n", + "\n", + "plt.tight_layout()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your model class here:\n", + "class NN4Layer(nn.Module):\n", + " def __init__(self, input_dim, hidden_dim):\n", + " super(NN4Layer, self).__init__()\n", + "\n", + " # First linear layer: input features -> hidden layer\n", + " self.layer1 = nn.Linear(input_dim, hidden_dim)\n", + "\n", + " # Second linear layer: hidden layer -> hidden layer\n", + " self.layer2 = nn.Linear(hidden_dim, hidden_dim)\n", + "\n", + " # Output layer: hidden layer -> single continuous value\n", + " self.layer3 = nn.Linear(hidden_dim, hidden_dim)\n", + "\n", + " self.layer4 = nn.Linear(hidden_dim, 1) # 1 cause its regression\n", + "\n", + " # ReLU activation for non-linearity in hidden layers\n", + " self.relu = nn.ReLU()\n", + "\n", + " # Defines how input data flows through the network\n", + " def forward(self, x):\n", + " # First hidden layer\n", + " a1 = self.relu(self.layer1(x))\n", + "\n", + " # Second hidden layer\n", + " a2 = self.relu(self.layer2(a1))\n", + "\n", + " a3 = self.relu(self.layer2(a2))\n", + "\n", + " # Output layer (regression output)\n", + " output = self.layer4(a3)\n", + " # because this is the output layer and we want it to be linear so we can we can calculate loss for this task. we will use\n", + " # MSE since its regression\n", + "\n", + " return output" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your training loop here:\n", + "def train_one_epoch(model, optimizer, criterion, train_loader, device):\n", + " # Set the model to training mode\n", + " model.train()\n", + "\n", + " running_loss = 0.0\n", + "\n", + " for X_batch, y_batch in train_loader:\n", + " # Move batch to the selected device\n", + " X_batch = X_batch.to(device) # shape: (batch_size, num_features)\n", + " y_batch = y_batch.view(-1, 1).to(device) # shape: (batch_size, 1)\n", + "\n", + " # Forward pass (continuous output)\n", + " outputs = model(X_batch) # shape: (batch_size, 1)\n", + " loss = criterion(outputs, y_batch)\n", + "\n", + " # Backward pass & optimization\n", + " optimizer.zero_grad() # Clear previous gradients\n", + " loss.backward() # Compute gradients\n", + " optimizer.step() # Update model parameters\n", + "\n", + " running_loss += loss.item()\n", + "\n", + " # Average loss over all batches\n", + " avg_loss = running_loss / len(train_loader)\n", + "\n", + " return avg_loss" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your validation loop here:\n", + "def validate(model, criterion, test_loader, device):\n", + " # Set the model to evaluation mode\n", + " model.eval()\n", + "\n", + " running_loss = 0.0\n", + "\n", + " with torch.no_grad():\n", + " for X_batch, y_batch in test_loader:\n", + " # Move data to device\n", + " X_batch = X_batch.to(device) # shape: (batch_size, num_features)\n", + " y_batch = y_batch.view(-1, 1).to(device) # shape: (batch_size, 1)\n", + "\n", + " # Forward pass (continuous output)\n", + " outputs = model(X_batch) # shape: (batch_size, 1)\n", + " loss = criterion(outputs, y_batch)\n", + "\n", + " running_loss += loss.item()\n", + "\n", + " # Average loss over all batches\n", + " avg_loss = running_loss / len(test_loader)\n", + "\n", + " return avg_loss" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Define device, model, loss, optimizer:\n", + "# device\n", + "device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# extra\n", + "sample_image, sample_label = train_dataset[0]\n", + "print(f\"Image shape: {sample_image.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# model\n", + "input_dim = 36 #3*32*32 #this is usually the image dims so\n", + "hidden_dim = 10\n", + "model = NN4Layer(input_dim, hidden_dim).to(device)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Start training for 20 epochs:\n", + "num_epochs = 20\n", + "learning_rate = 0.001\n", + "criterion = nn.MSELoss()\n", + "optimizer = AdamW(model.parameters(), learning_rate)\n", + "# Run Training\n", + "train_losses = []\n", + "val_losses = []\n", + "\n", + "print('Starting Training...')\n", + "for epoch in range(num_epochs):\n", + " # Train one epoch\n", + " train_loss = train_one_epoch(model, optimizer, criterion, train_loader, device)\n", + "\n", + " # Validate\n", + " val_loss = validate(model, criterion, test_loader, device)\n", + "\n", + " train_losses.append(train_loss)\n", + " val_losses.append(val_loss)\n", + "\n", + " if (epoch + 1) % 5 == 0:\n", + " print(\n", + " f'Epoch [{epoch+1}/{num_epochs}], '\n", + " f'Train Loss: {train_loss:.4f}, '\n", + " f'Val Loss: {val_loss:.4f}'\n", + " )\n", + "\n", + "print('Training Complete!')" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# i cant figure out why the matrices wont multiply. i tried the usual fixes but it didnt work this time.\n", + "# even when i make sure mat1 and 2 are multipliable it doesnt work" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "plt.figure(figsize=(7, 5))\n", + "\n", + "plt.plot(train_losses, label='Train Loss')\n", + "plt.plot(val_losses, label='Validation Loss')\n", + "plt.title('Loss over Epochs')\n", + "plt.xlabel('Epoch')\n", + "plt.ylabel('Loss (MSE)')\n", + "plt.legend()\n", + "\n", + "plt.tight_layout()\n", + "plt.show()\n", + "\n", + "# if theres a good fit the training and val loss will be low\n", + "# if theres underfitting both will be high\n", + "# if theres overfitting train loss low and val loss diverges upward" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2 (Bonus): Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/408/Q3.ipynb b/submissions_extracted/408/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..505030d33403e069c7a6efa226e392a32469155c --- /dev/null +++ b/submissions_extracted/408/Q3.ipynb @@ -0,0 +1,363 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "\n", + "\n", + "# Download latest version\n", + "\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q3-exam-data\")\n", + "\n", + "\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "import pandas as pd\n", + "df = pd.read_csv(f\"{path}/Q3_data.csv\") # using pandas library to read the csv path" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "df.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "df.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "# Missing values\n", + "print(\"Missing values:\")\n", + "print(df.isnull().sum())" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Missing values\n", + "print(\"Missing values:\")\n", + "print(df.isnull().sum().sum())" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "#handle\n", + "missing_percentage = (df.isnull().sum() / len(df)) * 100\n", + "missing_data = pd.DataFrame({\n", + " 'Column': missing_percentage.index,\n", + " 'Missing_Percentage': missing_percentage.values\n", + "})\n", + "missing_data = missing_data[missing_data['Missing_Percentage'] > 0].sort_values('Missing_Percentage', ascending=False)\n", + "\n", + "print(\"Missing Data Analysis:\")\n", + "missing_data.head(10)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# most of them are missing\n", + "df.drop(columns=['D_87']) # drop entire column if too many values are missing\n", + "# and i would go through the rest of them." + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "#duplicate samples?\n", + "def check_duplicates(df):\n", + " duplicates = df.duplicated().sum()\n", + " print(f\"Number of Duplicate Samples: {duplicates}\")\n", + " if duplicates > 0:\n", + " print(\"Dropping Duplicates...\")\n", + " df.drop_duplicates(inplace=True)\n", + " print(\"Duplicates Dropped.\")\n", + " else:\n", + " print(\"No Duplicate Samples Found.\")\n", + "\n", + "check_duplicates(df)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "# i will not encode because the data is already numeric. also, i was unable to drop\n", + "# ategorical columns?\n", + "categorical_cols = df.select_dtypes(include=[\"object\"]).columns\n", + "\n", + "print(\"Categorical Columns:\", list(categorical_cols))" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "from sklearn.preprocessing import StandardScaler\n", + "numerical_cols = df.select_dtypes(include=[\"int64\", \"float64\"]).columns.drop(\"Target\") # DON'T SCALE THE TARGET\n", + "\n", + "scaler = StandardScaler()\n", + "df[numerical_cols] = scaler.fit_transform(df[numerical_cols])\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "import matplotlib.pyplot as plt\n", + "plt.figure(figsize=(10, 5))\n", + "plt.hist(df['Target'].dropna(), bins=50, edgecolor='black')\n", + "plt.title('Target Distribution')\n", + "plt.xlabel('Target')\n", + "plt.ylabel('Frequency')\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "X = df.drop(\"Target\", axis=1).astype(float)\n", + "y = df['Target'].astype(float)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:\n", + "from sklearn.model_selection import StratifiedKFold\n", + "\n", + "X, y = X.copy(), y.copy()\n", + "\n", + "# Show full dataset class distribution\n", + "full_ratio = (y.value_counts(normalize=True) * 100).sort_index()\n", + "print(\"Full Dataset Class Distribution\")\n", + "print(\" y class percentages:\", {k: f\"{v:.2f}%\" for k, v in full_ratio.items()})\n", + "print(\"-\" * 40)\n", + "\n", + "# Define Stratified K-Fold\n", + "skf = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)\n", + "\n", + "print(\"Stratified K-Fold Cross Validation\\n\" + \"-\"*40)\n", + "\n", + "for fold, (train_idx, test_idx) in enumerate(skf.split(X, y), start=1):\n", + " # indexing for each fold\n", + " X_train, X_test = X.iloc[train_idx], X.iloc[test_idx]\n", + " y_train, y_test = y.iloc[train_idx], y.iloc[test_idx]\n", + "\n", + " print(f\"Fold {fold}\")\n", + " print(\" X_train shape:\", X_train.shape)\n", + " print(\" X_test shape :\", X_test.shape)\n", + " print(\" y_train shape:\", y_train.shape)\n", + " print(\" y_test shape :\", y_test.shape)\n", + "\n", + " # showing class distribution\n", + " train_ratio = (y_train.value_counts(normalize=True) * 100).sort_index()\n", + " test_ratio = (y_test.value_counts(normalize=True) * 100).sort_index()\n", + "\n", + " print(\" y_train class percentages:\", {k: f\"{v:.2f}%\" for k, v in train_ratio.items()})\n", + " print(\" y_test class percentages :\", {k: f\"{v:.2f}%\" for k, v in test_ratio.items()})\n", + "\n", + " print(\"-\" * 40)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# cat boost\n", + "from sklearn.neighbors import KNeighborsClassifier\n", + "from sklearn.svm import SVC\n", + "from sklearn.tree import DecisionTreeClassifier\n", + "from sklearn.ensemble import RandomForestClassifier\n", + "from xgboost import XGBClassifier\n", + "from catboost import CatBoostClassifier\n", + "\n", + "sklearn_models = {\n", + " \"CatBoost\": CatBoostClassifier(\n", + " verbose=0,\n", + " n_estimators=320,\n", + " max_depth=4\n", + " )\n", + "}" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# please consider the below code. i am unable to import catboost. if i could this is what id have done.\n", + "\n", + "# i would evaluate using f1 because of the class imbalance\n", + "all_results = {}\n", + "for name in sklearn_models:\n", + " all_results[name] = {'f1': []}\n", + "\n", + "# again, it wont allow me to import catboost. but i would use straified kfold because of the class imbalance\n", + "n_splits = 5 # K\n", + "skf = StratifiedKFold(n_splits=n_splits, shuffle=True, random_state=42)\n", + "\n", + "for fold_idx, (train_index, test_index) in enumerate(skf.split(X, y)):\n", + " print(f\"\\nFold {fold_idx + 1}/{n_splits}\")\n", + "\n", + " # 1. Split data\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", + " # 2. Train & Validate sklearn models\n", + " for model_name, model in sklearn_models.items():\n", + " print(f\"Training {model_name}...\")\n", + " model.fit(X_train, y_train) # train\n", + " y_pred = model.predict(X_test) # validate\n", + " # i reused code, but only kept the catboost part!\n", + "\n", + " # 3. Save metrics for that model in this fold\n", + " f1 = f1_score(y_test, y_pred, zero_division=0)\n", + "\n", + " all_results[model_name]['f1'].append(f1)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# i would then print out the average of the folds." + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "importances = {}\n", + "importances['CatBoost'] = sklearn_models['CatBoost'].feature_importances_\n", + "\n", + "# Create a 1x3 plot\n", + "fig, axes = plt.subplots(1, 3, figsize=(18, 6))\n", + "axes = axes.flatten()\n", + "features = X.columns\n", + "\n", + "for i, (model_name, imp) in enumerate(importances.items()):\n", + " # Sort features by importance for a cleaner plot\n", + " sorted_idx = np.argsort(imp)\n", + "\n", + " ax = axes[i]\n", + " ax.barh(features[sorted_idx], imp[sorted_idx])\n", + " ax.set_title(f\"{model_name} Feature Importance\")\n", + " ax.set_xlabel(\"Importance Score\")\n", + "\n", + "plt.tight_layout()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "print(\"I had no way to import catboost. the most important feature would have been the one that dominated the figure\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/409/Q1.ipynb b/submissions_extracted/409/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..3cf6a935aa8973b1888300ce7041f983fb7070b3 --- /dev/null +++ b/submissions_extracted/409/Q1.ipynb @@ -0,0 +1,265 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import pandas as pd\n", + "import matplotlib.pyplot as plt\n", + "import os\n", + "import kagglehub\n", + "\n", + "from sklearn.model_selection import train_test_split, StratifiedKFold, cross_val_score\n", + "from sklearn.preprocessing import StandardScaler, LabelEncoder\n", + "from sklearn.ensemble import RandomForestClassifier\n", + "from sklearn.metrics import classification_report, confusion_matrix, accuracy_score\n", + "\n", + "import warnings\n", + "warnings.filterwarnings('ignore')" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q1-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:import numpy as np\n", + "csv_path = os.path.join(path, \"Q1_data.csv\")\n", + "\n", + "df = pd.read_csv(csv_path)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "df.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "df.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "plt.hist(df['Delivery_Time'])\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "df = df.drop(columns=\"Order_ID\", axis=1)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "print(df.isnull().sum())\n", + "#I can see that the missing values are from (weather, traffic level, time of day, Courier_Experience_yrs and Delivery_Time)\n", + "# and all of them can be replaced wwith the mean or mode\n", + "\n", + "\n", + "cols = ['Weather','Traffic_Level','Time_of_Day']\n", + "df_clean = df[cols].copy()\n", + "df_clean = df_clean.dropna(subset= ['Weather','Traffic_Level','Time_of_Day'])\n", + "\n", + "\n", + "\n", + "df['Courier_Experience_yrs'] = df['Courier_Experience_yrs'].fillna(df['Courier_Experience_yrs'].mode()[0])\n", + "df['Delivery_Time'] = df['Delivery_Time'].fillna(df['Delivery_Time'].mode()[0])\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "def check_duplicates(df):\n", + " duplicates = df.duplicated().sum()\n", + " print(f\"Number of Duplicate Samples: {duplicates}\")\n", + " if duplicates > 0:\n", + " print(\"Dropping Duplicates...\")\n", + " df.drop_duplicates(inplace=True)\n", + " print(\"Duplicates Dropped.\")\n", + " else:\n", + " print(\"No Duplicate Samples Found.\")\n", + "\n", + "check_duplicates(df)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "from sklearn.preprocessing import LabelEncoder\n", + "\n", + "le = LabelEncoder()\n", + "df['Delivery_Time'] = le.fit_transform(df['Delivery_Time'])\n", + "\n", + "categorical_features = df.select_dtypes(include=['object']).columns\n", + "\n", + "df = pd.get_dummies(df, columns=categorical_features, drop_first=False)\n", + "\n", + "df = df.astype(float)\n", + "\n", + "df" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "\n", + "numerical_cols = ['Distance_km','Preparation_Time_min','Courier_Experience_yrs','Delivery_Time']\n", + "\n", + "scaler = StandardScaler()\n", + "df[numerical_cols] = scaler.fit_transform(df[numerical_cols])\n", + "df" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 6: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "X = df.drop(columns=('Delivery_Time'), axis=1)\n", + "y = df['Delivery_Time']" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42, stratify=y)\n", + "# Print shapes\n", + "print(\"X_train shape:\", X_train.shape)\n", + "print(\"X_test shape:\", X_test.shape)\n", + "print(\"y_train shape:\", y_train.shape)\n", + "print(\"y_test shape:\", y_test.shape)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "importance = pd.DataFrame({\n", + " 'feature': feature_cols,\n", + " 'importance': model.feature_importances_\n", + "}).sort_values('importance', ascending=False)\n", + "\n", + "plt.figure(figsize=(10, 6))\n", + "plt.barh(importance['feature'], importance['importance'], color='purple')\n", + "plt.xlabel('Importance')\n", + "plt.title('Feature Importance')\n", + "plt.gca().invert_yaxis()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "plt.hist(df['Delivery_Time'])\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/409/Q2.ipynb b/submissions_extracted/409/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..cab658bfcd61890fe12b8966b724d6aadcff3770 --- /dev/null +++ b/submissions_extracted/409/Q2.ipynb @@ -0,0 +1,346 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q2-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import os\n", + "import pandas as pd\n", + "import numpy as np\n", + "from PIL import Image\n", + "from sklearn.model_selection import train_test_split\n", + "\n", + "# Load Labels\n", + "labels_df = pd.read_csv(os.path.join(path, \"labels.csv\"))\n", + "img_dir = os.path.join(path, \"images\")\n", + "\n", + "images = []\n", + "ages = []\n", + "\n", + "# Load Images and Resize\n", + "print(\"Loading images...\")\n", + "for index, row in labels_df.iterrows():\n", + " img_name = row.iloc[0]\n", + " age = row.iloc[1]\n", + " img_path = os.path.join(img_dir, img_name)\n", + "\n", + " if os.path.exists(img_path):\n", + " img = Image.open(img_path).convert('RGB')\n", + " img_array = np.array(img) / 255.0 # Normalize pixel values to [0, 1]\n", + " images.append(img_array)\n", + " ages.append(age)\n", + "\n", + "X = np.array(images)\n", + "y = np.array(ages)\n", + "\n", + "# Transpose image dimensions to match PyTorch format (N, C, H, W)\n", + "X = np.transpose(X, (0, 3, 1, 2))\n", + "\n", + "# Split Data\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n", + "\n", + "print(f\"X_train shape: {X_train.shape}\")\n", + "print(f\"X_test shape: {X_test.shape}\")\n", + "print(f\"y_train shape: {y_train.shape}\")\n", + "print(f\"y_test shape: {y_test.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 1. Convert Numpy arrays to PyTorch Tensors\n", + "from sklearn.datasets import load_breast_cancer\n", + "from sklearn.model_selection import train_test_split\n", + "from sklearn.preprocessing import StandardScaler\n", + "from torch.utils.data import TensorDataset\n", + "from torch.utils.data import DataLoader\n", + "import torch\n", + "\n", + "\n", + "scaler = StandardScaler()\n", + "\n", + "X_train = torch.tensor(X_train, dtype=torch.float32)\n", + "X_test = torch.tensor(X_test, dtype=torch.float32)\n", + "y_train = torch.tensor(y_train, dtype=torch.float32)\n", + "y_test = torch.tensor(y_test, dtype=torch.float32)\n", + "\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 2. Create TensorDataset objects\n", + "from torch.utils.data import TensorDataset\n", + "\n", + "train_dataset = TensorDataset(X_train, y_train)\n", + "test_dataset = TensorDataset(X_test, y_test)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 3. Create DataLoaders\n", + "from torch.utils.data import DataLoader\n", + "\n", + "train_loader = DataLoader(\n", + " train_dataset,\n", + " batch_size=32,\n", + " shuffle=True,\n", + " num_workers=2\n", + ")\n", + "\n", + "test_loader = DataLoader(\n", + " test_dataset,\n", + " batch_size=32,\n", + " shuffle=False,\n", + " num_workers=2\n", + ")\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 4. Print shape of one batch\n", + "X_batch, y_batch = next(iter(train_loader))\n", + "print(f\"Training batch input shape: {X_batch.shape}\")\n", + "print(f\"Training batch labels shape: {y_batch.shape}\")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 5. Display sample images\n", + "import matplotlib.pyplot as plt\n", + "images, labels = next(iter(train_loader))\n", + "\n", + "\n", + "\n", + "plt.imshow(images[2])\n", + "plt.title(f\"Label: {labels[2].item()}\")\n", + "plt.axis('off')\n", + "\n", + "plt.tight_layout()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your model class here:\n", + "import torch.nn as nn\n", + "\n", + "\n", + "class NN3Layer(nn.Module):\n", + " def __init__(self, input_dim, hidden_dim):\n", + " super(NN3Layer, self).__init__()\n", + " self.layer1 = nn.Linear(input_dim, hidden_dim)\n", + "\n", + " self.layer2 = nn.Linear(hidden_dim, hidden_dim)\n", + "\n", + " self.layer3 = nn.Linear(hidden_dim, 1)\n", + "\n", + " self.relu = nn.ReLU()\n", + "\n", + " def forward(self, x):\n", + " a1 = self.relu(self.layer1(x))\n", + "\n", + " a2 = self.relu(self.layer2(a1))\n", + "\n", + " a3 = self.relu(self.layer2(a2))\n", + "\n", + " output = self.layer3(a3)\n", + "\n", + " return output" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your training loop here:\n", + "def train_one_epoch(model, optimizer, criterion, train_loader, device):\n", + " model.train()\n", + "\n", + " running_loss = 0.0\n", + "\n", + " for X_batch, y_batch in train_loader:\n", + "\n", + " X_batch = X_batch.to(device)\n", + " y_batch = y_batch.view(-1, 1).to(device)\n", + "\n", + " outputs = model(X_batch)\n", + " loss = criterion(outputs, y_batch)\n", + "\n", + " optimizer.zero_grad()\n", + " loss.backward()\n", + " optimizer.step()\n", + "\n", + " running_loss += loss.item()\n", + "\n", + " avg_loss = running_loss / len(train_loader)\n", + "\n", + " return avg_loss" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your validation loop here:\n", + "def validate(model, criterion, test_loader, device):\n", + " model.eval()\n", + "\n", + " running_loss = 0.0\n", + "\n", + " with torch.no_grad():\n", + " for X_batch, y_batch in test_loader:\n", + "\n", + " X_batch = X_batch.to(device)\n", + " y_batch = y_batch.view(-1, 1).to(device)\n", + "\n", + " outputs = model(X_batch)\n", + " loss = criterion(outputs, y_batch)\n", + "\n", + " running_loss += loss.item()\n", + "\n", + " avg_loss = running_loss / len(test_loader)\n", + "\n", + " return avg_loss" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Define device, model, loss, optimizer:\n", + "from torch.optim import Adam\n", + "device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n", + "\n", + "\n", + "input_dim = X_train.shape[1]\n", + "hidden_dim = 64\n", + "\n", + "model = NN3Layer(input_dim, hidden_dim).to(device)\n", + "\n", + "total_params = sum(p.numel() for p in model.parameters() if p.requires_grad)\n", + "learning_rate = 0.001\n", + "\n", + "criterion = nn.MSELoss()\n", + "optimizer = Adam(model.parameters(), learning_rate)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Start training for 20 epochs:\n", + "num_epochs = 20\n", + "\n", + "#RuntimeError: mat1 and mat2 shapes cannot be multiplied (3456x36 and 3x64) i need to squeeze but i have no time\n", + "train_losses = []\n", + "val_losses = []\n", + "\n", + "for epoch in range(num_epochs):\n", + " # Train one epoch\n", + " train_loss = train_one_epoch(model, optimizer, criterion, train_loader, device)\n", + "\n", + " # Validate\n", + " val_loss = validate(model, criterion, test_loader, device)\n", + "\n", + " train_losses.append(train_loss)\n", + " val_losses.append(val_loss)\n", + "\n", + " if (epoch + 1) % 5 == 0:\n", + " print(\n", + " f'Epoch [{epoch+1}/{num_epochs}], '\n", + " f'Train Loss: {train_loss:.4f}, '\n", + " f'Val Loss: {val_loss:.4f}'\n", + " )" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "plt.figure(figsize=(7, 5))\n", + "\n", + "plt.plot(train_losses, label='Train Loss')\n", + "plt.plot(val_losses, label='Validation Loss')\n", + "plt.title('Loss over Epochs')\n", + "plt.xlabel('Epoch')\n", + "plt.ylabel('Loss (MSE)')\n", + "plt.legend()\n", + "\n", + "plt.tight_layout()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2 (Bonus): Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/409/Q3.ipynb b/submissions_extracted/409/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..bedce242e13158b58883207f7c6a7787b01a0fb4 --- /dev/null +++ b/submissions_extracted/409/Q3.ipynb @@ -0,0 +1,242 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "import pandas as pd\n", + "import numpy as np\n", + "import torch\n", + "import torch.nn as nn\n", + "from torch.optim import AdamW\n", + "import matplotlib.pyplot as plt\n", + "from torch.utils.data import DataLoader, TensorDataset\n", + "from sklearn.model_selection import train_test_split\n", + "from sklearn.preprocessing import StandardScaler, LabelEncoder\n", + "from sklearn.metrics import mean_absolute_error, mean_squared_error, r2_score\n", + "import pandas as pd\n", + "import matplotlib.pyplot as plt\n", + "import os\n", + "import kagglehub\n", + "\n", + "from sklearn.model_selection import train_test_split, StratifiedKFold, cross_val_score\n", + "from sklearn.preprocessing import StandardScaler, LabelEncoder\n", + "from sklearn.ensemble import RandomForestClassifier\n", + "from sklearn.metrics import classification_report, confusion_matrix, accuracy_score\n", + "\n", + "import warnings\n", + "warnings.filterwarnings('ignore')" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "\n", + "\n", + "# Download latest version\n", + "\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q3-exam-data\")\n", + "\n", + "\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "csv_path = os.path.join(path, \"Q3_data.csv\")\n", + "\n", + "df = pd.read_csv(csv_path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "df.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "df.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "print(df.isnull().sum())\n", + "\n", + "\n", + "\n", + "for col in ['P_2', 'B_2', 'D_142', 'D_143', 'D_144', 'D_145']:\n", + " df[col] = df[col].fillna(df[col].mean())\n", + "print(df.isnull().sum())" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "def check_duplicates(df_clean):\n", + " duplicates = df_clean.duplicated().sum()\n", + " print(f\"Number of Duplicate Samples: {duplicates}\")\n", + " if duplicates > 0:\n", + " print(\"Dropping Duplicates...\")\n", + " df_clean.drop_duplicates(inplace=True)\n", + " print(\"Duplicates Dropped.\")\n", + " else:\n", + " print(\"No Duplicate Samples Found.\")\n", + "\n", + "check_duplicates(df)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "from sklearn.preprocessing import LabelEncoder\n", + "\n", + "le = LabelEncoder()\n", + "df['Target'] = le.fit_transform(df['Target'])\n", + "\n", + "categorical_features = df.select_dtypes(include=['object']).columns\n", + "\n", + "df = pd.get_dummies(df, columns=categorical_features, drop_first=False)\n", + "\n", + "df = df.astype(float)\n", + "\n", + "df" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "scaler = StandardScaler()\n", + "df = scaler.fit_transform(df)\n", + "df" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "X = df.drop(columns=('Target'), axis=1)\n", + "y = df['Target']" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:\n", + "# Task 2,3,4,5: Write your code here:\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42, stratify=y)\n", + "#notime\n", + "\n", + "baseline_accuracy = accuracy_score(y, baseline_pred)\n", + "baseline_precision = precision_score(y, baseline_pred, average='weighted', zero_division=0)\n", + "baseline_recall = recall_score(y, baseline_pred, average='weighted', zero_division=0)\n", + "baseline_f1 = f1_score(y, baseline_pred, average='weighted', zero_division=0)\n", + "\n", + "#iknow it's wroge but there is no time left :(" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/41/Q1.ipynb b/submissions_extracted/41/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..21de89afe52cfbeda002e75b0bcb6ead3f9bd724 --- /dev/null +++ b/submissions_extracted/41/Q1.ipynb @@ -0,0 +1,240 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "import pandas as pd\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q1-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "df = pd.read_csv('Q1_data.csv')" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "df.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "df.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + " df.plot.scatter(delivery_time)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "df.drop(columns=['Order_ID'])" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "df.isnull().sum()\n", + "df.fillna(df.mean())\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "df.duplicated()\n", + "df.drop_duplicates()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "from sklearn.preprocessing import OneHotEncoder\n", + "onehot_encoder = OneHotEncoder(sparse_output=False)\n", + "data_onehot_encoded = onehot_encoder.fit_transform(categories)\n", + "\n", + "print(data_onehot_encoded)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "from sklearn.preprocessing import StandardScaler\n", + "\n", + "\n", + "standard_scaler = StandardScaler()\n", + "data_standard_scaled = standard_scaler.fit_transform(data_for_scale)\n", + "\n", + "print( data_standard_scaled)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 6: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "from sklearn.model_selection import train_test_split\n", + "\n", + "# Use previously generated random data (example: classification data)\n", + "X, y = X_clf.copy(), y_clf.copy()\n", + "\n", + "# split ratio (80% train, 20% test)\n", + "X_train, X_test, y_train, y_test = train_test_split(\n", + " X, y,\n", + " test_size=0.2,\n", + " random_state=42,\n", + " shuffle=True,\n", + " stratify=y\n", + ")\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:\n", + "from sklearn.model_selection import KFold\n", + "\n", + "X, y = X_reg.copy(), y_reg.copy()\n", + "\n", + "\n", + "kf = KFold(n_splits=5, shuffle=True, random_state=42)\n", + "\n", + "for fold, (train_idx, test_idx) in enumerate(kf.split(X), start=1):\n", + "\n", + " X_train, X_test = X.iloc[train_idx], X.iloc[test_idx]\n", + " y_train, y_test = y.iloc[train_idx], y.iloc[test_idx]\n", + "\n", + "\n", + " def mean_squared_error(y, y_hat):\n", + " return (1 / (2 * len(y))) * np.sum((y_hat - y) ** 2)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "\n", + "plt.figure(figsize=(6, 4))\n", + "plt.scatter(y_test, y_pred, alpha=0.7)\n", + "plt.plot([min(y_test), max(y_test)],\n", + " [min(y_test), max(y_test)],\n", + " 'r--', linewidth=2)\n", + "\n", + "plt.xlabel(\"Actual y_test (Ground Truth)\")\n", + "plt.ylabel(\"Predicted y_pred (Decision Tree)\")\n", + "plt.title(\"Decision Tree Regression: Predictions vs. Ground Truth\")\n", + "plt.grid(True)\n", + "\n", + "plt.tight_layout()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + " df['column'].hist()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/41/Q2.ipynb b/submissions_extracted/41/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..dd90fdf52145fc7b1104a6a18a35c100f026c0ec --- /dev/null +++ b/submissions_extracted/41/Q2.ipynb @@ -0,0 +1,324 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q2-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import os\n", + "import pandas as pd\n", + "import numpy as np\n", + "from PIL import Image\n", + "from sklearn.model_selection import train_test_split\n", + "\n", + "# Load Labels\n", + "labels_df = pd.read_csv(os.path.join(path, \"labels.csv\"))\n", + "img_dir = os.path.join(path, \"images\")\n", + "\n", + "images = []\n", + "ages = []\n", + "\n", + "# Load Images and Resize\n", + "print(\"Loading images...\")\n", + "for index, row in labels_df.iterrows():\n", + " img_name = row.iloc[0]\n", + " age = row.iloc[1]\n", + " img_path = os.path.join(img_dir, img_name)\n", + "\n", + " if os.path.exists(img_path):\n", + " img = Image.open(img_path).convert('RGB')\n", + " img_array = np.array(img) / 255.0 # Normalize pixel values to [0, 1]\n", + " images.append(img_array)\n", + " ages.append(age)\n", + "\n", + "X = np.array(images)\n", + "y = np.array(ages)\n", + "\n", + "# Transpose image dimensions to match PyTorch format (N, C, H, W)\n", + "X = np.transpose(X, (0, 3, 1, 2))\n", + "\n", + "# Split Data\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n", + "\n", + "print(f\"X_train shape: {X_train.shape}\")\n", + "print(f\"X_test shape: {X_test.shape}\")\n", + "print(f\"y_train shape: {y_train.shape}\")\n", + "print(f\"y_test shape: {y_test.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 1. Convert Numpy arrays to PyTorch Tensors\n", + "import torch\n", + "torch.tensor(X_train)\n", + "torch.tensor(X_test)\n", + "torch.tensor(y_train)\n", + "torch.tensor(y_test)\n", + "\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 2. Create TensorDataset objects\n", + "\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 3. Create DataLoaders\n", + "from torch.utils.data import DataLoader\n", + "# DataLoader for training data\n", + "train_loader = DataLoader(\n", + " train_dataset,\n", + " batch_size=32,\n", + " shuffle=True,\n", + " num_workers=2\n", + ")\n", + "# DataLoader for test/validation data\n", + "test_loader = DataLoader(\n", + " test_dataset,\n", + " batch_size=32,\n", + " shuffle=False,\n", + " num_workers=2\n", + ")\n", + "# Get the first batch from the training DataLoader\n", + "X_batch, y_batch = next(iter(train_loader))\n", + "print(f\"Training batch input shape: {X_batch.shape}\")\n", + "print(f\"Training batch labels shape: {y_batch.shape}\")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 4. Print shape of one batch\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 5. Display sample images\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your model class here:\n", + "\n", + "class NN4Layer(nn.Module):\n", + "\n", + " def __init__(self, input_dim, hidden_dim, output_dim):\n", + " super(NN4Layer, self).__init__()\n", + "\n", + " # First linear layer: input features -> hidden layer\n", + " self.layer1 = nn.Linear(input_dim, hidden_dim)\n", + "\n", + " # Second linear layer: hidden layer -> hidden layer\n", + " self.layer2 = nn.Linear(hidden_dim, hidden_dim)\n", + "\n", + " # Third linear layer: hidden layer -> hidden layer\n", + " self.layer3 = nn.Linear(hidden_dim, hidden_dim)\n", + "\n", + " # Output layer: hidden layer -> number of classes (logits)\n", + " self.layer4 = nn.Linear(hidden_dim, output_dim)\n", + "\n", + " # ReLU activation for non-linearity\n", + " self.relu = nn.ReLU()\n", + "\n", + " # Defines how input data flows through the network\n", + " def forward(self, x):\n", + " # First hidden layer\n", + " a1 = self.relu(self.layer1(x))\n", + "\n", + " # Second hidden layer\n", + " a2 = self.relu(self.layer2(a1))\n", + "\n", + " # Third hidden layer\n", + " a3 = self.relu(self.layer3(a2))\n", + "\n", + " # Output layer (raw scores / logits)\n", + " output = self.layer4(a3) # we said we'll use softmax, where is it? ¯\\(ツ)/¯\n", + "\n", + " return output" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your training loop here:\n", + "\n", + "def train_one_epoch(model, optimizer, criterion, train_loader, device):\n", + " # Set the model to training mode\n", + " model.train()\n", + "\n", + " running_loss = 0.0\n", + "\n", + " for X_batch, y_batch in train_loader:\n", + " # Move batch to the selected device\n", + " X_batch = X_batch.to(device) # shape: (batch_size, num_features)\n", + " y_batch = y_batch.to(device) # shape: (batch_size,)\n", + "\n", + " # Forward pass (outputs are logits)\n", + " outputs = model(X_batch) # shape: (batch_size, num_classes)\n", + " loss = criterion(outputs, y_batch)\n", + "\n", + " # Backward pass & optimization\n", + " optimizer.zero_grad() # Clear previous gradients\n", + " loss.backward() # Compute gradients\n", + " optimizer.step() # Update model parameters\n", + "\n", + " running_loss += loss.item()\n", + "\n", + " # Average loss over all batches\n", + " avg_loss = running_loss / len(train_loader)\n", + "\n", + " return avg_loss" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your validation loop here:\n", + "\n", + "def validate(model, criterion, test_loader, device):\n", + " # Set the model to evaluation mode\n", + " model.eval()\n", + "\n", + " running_loss = 0.0\n", + " correct = 0\n", + " total = 0\n", + "\n", + " with torch.no_grad():\n", + " for X_batch, y_batch in test_loader:\n", + " # Move data to device\n", + " X_batch = X_batch.to(device) # shape: (batch_size, num_features)\n", + " y_batch = y_batch.to(device) # shape: (batch_size,)\n", + "\n", + " # Forward pass\n", + " outputs = model(X_batch) # shape: (batch_size, num_classes)\n", + " loss = criterion(outputs, y_batch)\n", + " running_loss += loss.item()\n", + "\n", + " # Apply Softmax to get probabilities\n", + " probabilities = F.softmax(outputs, dim=1)\n", + "\n", + " # Pick the classes with highest probabilities\n", + " predicted = torch.argmax(probabilities, dim=1)\n", + "\n", + " # Accuracy calculation\n", + " correct += (predicted == y_batch).sum().item()\n", + " total += y_batch.size(0)\n", + "\n", + " avg_loss = running_loss / len(test_loader)\n", + " accuracy = correct / total\n", + "\n", + " return avg_loss, accuracy" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Define device, model, loss, optimizer:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Start training for 20 epochs:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "import matplotlib.pyplot as plt\n", + "# Plotting results\n", + "plt.figure(figsize=(7, 5))\n", + "\n", + "plt.plot(train_losses, label='Train Loss')\n", + "plt.plot(val_losses, label='Validation Loss')\n", + "plt.title('Loss over Epochs')\n", + "plt.xlabel('Epoch')\n", + "plt.ylabel('Loss')\n", + "plt.legend()\n", + "\n", + "plt.tight_layout()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2 (Bonus): Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/41/Q3.ipynb b/submissions_extracted/41/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..d09684b22467321ece18ef0de8db6488504ac398 --- /dev/null +++ b/submissions_extracted/41/Q3.ipynb @@ -0,0 +1,191 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "import pandas as pd\n", + "# Download latest version\n", + "\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q3-exam-data\")\n", + "\n", + "\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "df = pd.read_csv('Q3_data.csv')" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "df.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "df.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "df.fillna(df.mode())" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "df.duplicated()\n", + "df.drop_duplicates()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "from sklearn.preprocessing import OneHotEncoder\n", + "onehot_encoder = OneHotEncoder(sparse_output=False)\n", + "data_onehot_encoded = onehot_encoder.fit_transform(categories)\n", + "\n", + "print(data_onehot_encoded)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "from sklearn.preprocessing import StandardScaler\n", + "\n", + "\n", + "standard_scaler = StandardScaler()\n", + "data_standard_scaled = standard_scaler.fit_transform(data_for_scale)\n", + "\n", + "print( data_standard_scaled)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "# Task 1: Write your code here:\n", + "from sklearn.model_selection import train_test_split\n", + "\n", + "# Use previously generated random data (example: classification data)\n", + "X, y = X_clf.copy(), y_clf.copy()\n", + "\n", + "# split ratio (80% train, 20% test)\n", + "X_train, X_test, y_train, y_test = train_test_split(\n", + " X, y,\n", + " test_size=0.2,\n", + " random_state=42,\n", + " shuffle=True,\n", + " stratify=y\n", + ")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/410/Q1.ipynb b/submissions_extracted/410/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..1e53a4aa9f61f7e171dba7d61d14ce319adb1a6d --- /dev/null +++ b/submissions_extracted/410/Q1.ipynb @@ -0,0 +1,264 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "from IPython.display import clear_output\n", + "\n", + "%pip install kagglehub catboost lightgbm tqdm -q\n", + "\n", + "clear_output()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import pandas as pd\n", + "import numpy as np\n", + "import matplotlib.pyplot as plt\n", + "import seaborn as sns\n", + "import kagglehub\n", + "import os\n", + "from tqdm import tqdm\n", + "from sklearn.preprocessing import OneHotEncoder\n", + "\n", + "%matplotlib inline" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q1-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "csv_path = os.path.join(path, \"Q1_data.csv\") # joins path with Q1_data.csv taht we found downloaded in our folder\n", + "\n", + "df = pd.read_csv(csv_path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "df.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "df.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "\n", + "def check_target_distribution(df, target_column): # function is reusable .. use when hit is needed\n", + " df[target_column].hist(bins=30, edgecolor='black')\n", + "\n", + " plt.title(f\"Target Distribution ({target_column})\")\n", + " plt.xlabel(target_column)\n", + " plt.ylabel(\"Frequency\")\n", + " plt.grid(False)\n", + "\n", + " plt.show()\n", + "\n", + "check_target_distribution(df, \"Delivery_Time\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "df.drop(columns=['Order_ID'])" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "def check_missing_values(df):\n", + " missing_values = df.isnull().sum()\n", + " print(\"Missing Values per Column:\")\n", + " print(missing_values[missing_values > 0])\n", + " if missing_values.any():\n", + " print(\"\\nHandle Missing Values as needed.\")\n", + " else:\n", + " print(\"\\nNo Missing Values Found.\")\n", + "\n", + "check_missing_values(df)\n", + "\n", + "#handling, filling target column and dropping rows where target (delivery time) or key features are missing\n", + "\n", + "cols = ['Distance_km', 'Weather', 'Traffic_Level', 'Time_of_Day', 'Vehicle_Type', 'Preparation_Time_min', 'Courier_Experience_yrs', 'Delivery_Time']\n", + "df_clean = df[cols].copy()\n", + "print(f\"Before: {df[cols].shape}\")\n", + "cols = df_clean.dropna(subset=['Weather', 'Traffic_Level', 'Time_of_Day', 'Courier_Experience_yrs'])\n", + "print(f\"After dropping missing Weather, Traffic_Level, Time_of_Day, Courier_Experience_yrs: {df[cols].shape}\")\n", + "\n", + "cols['Delivery_Time'] = cols['Delivery_Time'].fillna(cols['Delivery_Time'].mode()[0])\n", + "\n", + "\n", + "print(\"Missing values remaining:\", cols.isnull().sum())" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "def check_duplicates(df):\n", + " duplicates = df.duplicated().sum()\n", + " print(f\"Number of Duplicate Samples: {duplicates}\")\n", + " if duplicates > 0:\n", + " print(\"Dropping Duplicates...\")\n", + " df.drop_duplicates(inplace=True) # changes in original data\n", + " print(\"Duplicates Dropped.\")\n", + " else:\n", + " print(\"No Duplicate Samples Found.\")\n", + "\n", + "check_duplicates(df)\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "categorical_cols = df.select_dtypes(include=[\"object\"]).columns\n", + "\n", + "print(\"Categorical Columns:\", list(categorical_cols))\n", + "\n", + "ohe = OneHotEncoder(sparse_output=False)\n", + "encoded = ohe.fit_transform(df[categorical_cols])\n", + "\n", + "print('\\nData after encoding:\\n', encoded)\n", + "\n", + "print(df['Weather'].dtype)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "from sklearn.preprocessing import StandardScaler\n", + "\n", + "features = df.columns.drop(\"Delivery_Time\")\n", + "scaler = StandardScaler()\n", + "df[features] = scaler.fit_transform(df[features])\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 6: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/410/Q2.ipynb b/submissions_extracted/410/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..9fa11d93f7fc8e22ef7c3810e08b241b3dc667c4 --- /dev/null +++ b/submissions_extracted/410/Q2.ipynb @@ -0,0 +1,481 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import torch\n", + "import torch.nn as nn\n", + "from torchvision.datasets import MNIST\n", + "from torch.utils.data import DataLoader\n", + "from torch.optim import Adam, AdamW\n", + "import torch.optim as optim\n", + "from torchvision.transforms.functional import to_tensor\n", + "import torch.nn.functional as F\n", + "import matplotlib.pyplot as plt\n", + "import numpy as np\n", + "import pandas as pd\n", + "import matplotlib.pyplot as plt\n", + "import seaborn as sns\n", + "import warnings\n", + "warnings.filterwarnings('ignore')\n", + "\n", + "# Scikit-Learn: Data Preprocessing\n", + "from sklearn.model_selection import train_test_split, KFold, StratifiedKFold, cross_val_score\n", + "from sklearn.preprocessing import StandardScaler, MinMaxScaler, LabelEncoder, OneHotEncoder\n", + "\n", + "# Scikit-Learn: Regression Models\n", + "from sklearn.linear_model import LinearRegression, Ridge, Lasso\n", + "from sklearn.tree import DecisionTreeRegressor\n", + "from sklearn.ensemble import RandomForestRegressor\n", + "from sklearn.svm import SVR\n", + "\n", + "# Scikit-Learn: Classification Models\n", + "from sklearn.linear_model import LogisticRegression\n", + "from sklearn.neighbors import KNeighborsClassifier\n", + "from sklearn.tree import DecisionTreeClassifier\n", + "from sklearn.ensemble import RandomForestClassifier\n", + "from sklearn.svm import SVC\n", + "\n", + "# Scikit-Learn: Metrics\n", + "from sklearn.metrics import (\n", + " mean_absolute_error, mean_squared_error, r2_score,\n", + " accuracy_score, precision_score, recall_score, f1_score,\n", + " confusion_matrix, classification_report\n", + ")\n", + "\n", + "# Scikit-Learn: Unsupervised\n", + "from sklearn.decomposition import PCA\n", + "from sklearn.manifold import TSNE\n", + "from sklearn.cluster import KMeans\n", + "\n", + "# PyTorch Core\n", + "import torch\n", + "import torch.nn as nn\n", + "import torch.nn.functional as F\n", + "from torch.optim import Adam, AdamW, SGD\n", + "from torch.utils.data import DataLoader, TensorDataset\n", + "\n", + "# PyTorch Vision (for image problems)\n", + "from torchvision.datasets import MNIST\n", + "from torchvision.transforms import ToTensor, Compose, Normalize\n", + "from torchvision.transforms.functional import to_tensor\n", + "\n", + "# Set random seeds for reproducibility\n", + "np.random.seed(42)\n", + "torch.manual_seed(42)\n", + "\n", + "# Check device\n", + "device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\n", + "print(f\"Using device: {device}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q2-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import os\n", + "import pandas as pd\n", + "import numpy as np\n", + "from PIL import Image\n", + "from sklearn.model_selection import train_test_split\n", + "\n", + "# Load Labels\n", + "labels_df = pd.read_csv(os.path.join(path, \"labels.csv\"))\n", + "img_dir = os.path.join(path, \"images\")\n", + "\n", + "images = []\n", + "ages = []\n", + "\n", + "# Load Images and Resize\n", + "print(\"Loading images...\")\n", + "for index, row in labels_df.iterrows():\n", + " img_name = row.iloc[0]\n", + " age = row.iloc[1]\n", + " img_path = os.path.join(img_dir, img_name)\n", + "\n", + " if os.path.exists(img_path):\n", + " img = Image.open(img_path).convert('RGB')\n", + " img_array = np.array(img) / 255.0 # Normalize pixel values to [0, 1]\n", + " images.append(img_array)\n", + " ages.append(age)\n", + "\n", + "X = np.array(images)\n", + "y = np.array(ages)\n", + "\n", + "# Transpose image dimensions to match PyTorch format (N, C, H, W)\n", + "X = np.transpose(X, (0, 3, 1, 2))\n", + "\n", + "# Split Data\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n", + "\n", + "print(f\"X_train shape: {X_train.shape}\")\n", + "print(f\"X_test shape: {X_test.shape}\")\n", + "print(f\"y_train shape: {y_train.shape}\")\n", + "print(f\"y_test shape: {y_test.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 1. Convert Numpy arrays to PyTorch Tensors\n", + "\n", + "X_train = torch.tensor(X_train, dtype=torch.float32)\n", + "X_test = torch.tensor(X_test, dtype=torch.float32)\n", + "y_train = torch.tensor(y_train, dtype=torch.float32)\n", + "y_test = torch.tensor(y_test, dtype=torch.float32)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 2. Create TensorDataset objects\n", + "\n", + "# TensorDataset pairs input features (X) with their corresponding labels (y)\n", + "\n", + "train_dataset = TensorDataset(X_train, y_train)\n", + "test_dataset = TensorDataset(X_test, y_test)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 3. Create DataLoaders\n", + "\n", + "from torch.utils.data import DataLoader\n", + "\n", + "# DataLoader for training data\n", + "train_loader = DataLoader(\n", + " train_dataset,\n", + " batch_size=32,\n", + " shuffle=True,\n", + " num_workers=2\n", + ")\n", + "# DataLoader for test/validation data\n", + "test_loader = DataLoader(\n", + " test_dataset,\n", + " batch_size=32,\n", + " shuffle=False,\n", + " num_workers=2\n", + ")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 4. Print shape of one batch\n", + "\n", + "# Get the first batch from the training DataLoader\n", + "X_batch, y_batch = next(iter(train_loader))\n", + "print(f\"Training batch input shape: {X_batch.shape}\")\n", + "print(f\"Training batch labels shape: {y_batch.shape}\")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Get one batch of images and labels\n", + "images, labels = next(iter(train_loader))\n", + "\n", + "# Display the first 6 images in the batch\n", + "plt.figure(figsize=(8, 4))\n", + "\n", + "for i in range(6):\n", + " plt.subplot(2, 3, i + 1)\n", + "\n", + " # Convert from (C, H, W) to (H, W, C) for matplotlib\n", + " img = images[i].permute(1, 2, 0)\n", + "\n", + " plt.imshow(img)\n", + " plt.title(f\"Label: {labels[i].item()}\")\n", + " plt.axis('off')\n", + "\n", + "plt.tight_layout()\n", + "plt.show()\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "class NN4Layer(nn.Module):\n", + "\n", + " def __init__(self, input_dim, hidden_dim, output_dim):\n", + " super(NN4Layer, self).__init__()\n", + "\n", + " # First linear layer: input features -> hidden layer\n", + " self.layer1 = nn.Linear(input_dim, hidden_dim)\n", + "\n", + " # Second linear layer: hidden layer -> hidden layer\n", + " self.layer2 = nn.Linear(hidden_dim, hidden_dim)\n", + "\n", + " # Output layer: hidden layer -> number of classes (logits)\n", + " self.layer3 = nn.Linear(hidden_dim, hidden_dim)\n", + "\n", + " self.layer4 = nn.Linear(hidden_dim, output_dim)\n", + "\n", + " # ReLU activation for non-linearity\n", + " self.relu = nn.ReLU()\n", + "\n", + " # Defines how input data flows through the network\n", + " def forward(self, x):\n", + " # First hidden layer\n", + " z1 = self.layer1(x)\n", + " a1 = self.relu(z1)\n", + "\n", + " # Second hidden layer\n", + " z2 = self.layer2(a1)\n", + " a2 = self.relu(z2)\n", + "\n", + " #3rd hidden layer\n", + " z3= self.layer3(a2)\n", + " a3= self.relu(z3)\n", + "\n", + " # Output layer (raw scores / logits)\n", + " output = self.layer4(a2)\n", + "\n", + " return output\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "def train_one_epoch(model, optimizer, criterion, train_loader, device):\n", + " # Set the model to training mode\n", + " model.train()\n", + "\n", + " running_loss = 0.0\n", + "\n", + " for X_batch, y_batch in train_loader:\n", + " # Move batch to the selected device\n", + " X_batch = X_batch.view(X_batch.size(0), -1).to(device) # flatten image to a vector\n", + " y_batch = y_batch.to(device)\n", + "\n", + " # Forward pass\n", + " outputs = model(X_batch) # shape: (batch_size, 10)\n", + " loss = criterion(outputs, y_batch)\n", + "\n", + " # Backward pass & optimization\n", + " optimizer.zero_grad() # Clear previous gradients\n", + " loss.backward() # Compute gradients\n", + " optimizer.step() # Update model parameters\n", + "\n", + " running_loss += loss.item()\n", + "\n", + " # Average loss over all batches\n", + " avg_loss = running_loss / len(train_loader)\n", + "\n", + " return avg_loss" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "def validate(model, criterion, test_loader, device):\n", + " # Set the model to evaluation mode\n", + " model.eval()\n", + "\n", + " running_loss = 0.0\n", + " correct = 0\n", + " total = 0\n", + "\n", + " with torch.no_grad():\n", + " for X_batch, y_batch in test_loader:\n", + " # Move data to device\n", + " X_batch = X_batch.view(X_batch.size(0), -1).to(device)\n", + " y_batch = y_batch.to(device)\n", + "\n", + " # Forward pass\n", + " outputs = model(X_batch) # shape: (batch_size, 10)\n", + " loss = criterion(outputs, y_batch)\n", + " running_loss += loss.item()\n", + "\n", + " # Apply Softmax to get probabilities\n", + " probabilities = F.softmax(outputs, dim=1)\n", + " # 0 1. 2. 3 4 5. 6. 7. 8. 9\n", + " # [0.2,0.01,0.1,0.3,0.02,0.7, 0.02 ,0.0 , 0.0 , 0.0 ]\n", + "\n", + " # Multiclass predictions\n", + " predicted = torch.argmax(probabilities, dim=1)\n", + "\n", + " # Accuracy calculation\n", + " correct += (predicted == y_batch).sum().item()\n", + " total += y_batch.size(0)\n", + "\n", + " avg_loss = running_loss / len(test_loader)\n", + " accuracy = correct / total\n", + "\n", + " return avg_loss, accuracy\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Device setup\n", + "device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n", + "\n", + "# Model parameters\n", + "# TODO: What are input features ? (hint: flatten using channel, height, width)\n", + "\n", + "input_dim = 3*36*36\n", + "\n", + "# TODO: choose number of hidden neurons\n", + "hidden_dim = 5\n", + "\n", + "# TODO: what are the number of classes ?\n", + "output_dim = 6\n", + "\n", + "model = NN4Layer(input_dim, hidden_dim, output_dim).to(device)\n", + "\n", + "# Print the model architecture\n", + "print(\"Model Architecture:\\n\")\n", + "print(model)\n", + "\n", + "num_epochs = 20\n", + "learning_rate = 0.001\n", + "\n", + "# Define criterion (loss function) - using CrossEntropyLoss as model now outputs logits\n", + "criterion = nn.CrossEntropyLoss()\n", + "# Define optimizer\n", + "optimizer = AdamW(model.parameters(), learning_rate, )" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "train_losses = []\n", + "val_losses = []\n", + "val_accuracies = []\n", + "\n", + "print('Starting Training...')\n", + "for epoch in range(num_epochs):\n", + " # Train one epoch\n", + " train_loss = train_one_epoch(model, optimizer, criterion, train_loader, device)\n", + "\n", + " # Validate\n", + " val_loss, val_accuracy = validate(model, criterion, test_loader, device)\n", + "\n", + " train_losses.append(train_loss)\n", + " val_losses.append(val_loss)\n", + " val_accuracies.append(val_accuracy)\n", + "\n", + " print(f'Epoch [{epoch+1}/{num_epochs}], Train Loss: {train_loss:.4f}, Val Loss: {val_loss:.4f}, Val Accuracy: {val_accuracy:.4f}')\n", + "\n", + "print('Training Complete!')" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "plt.figure(figsize=(7, 5))\n", + "\n", + "plt.plot(train_losses, label='Train Loss')\n", + "plt.plot(val_losses, label='Validation Loss')\n", + "plt.title('Loss over Epochs')\n", + "plt.xlabel('Epoch')\n", + "plt.ylabel('Loss')\n", + "plt.legend()\n", + "\n", + "plt.tight_layout()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Set model to evaluation mode\n", + "model.eval()\n", + "# Get one batch from the test DataLoader\n", + "images, labels = next(iter(test_loader))\n", + "# Move images to device\n", + "images = images.to(device)\n", + "labels = labels.to(device)\n", + "\n", + "with torch.no_grad():\n", + " # Flatten images before passing to the model\n", + " outputs = model(images.view(images.size(0), -1))\n", + " predictions = torch.argmax(outputs, dim=1)\n", + "\n", + "# Move tensors back to CPU for plotting\n", + "images = images.cpu()\n", + "labels = labels.cpu()\n", + "predictions = predictions.cpu()\n", + "\n", + "# Plot first 6 predictions\n", + "plt.figure(figsize=(8, 4))\n", + "for i in range(6):\n", + " plt.subplot(2, 3, i + 1)\n", + " plt.imshow(images[i].squeeze(), cmap='gray')\n", + " plt.title(f\"True: {labels[i]} | Pred: {predictions[i]}\")\n", + " plt.axis('off')\n", + "\n", + "plt.tight_layout()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/410/Q3.ipynb b/submissions_extracted/410/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..cba0a7c0d64e2246af80e62b2fb1e7eabf69af49 --- /dev/null +++ b/submissions_extracted/410/Q3.ipynb @@ -0,0 +1,272 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import torch\n", + "import torch.nn as nn\n", + "from torchvision.datasets import MNIST\n", + "from torch.utils.data import DataLoader\n", + "from torch.optim import Adam, AdamW\n", + "import torch.optim as optim\n", + "from torchvision.transforms.functional import to_tensor\n", + "import torch.nn.functional as F\n", + "import matplotlib.pyplot as plt\n", + "import numpy as np\n", + "import pandas as pd\n", + "import matplotlib.pyplot as plt\n", + "import seaborn as sns\n", + "import warnings\n", + "warnings.filterwarnings('ignore')\n", + "\n", + "\n", + "# Scikit-Learn: Data Preprocessing\n", + "from sklearn.model_selection import train_test_split, KFold, StratifiedKFold, cross_val_score\n", + "from sklearn.preprocessing import StandardScaler, MinMaxScaler, LabelEncoder, OneHotEncoder\n", + "\n", + "# Scikit-Learn: Regression Models\n", + "from sklearn.linear_model import LinearRegression, Ridge, Lasso\n", + "from sklearn.tree import DecisionTreeRegressor\n", + "from sklearn.ensemble import RandomForestRegressor\n", + "from sklearn.svm import SVR\n", + "\n", + "# Scikit-Learn: Classification Models\n", + "from sklearn.linear_model import LogisticRegression\n", + "from sklearn.neighbors import KNeighborsClassifier\n", + "from sklearn.tree import DecisionTreeClassifier\n", + "from sklearn.ensemble import RandomForestClassifier\n", + "from sklearn.svm import SVC\n", + "\n", + "# Scikit-Learn: Metrics\n", + "from sklearn.metrics import (\n", + " mean_absolute_error, mean_squared_error, r2_score,\n", + " accuracy_score, precision_score, recall_score, f1_score,\n", + " confusion_matrix, classification_report\n", + ")\n", + "\n", + "# Scikit-Learn: Unsupervised\n", + "from sklearn.decomposition import PCA\n", + "from sklearn.manifold import TSNE\n", + "from sklearn.cluster import KMeans\n", + "\n", + "# PyTorch Core\n", + "import torch\n", + "import torch.nn as nn\n", + "import torch.nn.functional as F\n", + "from torch.optim import Adam, AdamW, SGD\n", + "from torch.utils.data import DataLoader, TensorDataset\n", + "\n", + "# PyTorch Vision (for image problems)\n", + "from torchvision.datasets import MNIST\n", + "from torchvision.transforms import ToTensor, Compose, Normalize\n", + "from torchvision.transforms.functional import to_tensor\n", + "\n", + "# Set random seeds for reproducibility\n", + "np.random.seed(42)\n", + "torch.manual_seed(42)\n", + "\n", + "# Check device\n", + "device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\n", + "print(f\"Using device: {device}\")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import pandas as pd\n", + "import numpy as np\n", + "import matplotlib.pyplot as plt\n", + "import seaborn as sns\n", + "import kagglehub\n", + "import os\n", + "from tqdm import tqdm\n", + "from sklearn.preprocessing import OneHotEncoder\n", + "\n", + "%matplotlib inline" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "\n", + "\n", + "# Download latest version\n", + "\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q3-exam-data\")\n", + "\n", + "\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "csv_path = os.path.join(path, \"Q3_data.csv\")\n", + "\n", + "df = pd.read_csv(csv_path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "df.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "df.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "def check_missing_values(df):\n", + " missing_values = df.isnull().sum()\n", + " print(\"Missing Values per Column:\")\n", + " print(missing_values[missing_values > 0])\n", + " if missing_values.any():\n", + " print(\"\\nHandle Missing Values as needed.\")\n", + " else:\n", + " print(\"\\nNo Missing Values Found.\")\n", + "\n", + "check_missing_values(df)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "def check_duplicates(df):\n", + " duplicates = df.duplicated().sum()\n", + " print(f\"Number of Duplicate Samples: {duplicates}\")\n", + " if duplicates > 0:\n", + " print(\"Dropping Duplicates...\")\n", + " df.drop_duplicates(inplace=True) # changes in original data\n", + " print(\"Duplicates Dropped.\")\n", + " else:\n", + " print(\"No Duplicate Samples Found.\")\n", + "\n", + "check_duplicates(df)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/411/Q1.ipynb b/submissions_extracted/411/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..9ae38452b44582637be9b3d66cfde9b551c4e7f0 --- /dev/null +++ b/submissions_extracted/411/Q1.ipynb @@ -0,0 +1,379 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import numpy as np\n", + "import pandas as pd\n", + "import matplotlib.pyplot as plt\n", + "import os\n", + "import kagglehub\n", + "\n", + "from sklearn.model_selection import train_test_split, KFold\n", + "from sklearn.preprocessing import StandardScaler, LabelEncoder\n", + "from sklearn.ensemble import RandomForestRegressor\n", + "from sklearn.metrics import mean_absolute_error, mean_squared_error\n", + "\n", + "import warnings\n", + "warnings.filterwarnings('ignore')\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q1-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "Q1_path = os.path.join(path, 'Q1_data.csv')\n", + "df_q1 = pd.read_csv(Q1_path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "df_q1.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "df_q1.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "df_q1.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "import matplotlib.pyplot as plt\n", + "\n", + "plt.figure()\n", + "plt.hist(df_q1['Delivery_Time'], bins=30)\n", + "plt.xlabel('Delivery Time (minutes)')\n", + "plt.ylabel('Count')\n", + "plt.title('Distribution of Delivery Time')\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "df_q1.drop(columns=['Order_ID'], inplace=True)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "\n", + "missing_percentage = (df_q1.isnull().sum() / len(df_q1)) * 100\n", + "missing_data = pd.DataFrame({\n", + " 'Column': missing_percentage.index,\n", + " 'Missing_Percentage': missing_percentage.values\n", + "})\n", + "missing_data = missing_data[missing_data['Missing_Percentage'] > 0].sort_values('Missing_Percentage', ascending=False)\n", + "\n", + "print(\"Missing Data Analysis:\")\n", + "missing_data.head(10)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "\n", + "# lets fix them\n", + "#since the percentage is small in each of them we will use mean for nummerical\n", + "# mode for categorical since our data is small\n", + "\n", + "df_q1.isnull().sum()\n", + "\n", + "# Numerical columns\n", + "num_cols = df_q1.select_dtypes(include=['int64', 'float64']).columns\n", + "\n", + "# Categorical columns\n", + "cat_cols = df_q1.select_dtypes(include=['object']).columns\n", + "\n", + "# Fill missing numerical values\n", + "for col in num_cols:\n", + " df_q1[col].fillna(df_q1[col].median(), inplace=True)\n", + "\n", + "# Fill missing categorical values\n", + "for col in cat_cols:\n", + " df_q1[col].fillna(df_q1[col].mode()[0], inplace=True)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "#check the duplicates\n", + "df_q1.duplicated().sum()\n", + "print(df_q1.duplicated().sum())\n", + "df_q1.drop_duplicates(inplace=True)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "df_q1 = pd.get_dummies(df_q1, columns=cat_cols, drop_first=True)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "# (actually we have to split before scaling but since it is requred here i will solve it)\n", + "from sklearn.preprocessing import StandardScaler\n", + "\n", + "X = df_q1.drop(columns=['Delivery_Time'])\n", + "y = df_q1['Delivery_Time']\n", + "\n", + "scaler = StandardScaler()\n", + "X_scaled = scaler.fit_transform(X)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 6: Write your code here:\n", + "def check_target_imbalance(df, target_column):\n", + " print(\"Target Distribution:\")\n", + "\n", + " df[target_column].hist() # Yeah you can just do this :)\n", + " plt.show()\n", + "\n", + "check_target_imbalance(df_q1, \"Delivery_Time\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "X = df_q1.drop(columns=['Delivery_Time'])\n", + "y = df_q1['Delivery_Time']" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:\n", + "from sklearn.model_selection import KFold\n", + "from sklearn.ensemble import RandomForestRegressor\n", + "from sklearn.metrics import mean_absolute_error\n", + "import numpy as np\n", + "\n", + "kf = KFold(n_splits=5, shuffle=True, random_state=42)\n", + "\n", + "mae_scores = []\n", + "\n", + "for train_index, val_index in kf.split(X):\n", + " X_train, X_val = X.iloc[train_index], X.iloc[val_index]\n", + " y_train, y_val = y.iloc[train_index], y.iloc[val_index]\n", + "\n", + " model = RandomForestRegressor(\n", + " n_estimators=200,\n", + " random_state=42,\n", + " n_jobs=-1\n", + " )\n", + "\n", + " model.fit(X_train, y_train)\n", + "\n", + " y_pred = model.predict(X_val)\n", + " mae = mean_absolute_error(y_val, y_pred)\n", + " mae_scores.append(mae)\n", + "\n", + "print(f\"Average MAE across folds: {np.mean(mae_scores):.2f} minutes\")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "from sklearn.ensemble import RandomForestRegressor\n", + "\n", + "final_model = RandomForestRegressor(\n", + " n_estimators=200,\n", + " random_state=42,\n", + " n_jobs=-1\n", + ")\n", + "\n", + "final_model.fit(X, y)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "import matplotlib.pyplot as plt\n", + "import pandas as pd\n", + "\n", + "feature_importance = pd.Series(\n", + " final_model.feature_importances_,\n", + " index=X.columns\n", + ").sort_values(ascending=False)\n", + "\n", + "plt.figure(figsize=(10, 6))\n", + "feature_importance.plot(kind='bar')\n", + "plt.xlabel('Features')\n", + "plt.ylabel('Importance')\n", + "plt.title('Feature Importance (Random Forest)')\n", + "plt.tight_layout()\n", + "plt.show()\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "!pip install catboost\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:\n", + "from sklearn.model_selection import KFold\n", + "from sklearn.ensemble import RandomForestRegressor\n", + "from catboost import CatBoostRegressor\n", + "from sklearn.metrics import mean_absolute_error\n", + "import numpy as np\n", + "\n", + "kf = KFold(n_splits=5, shuffle=True, random_state=42)\n", + "mae_scores = []\n", + "\n", + "for train_index, val_index in kf.split(X):\n", + " X_train, X_val = X.iloc[train_index], X.iloc[val_index]\n", + " y_train, y_val = y.iloc[train_index], y.iloc[val_index]\n", + "\n", + " # --- Random Forest ---\n", + " rf_model = RandomForestRegressor(\n", + " n_estimators=200,\n", + " random_state=42,\n", + " n_jobs=-1\n", + " )\n", + " rf_model.fit(X_train, y_train)\n", + "\n", + " # --- CatBoost ---\n", + " cb_model = CatBoostRegressor(\n", + " iterations=500,\n", + " learning_rate=0.1,\n", + " depth=6,\n", + " random_seed=42,\n", + " verbose=0\n", + " )\n", + " cb_model.fit(X_train, y_train)\n", + "\n", + " # --- Average predictions ---\n", + " y_pred_rf = rf_model.predict(X_val)\n", + " y_pred_cb = cb_model.predict(X_val)\n", + "\n", + " y_pred_ensemble = (y_pred_rf + y_pred_cb) / 2\n", + "\n", + " # --- Compute MAE ---\n", + " mae = mean_absolute_error(y_val, y_pred_ensemble)\n", + " mae_scores.append(mae)\n", + "\n", + "\n", + "print(f\"Average MAE across folds (Ensemble): {np.mean(mae_scores):.2f} minutes\")\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/411/Q2.ipynb b/submissions_extracted/411/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..37460a82ab1baaf238ba280eb55dbb795770c4a6 --- /dev/null +++ b/submissions_extracted/411/Q2.ipynb @@ -0,0 +1,370 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "import pandas as pd\n", + "import torch\n", + "import torch.nn as nn\n", + "from torch.optim import AdamW\n", + "import matplotlib.pyplot as plt\n", + "import torch.nn.functional as F\n", + "from torch.utils.data import DataLoader, TensorDataset\n", + "from sklearn.model_selection import train_test_split\n", + "from sklearn.preprocessing import StandardScaler, LabelEncoder" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q2-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import os\n", + "import pandas as pd\n", + "import numpy as np\n", + "from PIL import Image\n", + "from sklearn.model_selection import train_test_split\n", + "\n", + "# Load Labels\n", + "labels_df = pd.read_csv(os.path.join(path, \"labels.csv\"))\n", + "img_dir = os.path.join(path, \"images\")\n", + "\n", + "images = []\n", + "ages = []\n", + "\n", + "# Load Images and Resize\n", + "print(\"Loading images...\")\n", + "for index, row in labels_df.iterrows():\n", + " img_name = row.iloc[0]\n", + " age = row.iloc[1]\n", + " img_path = os.path.join(img_dir, img_name)\n", + "\n", + " if os.path.exists(img_path):\n", + " img = Image.open(img_path).convert('RGB')\n", + " img_array = np.array(img) / 255.0 # Normalize pixel values to [0, 1]\n", + " images.append(img_array)\n", + " ages.append(age)\n", + "\n", + "X = np.array(images)\n", + "y = np.array(ages)\n", + "\n", + "# Transpose image dimensions to match PyTorch format (N, C, H, W)\n", + "X = np.transpose(X, (0, 3, 1, 2))\n", + "\n", + "# Split Data\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n", + "\n", + "print(f\"X_train shape: {X_train.shape}\")\n", + "print(f\"X_test shape: {X_test.shape}\")\n", + "print(f\"y_train shape: {y_train.shape}\")\n", + "print(f\"y_test shape: {y_test.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 1. Convert Numpy arrays to PyTorch Tensors\n", + "import torch\n", + "import torch.nn as nn\n", + "from torch.utils.data import TensorDataset, DataLoader\n", + "import matplotlib.pyplot as plt\n", + "\n", + "X_train_tensor = torch.tensor(X_train).float()\n", + "y_train_tensor = torch.tensor(y_train).float()\n", + "\n", + "X_test_tensor = torch.tensor(X_test).float()\n", + "y_test_tensor = torch.tensor(y_test).float()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 2. Create TensorDataset objects\n", + "train_dataset = TensorDataset(X_train_tensor, y_train_tensor)\n", + "test_dataset = TensorDataset(X_test_tensor, y_test_tensor)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 3. Create DataLoaders\n", + "\n", + "train_loader = DataLoader(train_dataset, batch_size=32, shuffle=True)\n", + "test_loader = DataLoader(test_dataset, batch_size=32, shuffle=False)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 4. Print shape of one batch\n", + "\n", + "print(\"Train dataset:\", len(train_dataset))\n", + "print(\"Test dataset:\", len(test_dataset))\n", + "\n", + "# Get the first batch from the training DataLoader\n", + "X_batch, y_batch = next(iter(train_loader))\n", + "print(f\"Training batch input shape: {X_batch.shape}\")\n", + "print(f\"Training batch labels shape: {y_batch.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 5. Display sample images\n", + "\n", + "fig, axes = plt.subplots(1, 6, figsize=(15, 3))\n", + "# Display the first 6 images in the batch\n", + "plt.figure(figsize=(8, 4))\n", + "\n", + "for i in range(6):\n", + "\n", + " img = images[i].permute(1, 2, 0).numpy()\n", + " label = labels[i].item()\n", + "\n", + " axes[i].imshow(img)\n", + " axes[i].set_title(f\"Age: {label:.1f}\")\n", + " axes[i].axis('off')\n", + "\n", + "plt.show()\n", + "\n", + "\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your model class here:\n", + "\n", + "# Task 1: Write your model class here:\n", + "import torch.optim as optim\n", + "\n", + "class AgeModel(nn.Module):\n", + " def __init__(self):\n", + " super(AgeModel, self).__init__()\n", + " # flatten the input\n", + " self.flatten = nn.Flatten()\n", + "\n", + " # Define 4 Linear Layers\n", + " self.fc1 = nn.Linear(3 * 36 * 36, 512)\n", + " self.fc2 = nn.Linear(512, 256)\n", + " self.fc3 = nn.Linear(256, 64)\n", + " self.fc4 = nn.Linear(64, 1) # Output size is 1 (predicted age)\n", + "\n", + " self.relu = nn.ReLU()\n", + "\n", + " def forward(self, x):\n", + " x = self.flatten(x)\n", + " x = self.relu(self.fc1(x))\n", + " x = self.relu(self.fc2(x))\n", + " x = self.relu(self.fc3(x))\n", + " x = self.fc4(x) # No activation for final layer in regression\n", + " return x\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your training loop here:\n", + "\n", + "def train_step(dataloader, model, loss_fn, optimizer, device):\n", + " model.train() # Set to training mode\n", + " running_loss = 0.0\n", + "\n", + " for X, y in dataloader:\n", + " X, y = X.to(device), y.to(device)\n", + "\n", + " # we want te shape to be (batch_size, 1)\n", + " y = y.unsqueeze(1)\n", + "\n", + " # forward pass\n", + " pred = model(X)\n", + " loss = loss_fn(pred, y)\n", + "\n", + " # backpropagation\n", + " optimizer.zero_grad()\n", + " loss.backward()\n", + " optimizer.step()\n", + "\n", + " running_loss += loss.item()\n", + "\n", + "\n", + " return running_loss / len(dataloader)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your validation loop here:\n", + "def val_step(dataloader, model, loss_fn, device):\n", + " model.eval()\n", + " val_loss = 0.0\n", + "\n", + " with torch.no_grad():\n", + " for X, y in dataloader:\n", + " X, y = X.to(device), y.to(device)\n", + " y = y.unsqueeze(1)\n", + "\n", + " pred = model(X)\n", + " loss = loss_fn(pred, y)\n", + " val_loss += loss.item()\n", + "\n", + " return val_loss / len(dataloader)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Define device, model, loss, optimizer:\n", + "device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n", + "print(f\"Using device: {device}\")\n", + "\n", + "model = AgeModel().to(device)\n", + "\n", + "# MSELoss is standard for regression tasks\n", + "loss_fn = nn.MSELoss()\n", + "\n", + "# Adam is usually a good default optimizer\n", + "optimizer = torch.optim.Adam(model.parameters(), lr=0.001)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Start training for 20 epochs:\n", + "epochs = 20\n", + "train_losses = []\n", + "val_losses = []\n", + "\n", + "print(\"Starting training...\")\n", + "\n", + "for t in range(epochs):\n", + " train_loss = train_step(train_loader, model, loss_fn, optimizer, device)\n", + " val_loss = val_step(test_loader, model, loss_fn, device)\n", + "\n", + " train_losses.append(train_loss)\n", + " val_losses.append(val_loss)\n", + "\n", + " print(f\"Epoch {t+1}/{epochs} | Train Loss: {train_loss:.4f} | Val Loss: {val_loss:.4f}\")\n", + "\n", + "print(\"Training complete.\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "plt.figure(figsize=(10, 5))\n", + "plt.plot(range(1, epochs + 1), train_losses, label='Training Loss')\n", + "plt.plot(range(1, epochs + 1), val_losses, label='Validation Loss', linestyle='--')\n", + "plt.xlabel('Epochs')\n", + "plt.ylabel('Loss (MSE)')\n", + "plt.title('Training and Validation Loss Over Epochs')\n", + "plt.legend()\n", + "plt.grid(True)\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2 (Bonus): Write your code here:\n", + "\n", + "# Set model to evaluation mode\n", + "model.eval()\n", + "# Get one batch from the test DataLoader\n", + "images, labels = next(iter(test_loader))\n", + "# Move images to device\n", + "img = images.to(device)\n", + "label = labels.to(device)\n", + "\n", + "with torch.no_grad():\n", + " # Flatten images before passing to the model\n", + " outputs = model(images.view(images.size(0), -1))\n", + " predictions = torch.argmax(outputs, dim=1)\n", + "\n", + "# Move tensors back to CPU for plotting\n", + "images = images.cpu()\n", + "labels = labels.cpu()\n", + "predictions = predictions.cpu()\n", + "\n", + "# Plot first 6 predictions\n", + "plt.figure(figsize=(8, 4))\n", + "for i in range(6):\n", + " plt.subplot(2, 3, i + 1)\n", + " plt.imshow(images[i].squeeze(), cmap='gray')\n", + " plt.title(f\"True: {labels[i]} | Pred: {predictions[i]}\")\n", + " plt.axis('off')\n", + "\n", + "plt.tight_layout()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/411/Q3.ipynb b/submissions_extracted/411/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..878c3ceabebb5d42a6016bbbfbf579b485aa882c --- /dev/null +++ b/submissions_extracted/411/Q3.ipynb @@ -0,0 +1,324 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import pandas as pd\n", + "import numpy as np\n", + "import matplotlib.pyplot as plt\n", + "import seaborn as sns\n", + "import kagglehub\n", + "import os\n", + "from tqdm import tqdm" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "\n", + "\n", + "# Download latest version\n", + "\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q3-exam-data\")\n", + "\n", + "\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "\n", + "csv_path = os.path.join(path, \"Q3_data.csv\")\n", + "\n", + "df = pd.read_csv(csv_path)\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "df.info()\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "df.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "\n", + "missing_percentage = (df.isnull().sum() / len(df)) * 100\n", + "missing_data = pd.DataFrame({\n", + " 'Column': missing_percentage.index,\n", + " 'Missing_Percentage': missing_percentage.values\n", + "})\n", + "missing_data = missin\n", + "g_data[missing_data['Missing_Percentage'] > 0].sort_values('Missing_Percentage', ascending=False)\n", + "\n", + "print(\"Missing Data Analysis:\")\n", + "missing_data.head(10)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# we have a huge number of missing values we will fill them with \"none\" if categorical and 0 if nummerical\n", + "\n", + "numeric_cols = df.select_dtypes(include=['number']).columns\n", + "df[numeric_cols] = df[numeric_cols].fillna(0)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "duplicates_count = df.duplicated().sum()\n", + "print(f\"Duplicates found: {duplicates_count}\")\n", + "\n", + "if duplicates_count > 0:\n", + " df = df.drop_duplicates()\n", + " print(\"Duplicates removed.\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "from sklearn.preprocessing import LabelEncoder\n", + "categorical_cols = df.select_dtypes(include=['object']).columns\n", + "\n", + "if len(categorical_cols) > 0:\n", + " le = LabelEncoder()\n", + " for col in categorical_cols:\n", + " df[col] = le.fit_transform(df[col].astype(str))\n", + " print(f\"Encoded column: {col}\")\n", + "else:\n", + " print(\"No categorical variables found to encode.\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "from sklearn.preprocessing import StandardScaler\n", + "target_col = \"Target\"\n", + "scaler = StandardScaler()\n", + "\n", + "# we will not scale thhe target\n", + "X = df.drop(columns=[target_col])\n", + "y = df[target_col]\n", + "\n", + "# Scale X and convert back to DataFrame to keep column names\n", + "X_scaled = pd.DataFrame(scaler.fit_transform(X), columns=X.columns)\n", + "\n", + "print(\"Feature scaling applied to X.\")\n", + "print(X_scaled.head(3))" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "class_counts = y.value_counts(normalize=True)\n", + "print(class_counts)\n", + "\n", + "# A common threshold for imbalance is if the minority class is < 20%\n", + "minority_class_ratio = class_counts.min()\n", + "\n", + "if minority_class_ratio < 0.2:\n", + " print(f\">> RESULT: The dataset IS IMBALANCED (Minority class is {minority_class_ratio:.1%})\")\n", + "else:\n", + " print(f\">> RESULT: The dataset is BALANCED (Minority class is {minority_class_ratio:.1%})\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "# we defined x and y before now we will convert them to np array\n", + "X = X_scaled.values\n", + "y = y.values" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "!pip install catboost" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import numpy as np\n", + "from sklearn.model_selection import StratifiedKFold\n", + "from sklearn.metrics import f1_score, accuracy_score\n", + "from catboost import CatBoostClassifier" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:\n", + "skf = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)\n", + "\n", + "# Lists to store scores\n", + "f1_scores = []\n", + "\n", + "print(f\"Starting Cross-Validation with {skf.get_n_splits()} folds...\\n\")\n", + "\n", + "fold = 1\n", + "for train_index, val_index in skf.split(X, y):\n", + "\n", + " X_train_fold, X_val_fold = X[train_index], X[val_index]\n", + " y_train_fold, y_val_fold = y[train_index], y[val_index]\n", + "\n", + "\n", + "\n", + " model = CatBoostClassifier(iterations=500, learning_rate=0.1, depth=6, verbose=0, random_state=42)\n", + "\n", + "\n", + " model.fit(X_train_fold, y_train_fold)\n", + "\n", + " # predict\n", + " y_pred = model.predict(X_val_fold)\n", + "\n", + " # f1\n", + " score = f1_score(y_val_fold, y_pred)\n", + " f1_scores.append(score)\n", + "\n", + " print(f\"Fold {fold} F1 Score: {score:.4f}\")\n", + " fold += 1\n", + "\n", + "# scors\n", + "avg_f1 = np.mean(f1_scores)\n", + "print(\"-\" * 30)\n", + "print(f\"Average F1 Score: {avg_f1:.4f}\")\n", + "print(\"-\" * 30)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "feature_importances = model.get_feature_importance()\n", + "feature_names = X_scaled.columns\n", + "\n", + "\n", + "feat_df = pd.DataFrame({\n", + " 'Feature': feature_names,\n", + " 'Importance': feature_importances\n", + "})\n", + "\n", + "feat_df = feat_df.sort_values(by='Importance', ascending=False)\n", + "\n", + "plt.figure(figsize=(10, 6))\n", + "# top 10 featurs\n", + "top = feat_df.head(10)\n", + "plt.barh(top['Feature'], top['Importance'], color='gold')\n", + "plt.xlabel('Importance Score')\n", + "plt.title('Top 10 Most Important Features')\n", + "plt.gca().invert_yaxis() # Put the #1 feature at the top\n", + "plt.grid(axis='x', linestyle='--', alpha=0.7)\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/412/Q1.ipynb b/submissions_extracted/412/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..163bfd3a7539654e572e02c65c1e46d92d0c97d7 --- /dev/null +++ b/submissions_extracted/412/Q1.ipynb @@ -0,0 +1,326 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "import pandas as pd\n", + "import numpy as np\n", + "import matplotlib.pyplot as plt\n", + "import seaborn as sns\n", + "# import kagglehub\n", + "import os\n", + "from tqdm import tqdm\n", + "import numpy as np\n", + "import pandas as pd\n", + "import matplotlib.pyplot as plt\n", + "import os\n", + "import kagglehub\n", + "\n", + "from sklearn.model_selection import train_test_split, KFold\n", + "from sklearn.preprocessing import StandardScaler, LabelEncoder\n", + "from sklearn.ensemble import RandomForestRegressor\n", + "from sklearn.metrics import mean_absolute_error, mean_squared_error\n", + "\n", + "import warnings\n", + "warnings.filterwarnings('ignore')\n", + "\n", + "\n", + "%matplotlib inline\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q1-exam-data\")\n", + "csv_file_path = os.path.join(path, 'Q1_data.csv')\n", + "print(\"Path to dataset files:\", csv_file_path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "df = pd.read_csv(csv_file_path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "df.head(20)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "df.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "df.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "def check_target_distribution(df, target_column):\n", + " df[target_column].hist(bins=15, edgecolor='black')\n", + "\n", + " plt.title(f\"Target Distribution ({target_column})\")\n", + " plt.xlabel(target_column)\n", + " plt.ylabel(\"Frequency\")\n", + " plt.grid(False)\n", + "\n", + " plt.show()\n", + "\n", + "check_target_distribution(df, \"Delivery_Time\")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "df = df.drop('Order_ID',axis=1)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "def check_missing_values(df):\n", + " missing_values = df.isnull().sum()\n", + " print(\"Missing Values per Column:\")\n", + " print(missing_values[missing_values > 0])\n", + " if missing_values.any():\n", + " print(\"\\nHandle Missing Values as needed.\")\n", + " else:\n", + " print(\"\\nNo Missing Values Found.\")\n", + "\n", + "\n", + "\n", + "check_missing_values(df)\n", + "\n", + "\n", + "df = df.dropna()\n", + "\n", + "\n", + "\n", + "df.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "from pandas.io.formats.style_render import Subset\n", + "# Task 3: Write your code here:\n", + "\n", + "\n", + "# 4. Do we have duplicate samples?\n", + "def check_duplicates(df):\n", + " duplicates = df.duplicated().sum()\n", + " print(f\"Number of Duplicate Samples: {duplicates}\")\n", + " if duplicates > 0:\n", + " print(\"Dropping Duplicates...\")\n", + " df.drop_duplicates(inplace=True)\n", + " print(\"Duplicates Dropped.\")\n", + " else:\n", + " print(\"No Duplicate Samples Found.\")\n", + "\n", + "check_duplicates(df)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "from sklearn.preprocessing import OneHotEncoder,LabelEncoder\n", + "# 3. Do we have categorical columns?\n", + "categorical_cols = df.select_dtypes(include=[\"object\"]).columns\n", + "\n", + "print(\"Categorical Columns:\", list(categorical_cols))\n", + "\n", + "for col in categorical_cols:\n", + " le = LabelEncoder()\n", + " df[col] = le.fit_transform(df[col].astype(str))\n", + "\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "\n", + "features= ['Distance_km','Weather','Traffic_Level','Time_of_Day','Vehicle_Type','Preparation_Time_min','Courier_Experience_yrs']\n", + "X = df[features]\n", + "y = df['Delivery_Time']\n", + "\n", + "# Train-test split (80% train, 20% test)\n", + "# X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n", + "# print(f\"Train: {X_train.shape}, Test: {X_test.shape}\")\n", + "\n", + "scaler = StandardScaler()\n", + "X= scaler.fit_transform(X)\n", + "\n", + "print(x)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 6: Write your code here:\n", + "# 1. Is the target imbalanced?\n", + "def check_target_imbalance(df, target_column):\n", + " print(\"Target Distribution:\")\n", + " print(df[target_column].value_counts(normalize=True))\n", + " sns.countplot(x=df[target_column])\n", + " plt.title(\"Target Distribution\")\n", + " plt.show()\n", + "\n", + "check_target_imbalance(df, \"Delivery_Time\")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:\n", + "model = RandomForestRegressor(n_estimators=100, max_depth=20, random_state=42, n_jobs=-1)\n", + "model.fit(X_train, y_train)\n", + "print(\"Model trained!\")\n", + "\n", + "kfold = KFold(n_splits=5, shuffle=True, random_state=42)\n", + "\n", + "mae_scores = []\n", + "rmse_scores = []\n", + "\n", + "for train_idx, val_idx in kfold.split(X_train):\n", + " X_fold_train, X_fold_val = X_train[train_idx], X_train[val_idx]\n", + " y_fold_train, y_fold_val = y_train.iloc[train_idx], y_train.iloc[val_idx]\n", + "\n", + " # Train and predict\n", + " model.fit(X_fold_train, y_fold_train)\n", + " y_fold_pred = model.predict(X_fold_val)\n", + "\n", + " # Calculate metrics\n", + " mae_scores.append(mean_absolute_error(y_fold_val, y_fold_pred))\n", + "\n", + "mae_scores = np.array(mae_scores)\n", + "\n", + "print(f\"5-Fold CV Results:\")\n", + "print(f\"MAE: {mae_scores.mean():,.2f}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "# Feature importance\n", + "feature_importance = pd.DataFrame({\n", + " 'feature': features,\n", + " 'importance': model.feature_importances_\n", + "}).sort_values('importance', ascending=False)\n", + "\n", + "plt.figure(figsize=(10, 6))\n", + "plt.barh(feature_importance['feature'], feature_importance['importance'])\n", + "plt.xlabel('Importance')\n", + "plt.title('Feature Importance')\n", + "plt.gca().invert_yaxis()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "def check_target_distribution(df, target_column):\n", + " df[target_column].hist(bins=15, edgecolor='black')\n", + "\n", + " plt.title(f\"Target Distribution ({target_column})\")\n", + " plt.xlabel(target_column)\n", + " plt.ylabel(\"Frequency\")\n", + " plt.grid(False)\n", + "\n", + " plt.show()\n", + "\n", + "check_target_distribution(df, \"Delivery_Time\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/412/Q3.ipynb b/submissions_extracted/412/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..550a3b84c5fbbf6eb76d2865ccc80fbdec7b3a34 --- /dev/null +++ b/submissions_extracted/412/Q3.ipynb @@ -0,0 +1,473 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "%pip install kagglehub catboost xgboost tqdm imbalanced-learn -q\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "import pandas as pd\n", + "import numpy as np\n", + "import matplotlib.pyplot as plt\n", + "import seaborn as sns\n", + "# import kagglehub\n", + "import os\n", + "from tqdm import tqdm\n", + "import numpy as np\n", + "import pandas as pd\n", + "import matplotlib.pyplot as plt\n", + "import os\n", + "import kagglehub\n", + "\n", + "from sklearn.model_selection import train_test_split, KFold\n", + "from sklearn.preprocessing import StandardScaler, LabelEncoder\n", + "from sklearn.ensemble import RandomForestRegressor\n", + "from sklearn.metrics import mean_absolute_error, mean_squared_error\n", + "\n", + "import warnings\n", + "warnings.filterwarnings('ignore')\n", + "\n", + "\n", + "# Download latest version\n", + "\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q3-exam-data\")\n", + "\n", + "csv_file_path = os.path.join(path, 'Q3_data.csv')\n", + "\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "df = pd.read_csv(csv_file_path)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "df.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "df.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "def check_missing_values(df):\n", + " missing_values = df.isnull().sum()\n", + " print(\"Missing Values per Column:\")\n", + " print(missing_values[missing_values > 0])\n", + " if missing_values.any():\n", + " print(\"\\nHandle Missing Values as needed.\")\n", + " else:\n", + " print(\"\\nNo Missing Values Found.\")\n", + "\n", + "\n", + "\n", + "check_missing_values(df)\n", + "\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "from pandas.io.formats.style_render import Subset\n", + "\n", + "\n", + "# 4. Do we have duplicate samples?\n", + "def check_duplicates(df):\n", + " duplicates = df.duplicated().sum()\n", + " print(f\"Number of Duplicate Samples: {duplicates}\")\n", + " if duplicates > 0:\n", + " print(\"Dropping Duplicates...\")\n", + " df.drop_duplicates(inplace=True)\n", + " print(\"Duplicates Dropped.\")\n", + " else:\n", + " print(\"No Duplicate Samples Found.\")\n", + "\n", + "check_duplicates(df)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "from sklearn.preprocessing import OneHotEncoder,LabelEncoder\n", + "categorical_cols = df.select_dtypes(include=[\"object\"]).columns\n", + "\n", + "print(\"Categorical Columns:\", list(categorical_cols))\n", + "\n", + "for col in categorical_cols:\n", + " le = LabelEncoder()\n", + " df[col] = le.fit_transform(df[col].astype(str))\n", + "\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "from sklearn.preprocessing import MinMaxScaler\n", + "\n", + "# Pick only the numerical columns, NOT the target\n", + "\n", + "scaler = MinMaxScaler()\n", + "\n", + "# scale the `numerical_cols`\n", + "# df = scaler.fit_transform(df)\n", + "X = df.drop('Target', axis =1 )\n", + "\n", + "X_scaled = scaler.fit_transform(X)\n", + "\n", + "y = df['Target']\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "\n", + "def check_target_imbalance(df, target_column):\n", + " print(\"Target Distribution:\")\n", + "\n", + " df[target_column].hist() # Yeah you can just do this :)\n", + " plt.show()\n", + "check_target_imbalance(df, \"Target\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "X_train, X_test, y_train, y_test = train_test_split(X_scaled, y, test_size=0.2, random_state=42)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:\n", + "# The softmax function\n", + "def softmax(z):\n", + " z_shifted = z - np.max(z, axis=1, keepdims=True)\n", + " exp_z = np.exp(z_shifted)\n", + " return exp_z / np.sum(exp_z, axis=1, keepdims=True)\n", + "\n", + "\n", + "# Categorical cross entropy loss function using NumPy\n", + "def categorical_cross_entropy(y, y_hat):\n", + " epsilon = 1e-15\n", + " y_hat = np.clip(y_hat, epsilon, 1 - epsilon)\n", + "\n", + " loss = -np.mean(np.sum(y * np.log(y_hat), axis=1))\n", + " return loss\n", + "\n", + "def one_hot_encode(y, num_classes):\n", + " y = np.array(y)\n", + " m = len(y)\n", + " # 1. Create a grid of all zeros (num_samples, num_classes)\n", + " one_hot = np.zeros((m, num_classes))\n", + "\n", + " # 2. Go through each sample one by one\n", + " for i in range(m):\n", + " # Identify which class this sample belongs to\n", + " class_label = int(y[i])\n", + "\n", + " # In this row (i), set the specific class column to 1\n", + " one_hot[i, class_label] = 1\n", + "\n", + " return one_hot\n", + "\n", + "from sklearn.model_selection import StratifiedKFold\n", + "from sklearn.metrics import accuracy_score, f1_score" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "def gradient_descent(X, y, num_classes, lr, n_iters=1000):\n", + " # Get the number of samples (m) and number of features (n)\n", + " m, n = X.shape\n", + "\n", + " # Initialize weight matrix with shape (n, num_classes)\n", + " theta = np.zeros((n, num_classes))\n", + "\n", + " # One-hot encode the labels\n", + " y_onehot = one_hot_encode(y, num_classes)\n", + "\n", + " losses = []\n", + "\n", + " for _ in tqdm(range(n_iters), desc=\"Training Multiclass Logistic Regression\"):\n", + " # Calculate the logits z\n", + " z = np.dot(X, theta)\n", + "\n", + " # Get class probabilities using softmax\n", + " y_pred = softmax(z)\n", + "\n", + " # Compute the gradient of Categorical Cross-Entropy with Softmax\n", + " # ∂J/∂θ = (1/m) * X^T * (y_pred - y_onehot)\n", + " gradient = np.dot(X.T, (y_pred - y_onehot)) / m\n", + "\n", + " # Update weights\n", + " theta -= lr * gradient\n", + "\n", + " # Track loss\n", + " loss = categorical_cross_entropy(y_onehot, y_pred)\n", + " losses.append(loss)\n", + "\n", + " return theta, losses" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "n_splits = 3 # K=3 Folds\n", + "\n", + "skf = StratifiedKFold(n_splits=n_splits, shuffle=True, random_state=42)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "\n", + "from sklearn.linear_model import LogisticRegression\n", + "from sklearn.neighbors import KNeighborsClassifier\n", + "from sklearn.svm import SVC\n", + "from sklearn.tree import DecisionTreeClassifier\n", + "from sklearn.ensemble import RandomForestClassifier\n", + "from xgboost import XGBClassifier\n", + "from catboost import CatBoostClassifier\n", + "model = CatBoostClassifier( verbose=0,\n", + " n_estimators=200,\n", + " max_depth=4)\n", + "model.fit(X_train, y_train)\n", + "print(\"Model trained!\")\n", + "\n", + "sr_results = {'loss': [], 'acc': [], 'f1': []}\n", + "\n", + "for fold_idx, (train_index, test_index) in enumerate(skf.split(X, y)):\n", + "\n", + " print(f\"\\nFold {fold_idx + 1}/{n_splits}\")\n", + "\n", + " # Get the train & test split for this fold\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", + " # Train using gradient descent with learning rate = 0.5\n", + " theta, losses = gradient_descent(X_train, y_train, lr=0.5, num_classes=4)\n", + "\n", + " # Calculate z & class probabilities for X_test\n", + " z = np.dot(X_test, theta)\n", + " y_pred_proba = softmax(z)\n", + "\n", + " # Pick the predicted classes with the highest probability\n", + " y_pred = np.argmax(y_pred_proba, axis=1)\n", + "\n", + " # Calculate evaluation metrics\n", + " accuracy = accuracy_score(y_test, y_pred)\n", + " f1 = f1_score(y_test, y_pred, average='macro') # for multiclass f1 score, you should set the average hyperparameter (\"macro\", \"micro\", \"weighted\")\n", + "\n", + " # Store results\n", + " sr_results['loss'].append(losses)\n", + " sr_results['acc'].append(accuracy)\n", + " sr_results['f1'].append(f1)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "sklearn_models = {\n", + " \"CatBoost\": CatBoostClassifier(\n", + " verbose=0,\n", + " n_estimators=200,\n", + " max_depth=4\n", + " )\n", + "}\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "results = {}\n", + "\n", + "for model_name in sklearn_models:\n", + " results[model_name] = {'accuracy': [], 'precision': [], 'recall': [], 'f1': []}\n", + "\n", + "\n", + "for fold_idx, (train_index, test_index) in enumerate(skf.split(X, y)):\n", + " print(f\"\\nFold {fold_idx + 1}/{n_splits}\")\n", + "\n", + " # Get the train & test split for this fold\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", + " # Train & Validate Models\n", + " for model_name, model in sklearn_models.items():\n", + "\n", + " print(f\"Training {model_name}...\")\n", + "\n", + " # Fit the model on train data\n", + " model.fit(X_train, y_train)\n", + "\n", + " # Use the model to predict the test data\n", + " y_pred = model.predict(X_test)\n", + "\n", + " # Calculate evaluation metrics\n", + " accuracy = accuracy_score(y_test, y_pred)\n", + " f1 = f1_score(y_test, y_pred, average='macro') # for multiclass f1 score, you should set the average hyperparameter (\"macro\", \"micro\", \"weighted\")\n", + "\n", + " results[model_name]['accuracy'].append(accuracy)\n", + " results[model_name]['f1'].append(f1)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "for model_name in results:\n", + " print(f\"\\n{model_name}:\")\n", + " # Print the average of each evaluation metric across folds\n", + " print(f\" Avg-Accuracy: {np.mean(results[model_name]['accuracy']):.4f}\")\n", + " print(f\" Avg-F1-Score: {np.mean(results[model_name]['f1']):.4f}\")\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "\n", + "importances = {}\n", + "importances['CatBoost'] = sklearn_models['CatBoost'].feature_importances_\n", + "\n", + "# Create a 1x3 plot\n", + "fig, axes = plt.subplots(1, 3, figsize=(36, 12))\n", + "axes = axes.flatten()\n", + "features = X.columns\n", + "num = 0\n", + "for i, (model_name, imp) in enumerate(importances.items()):\n", + " # Sort features by importance for a cleaner plot\n", + " sorted_idx = np.argsort(imp)\n", + "\n", + " ax = axes[i]\n", + " ax.barh(features[sorted_idx], imp[sorted_idx])\n", + " ax.set_title(f\"{model_name} Feature Importance\")\n", + " ax.set_xlabel(\"Importance Score\")\n", + "\n", + "plt.tight_layout()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "print(f\"The name of the most importance feature is: P_2 \\n {df['P_2']}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/413/Q1.ipynb b/submissions_extracted/413/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..e44c6628bcb1514d9908f6f0d2fc1dfeb399c5cd --- /dev/null +++ b/submissions_extracted/413/Q1.ipynb @@ -0,0 +1,353 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q1-exam-data\")\n", + "paths = os.path.join(path, 'RegFood.csv')\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import numpy as np\n", + "import pandas as pd\n", + "import matplotlib.pyplot as plt\n", + "import os\n", + "import kagglehub\n", + "from sklearn.preprocessing import OneHotEncoder\n", + "import matplotlib.pyplot as plt\n", + "from sklearn.model_selection import train_test_split, StratifiedKFold, cross_val_score,KFold\n", + "from sklearn.preprocessing import StandardScaler, LabelEncoder\n", + "from sklearn.ensemble import RandomForestRegressor\n", + "from lightgbm import LGBMRegressor\n", + "from sklearn.tree import DecisionTreeRegressor\n", + "from sklearn.metrics import classification_report, confusion_matrix, accuracy_score\n", + "from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "\n", + "pokemon_path = os.path.join(path, 'Q1_data.csv')\n", + "df =pd.read_csv(pokemon_path)\n", + "\n", + "print(f\"Shape: {df.shape}\")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "df.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "df.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "\n", + "\n", + "def check_target_distribution(df, target_column):\n", + " df[target_column].hist(bins=30, edgecolor='black')\n", + "\n", + " plt.title(f\"Target Distribution ({target_column})\")\n", + " plt.xlabel(target_column)\n", + " plt.ylabel(\"Frequency\")\n", + " # plt.grid(False)\n", + "\n", + " plt.show()\n", + "\n", + "check_target_distribution(df,'Delivery_Time')" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "df=df.drop(columns='Order_ID')\n", + "df.head(2)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "# 2. Do we have missing values?\n", + "\n", + "#----code for check:----\n", + "# missing_percentage = (df.isnull().sum() / len(df)) * 100\n", + "# missing_data = pd.DataFrame({\n", + "# 'Column': missing_percentage.index,\n", + "# 'Missing_Percentage': missing_percentage.values\n", + "# })\n", + "# missing_data = missing_data[missing_data['Missing_Percentage'] > 0].sort_values('Missing_Percentage', ascending=False)\n", + "\n", + "# print(\"Missing Data Analysis:\")\n", + "# missing_data\n", + "\n", + "#we can drop it cuz is small\n", + "cols=['Delivery_Time','Weather','Traffic_Level','Time_of_Day','Courier_Experience_yrs']\n", + "df=df.dropna(subset=cols)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "missing_percentage = (df.isnull().sum() / len(df)) * 100\n", + "missing_data = pd.DataFrame({\n", + " 'Column': missing_percentage.index,\n", + " 'Missing_Percentage': missing_percentage.values\n", + "})\n", + "missing_data = missing_data[missing_data['Missing_Percentage'] > 0].sort_values('Missing_Percentage', ascending=False)\n", + "\n", + "print(\"Missing Data Analysis:\")\n", + "missing_data" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "def check_duplicates(df):\n", + " duplicates = df.duplicated().sum()\n", + " print(f\"Number of Duplicate Samples: {duplicates}\")\n", + " if duplicates > 0:\n", + " print(\"Dropping Duplicates...\")\n", + " df.drop_duplicates(inplace=True)\n", + " print(\"Duplicates Dropped.\")\n", + " else:\n", + " print(\"No Duplicate Samples Found.\")\n", + "\n", + "check_duplicates(df)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "\n", + "categorical_cols = df.select_dtypes(include=[\"object\"]).columns\n", + "label_encoders = {}\n", + "for col in categorical_cols:\n", + " le = LabelEncoder()\n", + " df[col] = le.fit_transform(df[col])\n", + " label_encoders[col] = le\n", + "df.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "scaler=StandardScaler()\n", + "features = df.columns.drop(\"Delivery_Time\")\n", + "\n", + "df[features] = scaler.fit_transform(df[features])\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 6: Write your code here:\n", + "plt.figure(figsize=(10, 5))\n", + "plt.hist(df['Delivery_Time'].dropna(), bins=50, edgecolor='black')\n", + "plt.title('time Distribution')\n", + "plt.xlabel('time')\n", + "plt.ylabel('Frequency')\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "X = df.drop(\"Delivery_Time\", axis=1).astype(float)\n", + "y = df['Delivery_Time'].astype(float)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:\n", + "from sklearn.metrics import mean_absolute_error\n", + "n_splits = 5 # K=5 Folds\n", + "mae=[]\n", + "model=RandomForestRegressor(n_estimators=200)\n", + "# 5-Fold Cross-Validation, shuffled\n", + "kf = KFold(n_splits=n_splits, shuffle=True, random_state=42)\n", + "\n", + "for fold_idx, (train_index, test_index) in enumerate(kf.split(X)):\n", + " print(f\"\\nFold {fold_idx + 1}/{n_splits}\")\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", + " # Train\n", + " model.fit(X_train, y_train)\n", + "\n", + " # Predict\n", + " y_pred = model.predict(X_test)\n", + " loss=mean_absolute_error(y_test, y_pred)\n", + " # Calculate metrics\n", + " mae.append(loss)\n", + " print(f' MAE for {fold_idx + 1}:{loss}')\n", + "\n", + "print(f\"avg sorec:{np.mean(np.array(mae))}\")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "cof=model.feature_importances_\n", + "i=0\n", + "for feature in features:\n", + " plt.barh(feature, cof[i])\n", + " plt.title(f\"{feature} Coefficients\")\n", + " plt.xlabel(\"Coefficient Value (Impact)\")\n", + " i+=1\n", + "\n", + "plt.tight_layout()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "plt.figure(figsize=(10, 5))\n", + "plt.hist(y_pred, bins=50, edgecolor='black')\n", + "plt.title('Predicted time Distribution')\n", + "plt.xlabel('time')\n", + "plt.ylabel('Frequency')\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:\n", + "models = {\n", + " \"LightGBM\": LGBMRegressor(verbose=-1),\n", + " \"Decision Tree Regressor\": DecisionTreeRegressor(max_depth=10)\n", + "}\n", + "\n", + "kf = KFold(n_splits=5, shuffle=True, random_state=42)\n", + "\n", + "for fold_idx, (train_index, test_index) in enumerate(kf.split(X)):\n", + " print(f\"\\nFold {fold_idx + 1}/{n_splits}\")\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", + " for model_name, model in models.items():\n", + " print(f\"Training {model_name}...\")\n", + "\n", + " # Train\n", + " model.fit(X_train, y_train)\n", + "\n", + " # Predict\n", + " y_pred = model.predict(X_test)\n", + "\n", + "\n", + " # Store results\n", + " loss=mean_absolute_error(y_test, y_pred)\n", + " # Calculate metrics\n", + " mae.append(loss)\n", + " print(f' MAE for {fold_idx + 1}:{loss}')\n", + "\n", + "print(f\"avg sorec:{np.mean(np.array(mae))}\")" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/413/Q2.ipynb b/submissions_extracted/413/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..368d57ef29a34a6f94e8d72466533426ef18e10d --- /dev/null +++ b/submissions_extracted/413/Q2.ipynb @@ -0,0 +1,437 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import torch.nn as nn" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q2-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import os\n", + "import pandas as pd\n", + "import numpy as np\n", + "from PIL import Image\n", + "from sklearn.model_selection import train_test_split\n", + "\n", + "# Load Labels\n", + "labels_df = pd.read_csv(os.path.join(path, \"labels.csv\"))\n", + "img_dir = os.path.join(path, \"images\")\n", + "\n", + "images = []\n", + "ages = []\n", + "\n", + "# Load Images and Resize\n", + "print(\"Loading images...\")\n", + "for index, row in labels_df.iterrows():\n", + " img_name = row.iloc[0]\n", + " age = row.iloc[1]\n", + " img_path = os.path.join(img_dir, img_name)\n", + "\n", + " if os.path.exists(img_path):\n", + " img = Image.open(img_path).convert('RGB')\n", + " img_array = np.array(img) / 255.0 # Normalize pixel values to [0, 1]\n", + " images.append(img_array)\n", + " ages.append(age)\n", + "\n", + "X = np.array(images)\n", + "y = np.array(ages)\n", + "\n", + "# Transpose image dimensions to match PyTorch format (N, C, H, W)\n", + "X = np.transpose(X, (0, 3, 1, 2))\n", + "\n", + "# Split Data\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n", + "\n", + "print(f\"X_train shape: {X_train.shape}\")\n", + "print(f\"X_test shape: {X_test.shape}\")\n", + "print(f\"y_train shape: {y_train.shape}\")\n", + "print(f\"y_test shape: {y_test.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 1. Convert Numpy arrays to PyTorch Tensors\n", + "\n", + "from sklearn.datasets import load_breast_cancer\n", + "from sklearn.model_selection import train_test_split\n", + "from sklearn.preprocessing import StandardScaler\n", + "from torch.utils.data import TensorDataset\n", + "from torch.utils.data import DataLoader\n", + "import torch\n", + "import matplotlib.pyplot as plt\n", + "# transform to tensors\n", + "X_train = torch.tensor(X_train, dtype=torch.float32)\n", + "X_test = torch.tensor(X_test, dtype=torch.float32)\n", + "y_train = torch.tensor(y_train, dtype=torch.float32)\n", + "y_test = torch.tensor(y_test, dtype=torch.float32)\n", + "\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 2. Create TensorDataset objects\n", + "\n", + "# TensorDataset pairs input features (X) with their corresponding labels (y)\n", + "# Each item in the dataset is returned as (X[i], y[i])\n", + "train_dataset = TensorDataset(X_train, y_train)\n", + "test_dataset = TensorDataset(X_test, y_test)\n", + "\n", + "# Access a single sample from the dataset\n", + "# This helps verify the shape of one data sample\n", + "first_sample, _ = train_dataset[0]\n", + "print(f\"Shape of one sample: {first_sample.shape} the label shape is {_.shape}\")\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 3. Create DataLoaders\n", + "\n", + "# Create Dataloaders to train and test data in batches\n", + "train_loader = DataLoader(train_dataset, batch_size=32, shuffle=True)\n", + "test_loader = DataLoader(test_dataset, batch_size=32, shuffle=False)\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 4. Print shape of one batch\n", + "\n", + "# Get the first batch from the training DataLoader\n", + "X_batch, y_batch = next(iter(train_loader))\n", + "print(f\"Training batch input shape: {X_batch.shape}\")\n", + "print(f\"Training batch labels shape: {y_batch.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 5. Display sample images\n", + "# Get one batch of images and labels\n", + "\n", + "images, labels = next(iter(train_loader))\n", + "\n", + "# Display the first 6 images in the batch\n", + "plt.figure(figsize=(8, 4))\n", + "\n", + "for i in range(6):\n", + " plt.subplot(2, 3, i + 1)\n", + "\n", + " # Convert from (C, H, W) to (H, W, C) for matplotlib\n", + " img = images[i].permute(1, 2, 0)\n", + "\n", + " plt.imshow(img)\n", + " plt.title(f\"Label: {labels[i].item()}\")\n", + " plt.axis('off')\n", + "\n", + "plt.tight_layout()\n", + "plt.show()\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your model class here:\n", + "class NN4Layer(nn.Module):\n", + "\n", + " def __init__(self, input_dim, hidden_dim, output_dim):\n", + " super(NN4Layer, self).__init__()\n", + "\n", + " # TODO: What are the dimensions of the first layer? (hint: features? hidden neurons?)\n", + " self.layer1 =nn.Linear(input_dim, hidden_dim) # \n", + "\n", + "\n", + " self.layer2 =nn.Linear(hidden_dim, hidden_dim) # \n", + "\n", + "\n", + " self.layer3 =nn.Linear(hidden_dim, hidden_dim) # \n", + "\n", + "\n", + " self.layer4 =nn.Linear(hidden_dim, output_dim) # \n", + "\n", + "\n", + " # activation function for non-linearity\n", + " self.relu = nn.ReLU()\n", + "\n", + " # Defines how input data flows through the network\n", + " def forward(self, x):\n", + " # Layer 1: TODO\n", + " a1 = self.relu(self.layer1(x))#YOUR CODE HERE)\n", + "\n", + " # Layer 2 TODO\n", + " a2 = self.relu(self.layer2(a1))\n", + "\n", + " # Layer 3 TODO\n", + " a3 = self.relu(self.layer3(a2))\n", + "\n", + " # Layer 4 TODO\n", + " a4 = self.relu(self.layer4(a3))\n", + "\n", + "\n", + " return a4" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your training loop here:\n", + "def train_one_epoch(model, optimizer, criterion, train_loader, device):\n", + " # Set the model to training mode\n", + " model.train()\n", + "\n", + " running_loss = 0.0\n", + "\n", + " for X_batch, y_batch in train_loader:\n", + " # Move batch to the selected device\n", + " X_batch = X_batch.view(X_batch.size(0), -1).to(device)\n", + " y_batch = y_batch.to(device)\n", + "\n", + " # Forward pass\n", + " outputs = model(X_batch) # shape: (batch_size, 10)\n", + " loss = criterion(outputs, y_batch)\n", + "\n", + " # Backward pass & optimization\n", + " optimizer.zero_grad() # Clear previous gradients\n", + " loss.backward() # Compute gradients\n", + " optimizer.step() # Update model parameters\n", + "\n", + " running_loss += loss.item()\n", + "\n", + " # Average loss over all batches\n", + " avg_loss = running_loss / len(train_loader)\n", + "\n", + " return avg_loss" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your validation loop here:\n", + "def validate(model, criterion, test_loader, device):\n", + " # Set the model to evaluation mode\n", + " model.eval()\n", + "\n", + " running_loss = 0.0\n", + " correct = 0\n", + " total = 0\n", + "\n", + " with torch.no_grad():\n", + " for X_batch, y_batch in test_loader:\n", + " # Move data to device\n", + " X_batch = X_batch.view(X_batch.size(0), -1).to(device)\n", + " y_batch = y_batch.to(device)\n", + "\n", + " # Forward pass\n", + " outputs = model(X_batch) # shape: (batch_size, 10)\n", + " loss = criterion(outputs, y_batch)\n", + " running_loss += loss.item()\n", + "\n", + " # Apply Softmax to get probabilities\n", + " probabilities = F.softmax(outputs, dim=1)\n", + "\n", + " # Multiclass predictions\n", + " predicted = torch.argmax(probabilities, dim=1)\n", + "\n", + " # Accuracy calculation\n", + " correct += (predicted == y_batch).sum().item()\n", + " total += y_batch.size(0)\n", + "\n", + " avg_loss = running_loss / len(test_loader)\n", + " accuracy = correct / total\n", + "\n", + " return avg_loss, accuracy" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Define device, model, loss, optimizer:\n", + "# Device setup\n", + "device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n", + "\n", + "# Model parameters\n", + "input_dim =36*36*32*3#img dimntion\n", + "\n", + "# TODO: choose number of hidden neurons\n", + "hidden_dim =64\n", + "\n", + "# TODO: what are the number of classes ?\n", + "output_dim =1 #\n", + "\n", + "# Instantiate model\n", + "model = NN4Layer(input_dim, hidden_dim, output_dim).to(device)\n", + "\n", + "# Print the model architecture\n", + "print(\"Model Architecture:\\n\")\n", + "print(model)\n", + "\n", + "# Calculate the total number of trainable parameters\n", + "total_params = sum(p.numel() for p in model.parameters() if p.requires_grad)\n", + "print(f\"\\nTotal trainable parameters: {total_params}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Start training for 20 epochs:\n", + "from torch.optim import AdamW\n", + "\n", + "model = model.to(device)\n", + "\n", + "# MSE Loss for reconstruction\n", + "criterion = nn.MSELoss()\n", + "\n", + "# Optimizer\n", + "LEARNING_RATE = 0.001\n", + "\n", + "\n", + "NUM_EPOCHS = 10\n", + "# Define criterion (loss function) - using CrossEntropyLoss as model now outputs logits\n", + "criterion = nn.CrossEntropyLoss()\n", + "# Define optimizer\n", + "optimizer = AdamW(model.parameters(), LEARNING_RATE)\n", + "\n", + "\n", + "print('Starting Training...')\n", + "for epoch in range(num_epochs):\n", + " # Train one epoch\n", + " train_loss = train_one_epoch(model, optimizer, criterion, train_loader, device)\n", + "\n", + " # Validate\n", + " val_loss, val_accuracy = validate(model, criterion, test_loader, device)\n", + "\n", + " train_losses.append(train_loss)\n", + " val_losses.append(val_loss)\n", + " val_accuracies.append(val_accuracy)\n", + " print(f'Epoch [{epoch+1}/{num_epochs}], Train Loss: {train_loss:.4f}, Val Loss: {val_loss:.4f}, Val Accuracy: {val_accuracy:.4f}')\n", + "\n", + "print('Training Complete!')" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "# Plotting results\n", + "plt.figure(figsize=(7, 5))\n", + "\n", + "plt.plot(train_losses, label='Train Loss')\n", + "plt.plot(val_losses, label='Validation Loss')\n", + "plt.title('Loss over Epochs')\n", + "plt.xlabel('Epoch')\n", + "plt.ylabel('Loss')\n", + "plt.legend()\n", + "\n", + "plt.tight_layout()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# # Task 2 (Bonus): Write your code here:\n", + "model.eval()\n", + "# Get one batch from the test DataLoader\n", + "images, labels = next(iter(test_loader))\n", + "# Move images to device\n", + "images = images.to(device)\n", + "labels = labels.to(device)\n", + "\n", + "with torch.no_grad():\n", + " # Flatten images before passing to the model\n", + " outputs = model(images.view(images.size(0), -1))\n", + " predictions = torch.argmax(outputs, dim=1)\n", + "\n", + "# Move tensors back to CPU for plotting\n", + "images = images.cpu()\n", + "labels = labels.cpu()\n", + "predictions = predictions.cpu()\n", + "\n", + "# Plot first 6 predictions\n", + "plt.figure(figsize=(8, 4))\n", + "for i in range(6):\n", + " plt.subplot(2, 3, i + 1)\n", + " plt.imshow(images[i].squeeze(), cmap='gray')\n", + " plt.title(f\"True: {labels[i]} | Pred: {predictions[i]}\")\n", + " plt.axis('off')\n", + "\n", + "plt.tight_layout()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/413/Q3.ipynb b/submissions_extracted/413/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..ff7575862533a6c899ce5e6e38698640c610b7c3 --- /dev/null +++ b/submissions_extracted/413/Q3.ipynb @@ -0,0 +1,314 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "\n", + "\n", + "# Download latest version\n", + "\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q3-exam-data\")\n", + "\n", + "\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "import numpy as np\n", + "import pandas as pd\n", + "import matplotlib.pyplot as plt\n", + "import os\n", + "import kagglehub\n", + "from sklearn.preprocessing import OneHotEncoder\n", + "import matplotlib.pyplot as plt\n", + "from sklearn.model_selection import train_test_split, StratifiedKFold, cross_val_score,KFold\n", + "from sklearn.preprocessing import StandardScaler, LabelEncoder\n", + "from sklearn.ensemble import RandomForestRegressor\n", + "from lightgbm import LGBMRegressor\n", + "from sklearn.tree import DecisionTreeRegressor\n", + "from sklearn.metrics import classification_report, confusion_matrix, accuracy_score\n", + "from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score\n", + "\n", + "\n", + "paths = os.path.join(path, 'Q3_data.csv')\n", + "df =pd.read_csv(paths)\n", + "\n", + "print(f\"Shape: {df.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "df.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "df.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "#to see the missing for task1\n", + "missing_percentage = (df.isnull().sum() / len(df)) * 100\n", + "missing_data = pd.DataFrame({\n", + " 'Column': missing_percentage.index,\n", + " 'Missing_Percentage': missing_percentage.values\n", + "})\n", + "missing_data = missing_data[missing_data['Missing_Percentage'] > 0].sort_values('Missing_Percentage', ascending=False)\n", + "\n", + "print(\"Missing Data Analysis:\")\n", + "missing_data" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "\n", + "\n", + "df=df.dropna(subset= df.columns)\n", + "\n", + "missing_percentage = (df.isnull().sum() / len(df)) * 100\n", + "missing_data = pd.DataFrame({\n", + " 'Column': missing_percentage.index,\n", + " 'Missing_Percentage': missing_percentage.values\n", + "})\n", + "missing_data = missing_data[missing_data['Missing_Percentage'] > 0].sort_values('Missing_Percentage', ascending=False)\n", + "\n", + "print(\"Missing Data Analysis:\")\n", + "missing_data" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "def check_duplicates(df):\n", + " duplicates = df.duplicated().sum()\n", + " print(f\"Number of Duplicate Samples: {duplicates}\")\n", + " if duplicates > 0:\n", + " print(\"Dropping Duplicates...\")\n", + " df.drop_duplicates(inplace=True)\n", + " print(\"Duplicates Dropped.\")\n", + " else:\n", + " print(\"No Duplicate Samples Found.\")\n", + "\n", + "check_duplicates(df)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "categorical_cols = df.select_dtypes(include=[\"object\"]).columns\n", + "#No ccategorical columes in the data but if ther we can use the next code if there were on:\n", + "label_encoders = {}\n", + "for col in categorical_cols:\n", + " le = LabelEncoder()\n", + " df[col] = le.fit_transform(df[col])\n", + " label_encoders[col] = le\n", + "df.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "\n", + "categorical_cols = df.select_dtypes(include=[\"object\"]).columns\n", + "label_encoders = {}\n", + "for col in categorical_cols:\n", + " le =StandardScaler()\n", + " df[col] = le.fit_transform(df[col])\n", + " label_encoders[col] = le\n", + "df.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "import seaborn as sns\n", + "def check_target_imbalance(df, target_column):\n", + " print(\"Target Distribution:\")\n", + " print(df[target_column].value_counts(normalize=True))\n", + " sns.countplot(x=df[target_column])\n", + " plt.title(\"Target Distribution\")\n", + " plt.tight_layout()\n", + " plt.show()\n", + "\n", + "check_target_imbalance(df, \"Target\")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "X = df.drop(\"Target\", axis=1).astype(float)# just convert them alwes to flot\n", + "y = df[\"Target\"].astype(float)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "from IPython.display import clear_output\n", + "\n", + "%pip install kagglehub catboost xgboost tqdm -q\n", + "\n", + "clear_output()\n", + "from catboost import CatBoostClassifier" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:\n", + "n_splits = 5 # K=5 Folds\n", + "\n", + "# Stratified 5-Fold Cross-Validation, shuffled\n", + "skf = StratifiedKFold(n_splits=n_splits, shuffle=True, random_state=42)\n", + "model=CatBoostClassifier(#cat boost you have syimtrc tree\n", + " verbose=0,\n", + " n_estimators=320,\n", + " max_depth=4\n", + " )\n", + "acc_loss=[]\n", + "F1_loss=[]\n", + "\n", + "for fold_idx, (train_index, test_index) in enumerate(skf.split(X, y)):\n", + " print(f\"\\nFold {fold_idx + 1}/{n_splits}\")\n", + "\n", + " # 1. Split data\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", + " # 2. Train & Validate sklearn models\n", + " print(f\"Training ...\")\n", + " model.fit(X_train, y_train) # train\n", + " y_pred = model.predict(X_test) # validate\n", + "\n", + " # 3. Save metrics for that model in this fold\n", + " accuracy = accuracy_score(y_test, y_pred)\n", + " f1 = f1_score(y_test, y_pred, zero_division=0)\n", + "\n", + " acc_loss.append(accuracy)\n", + " F1_loss.append(f1)\n", + "\n", + "print(f\"avg sorec:{np.mean(np.array(acc_loss))}\")\n", + "print(f\"avg sorec:{np.mean(np.array(F1_loss))}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "importances={}\n", + "importances['CatBoost'] =model.feature_importances_\n", + "col=df.columns\n", + "for i, (model_name, imp) in enumerate(importances.items()):\n", + " # Sort features by importance for a cleaner plot\n", + " sorted_idx = np.argsort(imp)\n", + "\n", + "\n", + " plt.barh(col[sorted_idx], imp[sorted_idx])\n", + "\n", + "plt.tight_layout()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "model.feature_names_[0:10]\n", + "#this is the first ten importinace feature" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/414/Q1.ipynb b/submissions_extracted/414/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..310296ef908c81e243ad49862341faefc50e2e97 --- /dev/null +++ b/submissions_extracted/414/Q1.ipynb @@ -0,0 +1,289 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "import numpy as np\n", + "import pandas as pd\n", + "import matplotlib.pyplot as plt\n", + "import os\n", + "from sklearn.preprocessing import OneHotEncoder\n", + "from sklearn.model_selection import train_test_split, StratifiedKFold, cross_val_score\n", + "from sklearn.preprocessing import StandardScaler, LabelEncoder\n", + "from sklearn.ensemble import RandomForestClassifier\n", + "from sklearn.metrics import classification_report, confusion_matrix, accuracy_score\n", + "\n", + "import warnings\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q1-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "df_path = os.path.join(path, 'Q1_data.csv')\n", + "df = pd.read_csv(df_path)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "df.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "df.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "plt.figure(figsize=(10, 5))\n", + "plt.hist(df['Delivery_Time'].dropna(), bins=50, edgecolor='black')\n", + "plt.title('Time Distribution')\n", + "plt.xlabel('Delivery_Time')\n", + "plt.ylabel('Frequency')\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "df_clean = df.drop(columns='Order_ID').copy()\n", + "df_clean.tail()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "stat_cols = ['Weather', 'Courier_Experience_yrs', 'Traffic_Level','Time_of_Day','Delivery_Time']\n", + "print(f\"Before: {df_clean.shape}\")\n", + "df_clean = df_clean.dropna(subset=stat_cols).copy()\n", + "print(f\"After dropping missing price/year/odometer: {df_clean.shape}\")\n", + "df_clean.tail()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "duplicate_rows = df_clean.duplicated().sum()\n", + "if duplicate_rows > 0:\n", + " print(f\"Found {duplicate_rows} duplicate rows. Removing them...\")\n", + " df_clean.drop_duplicates(inplace=True)\n", + " print(\"Duplicate rows removed.\")\n", + "else:\n", + " print(\"No duplicate rows found.\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "categorical_cols = df_clean.select_dtypes(include=[\"object\"]).columns\n", + "for col in categorical_cols:\n", + " print(f\"Encoding column: {col}\")\n", + " le = LabelEncoder()\n", + " df_clean[col] = le.fit_transform(df_clean[col])\n", + "df_clean\n", + "#X = df.drop('Delivery_Time', axis=1)\n", + "#y = df['Delivery_Time']\n", + "#cate = [['Weather'], ['Traffic_Level'], ['Time_of_Day'], ['Vehicle_Type']]\n", + "#onehot_encoder = OneHotEncoder(handle_unknown='ignore', sparse_output=False)\n", + "#X_encoded = pd.DataFrame(onehot_encoder.fit_transform(X), columns=onehot_encoder.get_feature_names_out(X.columns))\n", + "#encoder = OneHotEncoder(sparse_output=False)\n", + "#encoded = encoder.fit_transform(cate)\n", + "#X_encoded = pd.DataFrame(encoded.fit_transform(X), columns=encoded.get_feature_names_out(X.columns))\n", + "\n", + "#print(\"Original:\", cate)\n", + "#print(\"Encoded:\\n\", X_encoded)\n", + "#X_encoded.tail()\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "from sklearn.preprocessing import StandardScaler\n", + "\n", + "numerical_cols = df_clean.select_dtypes(include=[\"int64\", \"float64\"]).columns.drop(\"Delivery_Time\") # DON'T SCALE THE TARGET\n", + "\n", + "scaler = StandardScaler()\n", + "df_clean[numerical_cols] = scaler.fit_transform(df_clean[numerical_cols])\n", + "df_clean.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 6: Write your code here:\n", + "import seaborn as sns\n", + "def check_target_imbalance(df, target_column):\n", + " print(\"Target Distribution:\")\n", + " print(df[target_column].value_counts(normalize=True))#it gaves me the ratio of the place and not place #*** normalize gives the percentage and value_count, it count\n", + " sns.countplot(x=df[target_column])\n", + " plt.title(\"Target Distribution\")\n", + " plt.show()\n", + "\n", + "check_target_imbalance(df_clean, \"Delivery_Time\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "X = df_clean.drop(\"Delivery_Time\", axis=1).astype(float)\n", + "y = df_clean['Delivery_Time'].astype(float)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "from sklearn.ensemble import RandomForestRegressor\n", + "from tqdm import tqdm\n", + "from sklearn.model_selection import KFold\n", + "# Task 2,3,4,5: Write your code here:\n", + "n_splits = 5 # K=5 Folds\n", + "\n", + "\n", + "\n", + "# 5-Fold Cross-Validation, shuffled\n", + "kf = KFold(n_splits=n_splits, shuffle=True, random_state=42)\n", + "\n", + "def mean_squared_error(y, y_hat):\n", + " return (1 / (2 * len(y))) * np.sum((y_hat - y) ** 2)\n", + "\n", + "\n", + "def gradient_descent(X, y, learning_rate, n_iters=500):\n", + " m, n = X.shape # m rows, n columns (dimensions)\n", + " theta = np.zeros(n) # initialize a zeros weight vector with n dimensions****\n", + " losses = []\n", + "\n", + " for _ in tqdm(range(n_iters), desc=\"Training Linear Regression\"):\n", + " y_hat = np.dot(X, theta)\n", + " gradient = np.dot(X.T, (y_hat - y)) / m\n", + " theta -= learning_rate * gradient\n", + "\n", + " loss = mean_squared_error(y, y_hat)\n", + " losses.append(loss)\n", + "\n", + " return theta, losses\n", + "\n", + "for fold_idx, (train_index, test_index) in enumerate(skf.split(X)):\n", + " print(f\"\\nFold {fold_idx + 1}/{n_splits}\")\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", + " rf = RandomForestRegressor(n_estimators=100, max_depth=5, random_state=42)\n", + " rf.fit(X_train, y_train)\n", + " print(\"Random Forest R²:\", rf.score(X_test, y_test))\n", + "\n", + " # Train\n", + " theta, losses = gradient_descent(X_train.values, y_train.values, learning_rate=0.1, n_iters=500)\n", + "\n", + " # Validate\n", + " y_pred = np.dot(X_test.values, theta)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/414/Q2.ipynb b/submissions_extracted/414/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..a126f70e94bd4c2470ea47057295afb785aff4b7 --- /dev/null +++ b/submissions_extracted/414/Q2.ipynb @@ -0,0 +1,435 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q2-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import os\n", + "import pandas as pd\n", + "import numpy as np\n", + "from PIL import Image\n", + "from sklearn.model_selection import train_test_split\n", + "\n", + "# Load Labels\n", + "labels_df = pd.read_csv(os.path.join(path, \"labels.csv\"))\n", + "img_dir = os.path.join(path, \"images\")\n", + "\n", + "images = []\n", + "ages = []\n", + "\n", + "# Load Images and Resize\n", + "print(\"Loading images...\")\n", + "for index, row in labels_df.iterrows():\n", + " img_name = row.iloc[0]\n", + " age = row.iloc[1]\n", + " img_path = os.path.join(img_dir, img_name)\n", + "\n", + " if os.path.exists(img_path):\n", + " img = Image.open(img_path).convert('RGB')\n", + " img_array = np.array(img) / 255.0 # Normalize pixel values to [0, 1]\n", + " images.append(img_array)\n", + " ages.append(age)\n", + "\n", + "X = np.array(images)\n", + "y = np.array(ages)\n", + "\n", + "# Transpose image dimensions to match PyTorch format (N, C, H, W)\n", + "X = np.transpose(X, (0, 3, 1, 2))\n", + "\n", + "# Split Data\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n", + "\n", + "print(f\"X_train shape: {X_train.shape}\")\n", + "print(f\"X_test shape: {X_test.shape}\")\n", + "print(f\"y_train shape: {y_train.shape}\")\n", + "print(f\"y_test shape: {y_test.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 1. Convert Numpy arrays to PyTorch Tensors\n", + "import torch\n", + "import torch.nn as nn\n", + "from torchvision.datasets import MNIST\n", + "from torch.utils.data import DataLoader\n", + "from torch.optim import Adam\n", + "from torchvision.transforms.functional import to_tensor\n", + "import torch.nn.functional as F\n", + "import matplotlib.pyplot as plt\n", + "\n", + "X_train = torch.from_numpy(X_train).float()\n", + "X_test = torch.from_numpy(X_test).float()\n", + "y_train = torch.from_numpy(y_train).float()\n", + "y_test = torch.from_numpy(y_test).float().unsqueeze(1)\n", + "\n", + "\n", + "print(f\"X_train tensor shape: {X_train.shape}\")\n", + "\n", + "print(f\"X_test tensor shape: {X_test.shape}\")\n", + "print(f\"y_train tensor shape: {y_train.shape}\")\n", + "print(f\"y_test tensor shape: {y_test.shape}\")\n", + "\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 2. Create TensorDataset objects\n", + "from torch.utils.data import TensorDataset\n", + "\n", + "train_dataset = TensorDataset(X_train, y_train)\n", + "test_dataset = TensorDataset(X_test, y_test)\n", + "\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 3. Create DataLoaders\n", + "batch_size = 32\n", + "train_loader = DataLoader(train_dataset, batch_size=batch_size, shuffle=True)\n", + "test_loader = DataLoader(test_dataset, batch_size=batch_size, shuffle=False)\n", + "\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 4. Print shape of one batch\n", + "for batch_idx, (data, target) in enumerate(train_loader):\n", + " print(f\"Batch {batch_idx + 1} - Data shape: {data.shape}, Target shape: {target.shape}\")\n", + " break\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 5. Display sample images\n", + "def display_images(images, num_images=5):\n", + " fig, axes = plt.subplots(1, num_images, figsize=(15, 3))\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your model class here:\n", + "class NN4Layer(nn.Module):\n", + "\n", + " def __init__(self, input_dim, hidden_dim):\n", + "\n", + " super(NN4Layer, self).__init__()\n", + "\n", + " # input_dim = num of features, hidden_dim = num of neurons\n", + " self.layer1 = nn.Linear(input_dim, hidden_dim)# output of 1st layer = input of 2nd layer\n", + " # hidden_dim = num of neurons, Output for binary classification is 1\n", + " self.layer2 = nn.Linear(hidden_dim, hidden_dim)\n", + "\n", + " self.layer3 = nn.Linear(hidden_dim, hidden_dim)\n", + "\n", + " self.layer4 = nn.Linear(hidden_dim, 1)\n", + "\n", + " self.relu = nn.ReLU()\n", + " self.sigmoid = nn.Sigmoid()\n", + "\n", + "\n", + " def forward(self, x):\n", + " z1 = self.layer1(x)#نمرر الانبوت على اللاير الاول\n", + " a1 = self.relu(z1)#لازم نفس الترتيب ---- layer >> activation function\n", + " z2 = self.layer2(a1)\n", + " a2 = self.relu(z2)\n", + " z3 = self.layer3(a2)\n", + " a3 = self.relu(z3)\n", + " z4 = self.layer4(a3)\n", + " a4 = self.sigmoid(z4)\n", + "\n", + "\n", + "\n", + "\n", + " return a4\n", + "\n", + "\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your training loop here:\n", + "device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n", + "\n", + "def train(model, train_loader, optimizer, criterion):\n", + "\n", + " model.train()\n", + " model.to(device)\n", + "\n", + "\n", + " train_loss = 0.0\n", + "\n", + " for batch_idx, (data, target) in enumerate(train_loader):\n", + "\n", + " optimizer.zero_grad()\n", + "\n", + " output = model(data)\n", + "\n", + "\n", + " loss = criterion(output, target)\n", + " loss.backward()\n", + " optimizer.step()\n", + "\n", + "\n", + " train_loss += loss.item()\n", + "\n", + "\n", + " return train_loss / len(train_loader)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your validation loop here:\n", + "\n", + "def validate(model, criterion, test_loader, device):\n", + " # Set the model to evaluation mode\n", + " model.eval()\n", + "\n", + " running_loss = 0.0\n", + " correct = 0\n", + " total = 0\n", + "\n", + " with torch.no_grad(): # Disable gradient computation\n", + " for X_batch, y_batch in test_loader:\n", + " # Move batch to the selected device\n", + " X_batch = X_batch.to(device)\n", + " y_batch = y_batch.view(-1, 1).to(device)\n", + "\n", + " # Forward pass\n", + " outputs = model(X_batch)\n", + " loss = criterion(outputs, y_batch)\n", + " running_loss += loss.item()# ask him\n", + "\n", + " # Binary predictions\n", + " predicted = (outputs > 0.5).float()\n", + "\n", + " # Accuracy calculation\n", + " correct += (predicted == y_batch).sum().item()\n", + " total += y_batch.size(0)\n", + "\n", + " avg_loss = running_loss / len(test_loader)\n", + " accuracy = correct / total\n", + "\n", + " return avg_loss, accuracy" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Define device, model, loss, optimizer:\n", + "device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n", + "\n", + "input_dim = X_train.shape[1]\n", + "hidden_dim = 128\n", + "model = NN4Layer(input_dim, hidden_dim)\n", + "criterion = nn.MSELoss()\n", + "optimizer = Adam(model.parameters(), lr=0.001)\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import torch\n", + "import torch.nn as nn\n", + "\n", + "# Create a linear layer: 3 input features -> 1 output\n", + "linear = nn.Linear(in_features=3, out_features=1)#***\n", + "\n", + "# Example input: batch of 4 samples, each with 3 features\n", + "x = torch.randn(4, 3)\n", + "\n", + "# Forward through the layer\n", + "y = linear(x)\n", + "\n", + "print(\"Input shape:\", x.shape) # torch.Size([4, 3])\n", + "print(\"Output shape:\", y.shape) # torch.Size([4, 1])\n", + "print(y)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "def train_one_epoch(model, optimizer, criterion, train_loader, device):\n", + " # Set the model to training mode\n", + " model.train()\n", + " model.to(device)\n", + "\n", + " running_loss = 0.0\n", + "\n", + " for X_batch, y_batch in train_loader:\n", + " # Move batch to the selected device\n", + " X_batch = X_batch.to(device)\n", + " y_batch = y_batch.view(-1, 1).to(device)\n", + "\n", + " # Forward pass\n", + " outputs = model(X_batch)#asl him\n", + " loss = criterion(outputs, y_batch)\n", + "\n", + " # Backward pass & optimization\n", + " optimizer.zero_grad() # Clear previous gradients---impo!! forgite previous\n", + " loss.backward() # Compute gradients\n", + " optimizer.step() # Update model parameters\n", + "\n", + " running_loss += loss.item()\n", + "\n", + " # Average loss over all batches\n", + " avg_loss = running_loss / len(train_loader)\n", + "\n", + " return avg_loss" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "num_epochs = 20 #*** proportional to the time\n", + "learning_rate = 0.001\n", + "\n", + "# Model, Criterion, Optimizer\n", + "input_dim = X_train.shape[1]# num of feature or column\n", + "hidden_dim = 10 #neorons\n", + "model =NN4Layer(input_dim, hidden_dim).to(device)\n", + "criterion = nn.BCELoss() #loss function for two class\n", + "optimizer = Adam(model.parameters(), lr=learning_rate)\n", + "\n", + "\n", + "# Run Training\n", + "train_losses = []\n", + "val_losses = []\n", + "val_accuracies = []\n", + "\n", + "print('Starting Training...')\n", + "for epoch in range(num_epochs):\n", + " # Train one epoch\n", + " train_loss = train_one_epoch(model, optimizer, criterion, train_loader, device)\n", + "\n", + " # Validate\n", + " val_loss, val_accuracy = validate(model, criterion, test_loader, device)\n", + "\n", + " train_losses.append(train_loss)\n", + " val_losses.append(val_loss)\n", + " val_accuracies.append(val_accuracy)\n", + "\n", + " if (epoch + 1) % 5 == 0: # every 5 epoch print the result\n", + " print(f'Epoch [{epoch+1}/{num_epochs}], Train Loss: {train_loss:.4f}, Val Loss: {val_loss:.4f}, Val Accuracy: {val_accuracy:.4f}')\n", + "\n", + "print('Training Complete!')" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Start training for 20 epochs:\n", + "num_epochs = 20\n", + "train_losses = []\n", + "val_losses = []\n", + "for epoch in range(num_epochs):\n", + " train_loss = train(model, train_loader, optimizer, criterion)\n", + " val_loss, val_acc = validate(model, criterion, test_loader, device)\n", + " train_losses.append(train_loss)\n", + " val_losses.append(val_loss)\n", + " print(f\"Epoch {epoch + 1}/{num_epochs}, Train Loss: {train_loss:.4f}, Val Loss: {val_loss:.4f}, Val Acc: {val_acc:.4f}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "plt.figure(figsize=(10, 5))\n", + "plt.plot(range(1, num_epochs + 1), train_losses, label='Training Loss')\n", + "plt.plot(range(1, num_epochs + 1), val_losses, label='Validation Loss')" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2 (Bonus): Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/414/Q3.ipynb b/submissions_extracted/414/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..5ce2a6447cbc8db3844fea4bea30eb798b3c3764 --- /dev/null +++ b/submissions_extracted/414/Q3.ipynb @@ -0,0 +1,219 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "\n", + "\n", + "# Download latest version\n", + "\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q3-exam-data\")\n", + "\n", + "\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "import kagglehub\n", + "import numpy as np\n", + "import pandas as pd\n", + "import matplotlib.pyplot as plt\n", + "import os\n", + "from sklearn.preprocessing import OneHotEncoder\n", + "from sklearn.model_selection import train_test_split, StratifiedKFold, cross_val_score\n", + "from sklearn.preprocessing import StandardScaler, LabelEncoder\n", + "from sklearn.ensemble import RandomForestClassifier\n", + "from sklearn.metrics import classification_report, confusion_matrix, accuracy_score\n", + "\n", + "import warnings\n", + "\n", + "df_path = os.path.join(path, 'Q3_data.csv')\n", + "df = pd.read_csv(df_path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "df.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "df.describe()\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "stat_cols = ['D_42', 'D_43', 'D_137','D_138','D_142']\n", + "print(f\"Before: {df.shape}\")\n", + "df_clean = df.dropna(subset=stat_cols).copy()\n", + "print(f\"After dropping missing price/year/odometer: {df.shape}\")\n", + "df_clean.tail()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "duplicate_rows = df_clean.duplicated().sum()\n", + "if duplicate_rows > 0:\n", + " print(f\"Found {duplicate_rows} duplicate rows. Removing them...\")\n", + " df_clean.drop_duplicates(inplace=True)\n", + " print(\"Duplicate rows removed.\")\n", + "else:\n", + " print(\"No duplicate rows found.\")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "categorical_cols = df_clean.select_dtypes(include=[\"object\"]).columns\n", + "for col in categorical_cols:\n", + " print(f\"Encoding column: {col}\")\n", + " le = LabelEncoder()\n", + " df_clean[col] = le.fit_transform(df_clean[col])\n", + "df_clean" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "from sklearn.preprocessing import StandardScaler\n", + "\n", + "numerical_cols = df_clean.select_dtypes(include=[\"int64\", \"float64\"]).columns.drop(\"Target\") # DON'T SCALE THE TARGET\n", + "\n", + "scaler = StandardScaler()\n", + "df_clean[numerical_cols] = scaler.fit_transform(df_clean[numerical_cols])\n", + "df_clean.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "import seaborn as sns\n", + "def check_target_imbalance(df, target_column):\n", + " print(\"Target Distribution:\")\n", + " print(df[target_column].value_counts(normalize=True))#it gaves me the ratio of the place and not place #*** normalize gives the percentage and value_count, it count\n", + " sns.countplot(x=df[target_column])\n", + " plt.title(\"Target Distribution\")\n", + " plt.show()\n", + "\n", + "check_target_imbalance(df_clean, \"Target\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/415/Q1.ipynb b/submissions_extracted/415/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..963a98f13e21715107dbb29fab35bd39caa8bf7d --- /dev/null +++ b/submissions_extracted/415/Q1.ipynb @@ -0,0 +1,351 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "from sklearn.preprocessing import StandardScaler\n", + "import numpy as np\n", + "import pandas as pd\n", + "import matplotlib.pyplot as plt\n", + "from sklearn.model_selection import KFold\n", + "from sklearn.ensemble import RandomForestRegressor\n", + "from sklearn.metrics import mean_absolute_error\n", + "import pandas as pd\n", + "import matplotlib.pyplot as plt\n", + "import seaborn as sns\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q1-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Read the CSV file using pandas\n", + "df = pd.read_csv(f\"{path}/Q1_data.csv\") # Load dataset into DataFrame\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Display the first few rows of the dataset\n", + "df.head()\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Display dataset information\n", + "df.info()\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Show statistical summary of numerical columns\n", + "df.describe()\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Plot the target distribution (Delivery_Time)\n", + "plt.figure(figsize=(8,5))\n", + "sns.histplot(df[\"Delivery_Time\"], kde=True)\n", + "\n", + "plt.title(\"Distribution of Delivery Time\")\n", + "plt.xlabel(\"Delivery Time (minutes)\")\n", + "plt.ylabel(\"Frequency\")\n", + "plt.show()\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Drop Order_ID since it is an identifier and not useful for prediction\n", + "df = df.drop(columns=[\"Order_ID\"])\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Check missing values in each column\n", + "df.isnull().sum()\n", + "# Fill missing values in numerical columns with the mean\n", + "num_cols = df.select_dtypes(include=[\"int64\", \"float64\"]).columns\n", + "\n", + "for col in num_cols:\n", + " df[col] = df[col].fillna(df[col].mean())\n", + "# Fill missing values in categorical columns with the mode\n", + "cat_cols = df.select_dtypes(include=[\"object\"]).columns\n", + "\n", + "for col in cat_cols:\n", + " df[col] = df[col].fillna(df[col].mode()[0])\n", + "df\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 3) Remove duplicates if any exist\n", + "dup_count = df.duplicated().sum()\n", + "print(\"Number of duplicate rows:\", dup_count)\n", + "\n", + "df = df.drop_duplicates()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 4) One-Hot Encode categorical variables\n", + "df = pd.get_dummies(df, drop_first=True)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 5) Feature scaling using StandardScaler\n", + "# Separate features and target\n", + "X = df.drop(columns=[\"Delivery_Time\"])\n", + "y = df[\"Delivery_Time\"]\n", + "\n", + "# Standardize features\n", + "scaler = StandardScaler()\n", + "X_scaled = scaler.fit_transform(X)\n", + "\n", + "print(\" Data is ready!\")\n", + "print(\"X_scaled shape:\", X_scaled.shape)\n", + "print(\"y shape:\", y.shape)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "print(\"Note: Target imbalance is not applicable because Delivery_Time is continuous (regression).\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "\n", + "# 1) Split the dataset into features (X) and target (y)\n", + "X = df.drop(columns=[\"Delivery_Time\"]) # Features\n", + "y = df[\"Delivery_Time\"] # Target (continuous -> regression)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 2) Use the correct split: KFold (for regression)\n", + "kf = KFold(n_splits=5, shuffle=True, random_state=42) # 5-Fold CV with shuffling\n", + "\n", + "mae_scores = [] # Store MAE for each fold\n", + "\n", + "# 3) Train a RandomForest model + 4) Evaluate using MAE only\n", + "for fold, (train_idx, test_idx) in enumerate(kf.split(X), start=1):\n", + " # Split data into train/test for this fold\n", + " X_train, X_test = X.iloc[train_idx], X.iloc[test_idx]\n", + " y_train, y_test = y.iloc[train_idx], y.iloc[test_idx]\n", + "\n", + " # Create the RandomForest regressor model\n", + " model = RandomForestRegressor(\n", + " n_estimators=200, # Number of trees\n", + " random_state=42, # Reproducibility\n", + " n_jobs=-1 # Use all CPU cores\n", + " )\n", + "\n", + " # Train the model\n", + " model.fit(X_train, y_train)\n", + "\n", + " # Predict on the test fold\n", + " y_pred = model.predict(X_test)\n", + "\n", + " # Calculate MAE for this fold\n", + " mae = mean_absolute_error(y_test, y_pred)\n", + " mae_scores.append(mae)\n", + "\n", + " print(f\"Fold {fold} MAE: {mae:.4f}\") # Print fold result\n", + "\n", + "# 5) Print the averaged score across all folds\n", + "avg_mae = np.mean(mae_scores)\n", + "print(\"-\" * 30)\n", + "print(f\"Average MAE across all folds: {avg_mae:.4f}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Get feature importances from the trained RandomForest model\n", + "feature_importance = model.feature_importances_\n", + "\n", + "# Create a DataFrame for better visualization\n", + "importance_df = pd.DataFrame({\n", + " \"Feature\": X.columns,\n", + " \"Importance\": feature_importance\n", + "}).sort_values(by=\"Importance\", ascending=False)\n", + "\n", + "# Plot feature importance\n", + "plt.figure(figsize=(10,6))\n", + "plt.barh(importance_df[\"Feature\"], importance_df[\"Importance\"])\n", + "plt.gca().invert_yaxis() # Most important feature on top\n", + "plt.title(\"Feature Importance from RandomForest Model\")\n", + "plt.xlabel(\"Importance Score\")\n", + "plt.ylabel(\"Features\")\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Predict delivery time using the trained model\n", + "y_pred_all = model.predict(X)\n", + "\n", + "# Plot histogram of predicted delivery times\n", + "plt.figure(figsize=(8,5))\n", + "plt.hist(y_pred_all, bins=30)\n", + "\n", + "plt.title(\"Predicted Delivery Time Distribution\")\n", + "plt.xlabel(\"Predicted Delivery Time (minutes)\")\n", + "plt.ylabel(\"Frequency\")\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "try:\n", + " from catboost import CatBoostRegressor\n", + "except ImportError:\n", + " # If running on Colab, install CatBoost then import again\n", + " !pip -q install catboost\n", + " from catboost import CatBoostRegressor\n", + "\n", + "# 1) Split the dataset into features (X) and target (y)\n", + "X = df.drop(columns=[\"Delivery_Time\"]) # Features\n", + "y = df[\"Delivery_Time\"] # Target (regression)\n", + "\n", + "# 2) Use KFold for regression\n", + "kf = KFold(n_splits=5, shuffle=True, random_state=42)\n", + "\n", + "mae_scores = [] # Store MAE per fold\n", + "\n", + "for fold, (train_idx, test_idx) in enumerate(kf.split(X), start=1):\n", + " # Split data for this fold\n", + " X_train, X_test = X.iloc[train_idx], X.iloc[test_idx]\n", + " y_train, y_test = y.iloc[train_idx], y.iloc[test_idx]\n", + "\n", + " # 3) Model 1: RandomForestRegressor\n", + " rf = RandomForestRegressor(\n", + " n_estimators=300, # Number of trees\n", + " random_state=42,\n", + " n_jobs=-1\n", + " )\n", + "\n", + " # 3) Model 2: CatBoostRegressor (silent training)\n", + " cb = CatBoostRegressor(\n", + " iterations=600, # Number of boosting rounds\n", + " learning_rate=0.05,\n", + " depth=8,\n", + " random_seed=42,\n", + " verbose=0 # No training logs\n", + " )\n", + "\n", + " # Train both models\n", + " rf.fit(X_train, y_train)\n", + " cb.fit(X_train, y_train)\n", + "\n", + " # Predict with both models\n", + " pred_rf = rf.predict(X_test)\n", + " pred_cb = cb.predict(X_test)\n", + "\n", + " # 4) Average predictions (simple ensemble)\n", + " pred_ensemble = (pred_rf + pred_cb) / 2\n", + "\n", + " # 5) Evaluate using MAE only\n", + " mae = mean_absolute_error(y_test, pred_ensemble)\n", + " mae_scores.append(mae)\n", + "\n", + " print(f\"Fold {fold} Ensemble MAE: {mae:.4f}\")\n", + "\n", + "# Print the averaged MAE across all folds\n", + "avg_mae = np.mean(mae_scores)\n", + "print(\"-\" * 30)\n", + "print(f\"Average Ensemble MAE across all folds: {avg_mae:.4f}\")" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/415/Q2.ipynb b/submissions_extracted/415/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..0d8f3f136bfa1243fbd981027f3226841d5e5463 --- /dev/null +++ b/submissions_extracted/415/Q2.ipynb @@ -0,0 +1,382 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "import os\n", + "import pandas as pd\n", + "import numpy as np\n", + "from PIL import Image\n", + "from sklearn.model_selection import train_test_split\n", + "import numpy as np\n", + "import torch\n", + "import torch.nn as nn\n", + "from torch.utils.data import TensorDataset, DataLoader\n", + "import matplotlib.pyplot as plt\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q2-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "\n", + "\n", + "# Load Labels\n", + "labels_df = pd.read_csv(os.path.join(path, \"labels.csv\"))\n", + "img_dir = os.path.join(path, \"images\")\n", + "\n", + "images = []\n", + "ages = []\n", + "\n", + "# Load Images and Resize\n", + "print(\"Loading images...\")\n", + "for index, row in labels_df.iterrows():\n", + " img_name = row.iloc[0]\n", + " age = row.iloc[1]\n", + " img_path = os.path.join(img_dir, img_name)\n", + "\n", + " if os.path.exists(img_path):\n", + " img = Image.open(img_path).convert('RGB')\n", + " img_array = np.array(img) / 255.0 # Normalize pixel values to [0, 1]\n", + " images.append(img_array)\n", + " ages.append(age)\n", + "\n", + "X = np.array(images)\n", + "y = np.array(ages)\n", + "\n", + "# Transpose image dimensions to match PyTorch format (N, C, H, W)\n", + "X = np.transpose(X, (0, 3, 1, 2))\n", + "\n", + "# Split Data\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n", + "\n", + "print(f\"X_train shape: {X_train.shape}\")\n", + "print(f\"X_test shape: {X_test.shape}\")\n", + "print(f\"y_train shape: {y_train.shape}\")\n", + "print(f\"y_test shape: {y_test.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 1. Convert Numpy arrays to PyTorch Tensors\n", + "\n", + "\n", + "# Convert X to float32 tensors\n", + "X_train_t = torch.tensor(X_train, dtype=torch.float32)\n", + "X_test_t = torch.tensor(X_test, dtype=torch.float32)\n", + "\n", + "# Convert y to float32 tensors (regression)\n", + "y_train_t = torch.tensor(y_train, dtype=torch.float32)\n", + "y_test_t = torch.tensor(y_test, dtype=torch.float32)\n", + "\n", + "# If images are in NHWC format (N, H, W, C), convert to NCHW (N, C, H, W)\n", + "if X_train_t.ndim == 4 and X_train_t.shape[-1] in [1, 3]:\n", + " X_train_t = X_train_t.permute(0, 3, 1, 2) # NHWC -> NCHW\n", + " X_test_t = X_test_t.permute(0, 3, 1, 2)\n", + "\n", + "# Ensure y is shape (N, 1) for regression\n", + "if y_train_t.ndim == 1:\n", + " y_train_t = y_train_t.unsqueeze(1)\n", + "if y_test_t.ndim == 1:\n", + " y_test_t = y_test_t.unsqueeze(1)\n", + "\n", + "print(\"X_train_t shape:\", X_train_t.shape)\n", + "print(\"y_train_t shape:\", y_train_t.shape)\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 2. Create TensorDataset objects\n", + "train_dataset = TensorDataset(X_train_t, y_train_t)\n", + "test_dataset = TensorDataset(X_test_t, y_test_t)\n", + "\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 3. Create DataLoaders (batch size = 32)\n", + "train_loader = DataLoader(train_dataset, batch_size=32, shuffle=True)\n", + "test_loader = DataLoader(test_dataset, batch_size=32, shuffle=False)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 4. Print shape of one batch\n", + "images_batch, labels_batch = next(iter(train_loader))\n", + "print(\"One batch images shape:\", images_batch.shape) # (32, C, H, W)\n", + "print(\"One batch labels shape:\", labels_batch.shape) # (32, 1)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "#5) Display a few images using matplotlib\n", + "\n", + "# Display first 6 images from the batch\n", + "plt.figure(figsize=(12, 6))\n", + "\n", + "num_show = 6\n", + "for i in range(num_show):\n", + " img = images_batch[i]\n", + "\n", + " # Convert from (C, H, W) to (H, W, C) for plotting\n", + " img_np = img.permute(1, 2, 0).cpu().numpy()\n", + "\n", + " # If values are normalized or in [0,1], this will still display fine.\n", + " # If your images look dark/strange, you might need to rescale.\n", + " plt.subplot(2, 3, i + 1)\n", + " plt.imshow(img_np.squeeze(), cmap=\"gray\" if img_np.shape[-1] == 1 else None)\n", + " plt.title(f\"Age: {labels_batch[i].item():.1f}\")\n", + " plt.axis(\"off\")\n", + "\n", + "plt.tight_layout()\n", + "plt.show()\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "class AgeRegressionModel(nn.Module):\n", + " def __init__(self, input_dim):\n", + " super(AgeRegressionModel, self).__init__()\n", + "\n", + " # 4 fully connected (linear) layers\n", + " self.fc1 = nn.Linear(input_dim, 512)\n", + " self.fc2 = nn.Linear(512, 256)\n", + " self.fc3 = nn.Linear(256, 64)\n", + " self.fc4 = nn.Linear(64, 1) # Output layer (age prediction)\n", + "\n", + " self.relu = nn.ReLU()\n", + "\n", + " def forward(self, x):\n", + " # Flatten image tensor (B, C, H, W) -> (B, C*H*W)\n", + " x = x.view(x.size(0), -1)\n", + "\n", + " x = self.relu(self.fc1(x))\n", + " x = self.relu(self.fc2(x))\n", + " x = self.relu(self.fc3(x))\n", + " x = self.fc4(x) # No activation (regression)\n", + "\n", + " return x" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your training loop here:\n", + "def train_one_epoch(model, loader, optimizer, criterion, device):\n", + " model.train() # Set model to training mode\n", + " running_loss = 0.0\n", + "\n", + " for images, labels in loader:\n", + " images = images.to(device)\n", + " labels = labels.to(device)\n", + "\n", + " optimizer.zero_grad()\n", + "\n", + " outputs = model(images)\n", + " loss = criterion(outputs, labels)\n", + "\n", + " loss.backward()\n", + " optimizer.step()\n", + "\n", + " running_loss += loss.item()\n", + "\n", + " return running_loss / len(loader)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your validation loop here:\n", + "def validate(model, loader, criterion, device):\n", + " model.eval() # Set model to evaluation mode\n", + " running_loss = 0.0\n", + "\n", + " with torch.no_grad():\n", + " for images, labels in loader:\n", + " images = images.to(device)\n", + " labels = labels.to(device)\n", + "\n", + " outputs = model(images)\n", + " loss = criterion(outputs, labels)\n", + "\n", + " running_loss += loss.item()\n", + "\n", + " return running_loss / len(loader)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Define device, model, loss, optimizer:\n", + "# Device\n", + "device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n", + "print(\"Using device:\", device)\n", + "\n", + "# Get input dimension from one batch\n", + "sample_images, _ = next(iter(train_loader))\n", + "input_dim = sample_images.view(sample_images.size(0), -1).shape[1]\n", + "\n", + "# Model\n", + "model = AgeRegressionModel(input_dim).to(device)\n", + "\n", + "# Loss function (MAE for regression)\n", + "criterion = nn.L1Loss()\n", + "\n", + "# Optimizer\n", + "optimizer = torch.optim.Adam(model.parameters(), lr=1e-4)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Start training for 20 epochs:\n", + "num_epochs = 20\n", + "\n", + "train_losses = []\n", + "val_losses = []\n", + "\n", + "for epoch in range(1, num_epochs + 1):\n", + " train_loss = train_one_epoch(model, train_loader, optimizer, criterion, device)\n", + " val_loss = validate(model, test_loader, criterion, device)\n", + "\n", + " train_losses.append(train_loss)\n", + " val_losses.append(val_loss)\n", + "\n", + " print(f\"Epoch [{epoch}/{num_epochs}] \"\n", + " f\"Train Loss: {train_loss:.4f} | Val Loss: {val_loss:.4f}\")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Plot training and validation loss curves\n", + "plt.figure(figsize=(8,5))\n", + "plt.plot(train_losses, label=\"Train Loss\")\n", + "plt.plot(val_losses, label=\"Validation Loss\")\n", + "\n", + "plt.title(\"Training vs Validation Loss\")\n", + "plt.xlabel(\"Epoch\")\n", + "plt.ylabel(\"Loss (MAE)\")\n", + "plt.legend()\n", + "plt.grid(True)\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "\n", + "\n", + "\n", + "# Get one batch from the test loader\n", + "images, labels = next(iter(test_loader))\n", + "\n", + "# Move images to device for prediction\n", + "images_device = images.to(device)\n", + "\n", + "# Predict (no gradients needed)\n", + "model.eval()\n", + "with torch.no_grad():\n", + " preds = model(images_device).cpu().numpy().squeeze() # shape: (batch,)\n", + "\n", + "# Convert labels to numpy\n", + "labels_np = labels.numpy().squeeze()\n", + "\n", + "# Plot a few examples\n", + "num_show = 6\n", + "plt.figure(figsize=(12, 6))\n", + "\n", + "for i in range(num_show):\n", + " img = images[i] # (C, H, W)\n", + "\n", + " # Convert from (C, H, W) -> (H, W, C) for matplotlib\n", + " img_np = img.permute(1, 2, 0).numpy()\n", + "\n", + " # If image is normalized/looks dark, rescale to [0,1] for display\n", + " img_np = (img_np - img_np.min()) / (img_np.max() - img_np.min() + 1e-8)\n", + "\n", + " plt.subplot(2, 3, i + 1)\n", + " plt.imshow(img_np.squeeze(), cmap=\"gray\" if img_np.shape[-1] == 1 else None)\n", + " plt.title(f\"Pred: {preds[i]:.1f} | Actual: {labels_np[i]:.1f}\")\n", + " plt.axis(\"off\")\n", + "\n", + "plt.tight_layout()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/415/Q3.ipynb b/submissions_extracted/415/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..7031892faad0503e32cc0ad3eefd8e48e7140e7e --- /dev/null +++ b/submissions_extracted/415/Q3.ipynb @@ -0,0 +1,265 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "import pandas as pd\n", + "import numpy as np\n", + "import os\n", + "from sklearn.preprocessing import StandardScaler\n", + "from sklearn.model_selection import StratifiedKFold\n", + "from sklearn.metrics import f1_score\n", + "\n", + "from catboost import CatBoostClassifier\n", + "import matplotlib.pyplot as plt\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "\n", + "# Download latest version\n", + "\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q3-exam-data\")\n", + "\n", + "\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "\n", + "# 1) Read the dataset\n", + "# List files (already confirmed)\n", + "files = os.listdir(path)\n", + "print(\"Files in dataset folder:\", files)\n", + "\n", + "# Read the dataset using the correct path\n", + "csv_path = os.path.join(path, \"Q3_data.csv\")\n", + "df = pd.read_csv(csv_path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 2) Inspect the first few rows\n", + "df.head() # Display the first 5 rows of the dataset\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Dataset info\n", + "df.info()\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "df.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Separate features and target\n", + "target_col = \"Target\"\n", + "X = df.drop(columns=[target_col])\n", + "y = df[target_col]\n", + "\n", + "# Check missing values\n", + "print(\"Missing values before:\", X.isnull().sum().sum())\n", + "\n", + "# Fill missing values using median (robust for anonymized numeric data)\n", + "X = X.fillna(X.median())\n", + "\n", + "print(\"Missing values after:\", X.isnull().sum().sum())\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Check duplicates\n", + "duplicates = X.duplicated().sum()\n", + "print(\"Number of duplicate rows:\", duplicates)\n", + "\n", + "# Remove duplicates if any\n", + "if duplicates > 0:\n", + " X = X.drop_duplicates()\n", + " y = y.loc[X.index]\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Check if categorical variables exist\n", + "cat_cols = X.select_dtypes(include=[\"object\", \"category\"]).columns\n", + "\n", + "if len(cat_cols) == 0:\n", + " print(\"No categorical variables were found so encoding is not required.\")\n", + "else:\n", + " print(\"Categorical columns found:\", list(cat_cols))\n", + " # If needed you could apply encoding here like one-hot encoding)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Apply feature scaling\n", + "scaler = StandardScaler()\n", + "X_scaled = scaler.fit_transform(X)\n", + "\n", + "print(\"Scaled feature shape:\", X_scaled.shape)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Check target\n", + "print(\"Target value counts:\")\n", + "print(y.value_counts())\n", + "\n", + "print(\"\\nTarget distribution (normalized):\")\n", + "print(y.value_counts(normalize=True))" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "target_col = \"Target\"\n", + "X = df.drop(columns=[target_col])\n", + "y = df[target_col]\n", + "scaler = StandardScaler()\n", + "X_scaled = scaler.fit_transform(X)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 2) StratifiedKFold (classification + imbalance)\n", + "skf = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)\n", + "\n", + "scores = []\n", + "\n", + "for fold, (train_idx, test_idx) in enumerate(skf.split(X_scaled, y), start=1):\n", + " X_train, X_test = X_scaled[train_idx], X_scaled[test_idx]\n", + " y_train, y_test = y.iloc[train_idx], y.iloc[test_idx]\n", + "\n", + " # 3) Train CatBoostClassifier\n", + " model = CatBoostClassifier(\n", + " iterations=500,\n", + " learning_rate=0.05,\n", + " depth=6,\n", + " random_seed=42,\n", + " verbose=0\n", + " )\n", + "\n", + " model.fit(X_train, y_train)\n", + "\n", + " # 4) Evaluate using F1 Score ONLY\n", + " y_pred = model.predict(X_test)\n", + " f1 = f1_score(y_test, y_pred)\n", + " scores.append(f1)\n", + "\n", + " print(f\"Fold {fold} F1: {f1:.4f}\")\n", + "\n", + "# 5) Print averaged score\n", + "print(\"-\" * 30)\n", + "print(f\"Average F1 across all folds: {np.mean(scores):.4f}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "importances = model.get_feature_importance()\n", + "\n", + "# Create DataFrame for feature importance\n", + "feat_imp_df = pd.DataFrame({\n", + " \"Feature\": X.columns,\n", + " \"Importance\": importances\n", + "}).sort_values(by=\"Importance\", ascending=False)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Plot top 20 important features\n", + "plt.figure(figsize=(10,6))\n", + "plt.barh(feat_imp_df[\"Feature\"].head(20)[::-1],\n", + " feat_imp_df[\"Importance\"].head(20)[::-1])\n", + "plt.xlabel(\"Importance\")\n", + "plt.ylabel(\"Feature\")\n", + "plt.title(\"Top Feature Importances (CatBoost)\")\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/416/Q1.ipynb b/submissions_extracted/416/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..d86ca07e2b97d2e7c2f6b3db415e9e84bb9572c4 --- /dev/null +++ b/submissions_extracted/416/Q1.ipynb @@ -0,0 +1,368 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q1-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import numpy as np\n", + "import pandas as pd\n", + "import matplotlib.pyplot as plt\n", + "import os\n", + "import kagglehub\n", + "\n", + "from sklearn.model_selection import train_test_split, KFold\n", + "from sklearn.preprocessing import StandardScaler, OneHotEncoder\n", + "from sklearn.ensemble import RandomForestRegressor,\n", + "from sklearn.metrics import mean_absolute_error, mean_squared_error\n", + "\n", + "import warnings\n", + "warnings.filterwarnings('ignore')" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here\n", + "# Load the dataset\n", + "Q1_data = os.path.join(path, 'Q1_data.csv')\n", + "df_data = pd.read_csv(Q1_data)\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "\n", + "df_data.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "df_data.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "df_data.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "# Delivery_Time distribution (target variable)\n", + "plt.figure(figsize=(10, 5))\n", + "plt.hist(df_data['Delivery_Time'].dropna(), bins=50, edgecolor='black')\n", + "plt.title('Delivery_Time Distribution')\n", + "plt.xlabel('Delivery_Time')\n", + "plt.ylabel('Frequency')\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "df_data=df_data.drop(columns=['Order_ID'])\n", + "df_data" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "def check_missing_values(df):\n", + " missing_values = df.isnull().sum()\n", + " print(\"Missing Values per Column:\")\n", + " print(missing_values[missing_values > 0])\n", + " if missing_values.any():\n", + " print(\"\\nHandle Missing Values as needed.\")\n", + " else:\n", + " print(\"\\nNo Missing Values Found.\")\n", + "\n", + "check_missing_values(df_data)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Define object columns\n", + "objcols = ['Weather', 'Traffic_Level', 'Time_of_Day']\n", + "\n", + "# Drop rows with missing object values\n", + "df_clean = df_data.dropna(subset=objcols).copy()\n", + "print(f\"Shape after cleaning: {df_clean.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "df_clean['Courier_Experience_yrs'] = df_clean['Courier_Experience_yrs'].fillna('none')\n", + "df_clean['Delivery_Time'] = df_clean['Delivery_Time'].fillna('none')\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "# Do we have duplicate samples?\n", + "def check_duplicates(df):\n", + " duplicates = df.duplicated().sum()\n", + " print(f\"Number of Duplicate Samples: {duplicates}\")\n", + " if duplicates > 0:\n", + " print(\"Dropping Duplicates...\")\n", + " df.drop_duplicates(inplace=True)\n", + " print(\"Duplicates Dropped.\")\n", + " else:\n", + " print(\"No Duplicate Samples Found.\")\n", + "\n", + "check_duplicates(df_data)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "# Encode\n", + "oneH = OneHotEncoder()\n", + "data_onehot_encoded = oneH.fit_transform(df_data)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 6: Write your code here:\n", + "# Target distribution to see if balanced\n", + "print(df_data['Delivery_Time'].value_counts())\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "numerical_cols = df_data.select_dtypes(include=[\"int64\", \"float64\"]).columns.drop(\"Delivery_Time\")\n", + "for col in numerical_cols:\n", + " print(f\"Encoding column: {col}\")\n", + " le = LabelEncoder()\n", + " # TODO: Apply fit_transform to encode the column\n", + " df_data[col] = le.fit_transform(df_data[col]) # \n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "\n", + "standard_scaler = StandardScaler() # Instantiate StandardScaler\n", + "data_standard_scaled = standard_scaler.fit_transform(df_data)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "X = df_data.drop(\"Delivery_Time\", axis=1).astype(float)\n", + "y = df_data['Delivery_Time'].astype(float)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:\n", + "n_splits = 5 # K=5 Folds\n", + "\n", + "# 5-Fold Cross-Validation, shuffled\n", + "lr_mae = []\n", + "kf = KFold(n_splits=5, shuffle=True, random_state=42)\n", + "\n", + "for fold_idx, (train_index, test_index) in enumerate(kf.split(X)):\n", + " print(f\"\\nFold {fold_idx + 1}/{n_splits}\")\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", + " for model_name, model in models.items():\n", + " print(f\"Training {model_name}...\")\n", + "\n", + " # Train\n", + " model.fit(X_train, y_train)\n", + "\n", + " # Predict\n", + " y_pred = model.predict(X_test)\n", + " mae = mean_absolute_error(y_test, y_pred)\n", + " lr_mae.append(mae)\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "average_losses = np.mean(lr_losses, axis=0)\n", + "\n", + "plt.figure(figsize=(10, 6))\n", + "plt.plot(average_losses, label='Average Loss')\n", + "plt.xlabel('Iteration')\n", + "plt.ylabel('MSE Loss')\n", + "plt.title('Linear Regression Training Loss (Averaged Across Folds)')\n", + "plt.legend()\n", + "plt.grid(True, alpha=0.3)\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:\n", + "models = {\n", + " \"Random Tree Regressor\": RandomTreeRegressor(max_depth=10),\n", + " \"CatBoost\": CatBoostRegressor(verbose=0)\n", + "\n", + "}" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Storage for results\n", + "all_results = {}\n", + "\n", + "for name in models:\n", + " all_results[name] = {'mse': [], 'rmse': [], 'r2': []}" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "kf = KFold(n_splits=5, shuffle=True, random_state=42)\n", + "\n", + "for fold_idx, (train_index, test_index) in enumerate(kf.split(X)):\n", + " print(f\"\\nFold {fold_idx + 1}/{n_splits}\")\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", + " for model_name, model in models.items():\n", + " print(f\"Training {model_name}...\")\n", + "\n", + " # Train\n", + " model.fit(X_train, y_train)\n", + "\n", + " # Predict\n", + " y_pred = model.predict(X_test)\n", + "\n", + " # Calculate metrics\n", + " mse = mean_squared_error(y_test, y_pred)\n", + " rmse = np.sqrt(mse)\n", + "\n", + " # Store results\n", + " all_results[model_name][\"mse\"].append(mse)\n", + " all_results[model_name][\"rmse\"].append(rmse)\n", + "\n", + "for model_name in all_results:\n", + " print(f\"\\n{model_name}:\")\n", + " print(f\" MSE: {np.mean(all_results[model_name]['mse']):.4f}\")\n", + " print(f\" RMSE: {np.mean(all_results[model_name]['rmse']):.4f}\")" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/416/Q2.ipynb b/submissions_extracted/416/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..91440de9dce935ca00541ccb34d45aad75ae7fee --- /dev/null +++ b/submissions_extracted/416/Q2.ipynb @@ -0,0 +1,353 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q2-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import os\n", + "import torch\n", + "import kagglehub\n", + "import pandas as pd\n", + "import numpy as np\n", + "import torch.nn as nn\n", + "from torch.optim import AdamW\n", + "import matplotlib.pyplot as plt\n", + "from torch.utils.data import DataLoader, TensorDataset\n", + "from sklearn.model_selection import train_test_split\n", + "from sklearn.preprocessing import StandardScaler, LabelEncoder\n", + "from sklearn.metrics import mean_absolute_error, mean_squared_error, r2_score\n", + "\n", + "print(f\"PyTorch version: {torch.__version__}\")\n", + "print(f\"CUDA available: {torch.cuda.is_available()}\")\n", + "import pandas as pd\n", + "import numpy as np\n", + "from PIL import Image\n", + "from sklearn.model_selection import train_test_split\n", + "\n", + "# Load Labels\n", + "labels_df = pd.read_csv(os.path.join(path, \"labels.csv\"))\n", + "img_dir = os.path.join(path, \"images\")\n", + "\n", + "images = []\n", + "ages = []\n", + "\n", + "# Load Images and Resize\n", + "print(\"Loading images...\")\n", + "for index, row in labels_df.iterrows():\n", + " img_name = row.iloc[0]\n", + " age = row.iloc[1]\n", + " img_path = os.path.join(img_dir, img_name)\n", + "\n", + " if os.path.exists(img_path):\n", + " img = Image.open(img_path).convert('RGB')\n", + " img_array = np.array(img) / 255.0 # Normalize pixel values to [0, 1]\n", + " images.append(img_array)\n", + " ages.append(age)\n", + "\n", + "X = np.array(images)\n", + "y = np.array(ages)\n", + "\n", + "# Transpose image dimensions to match PyTorch format (N, C, H, W)\n", + "X = np.transpose(X, (0, 3, 1, 2))\n", + "\n", + "# Split Data\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n", + "\n", + "print(f\"X_train shape: {X_train.shape}\")\n", + "print(f\"X_test shape: {X_test.shape}\")\n", + "print(f\"y_train shape: {y_train.shape}\")\n", + "print(f\"y_test shape: {y_test.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 1. Convert Numpy arrays to PyTorch Tensors\n", + "X_train = torch.tensor(X_train.values, dtype=torch.float32)\n", + "X_test = torch.tensor(X_test.values, dtype=torch.float32)\n", + "y_train = torch.tensor(y_train.values, dtype=torch.long)\n", + "y_test = torch.tensor(y_test.values, dtype=torch.long)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 2. Create TensorDataset objects\n", + "\n", + "train_dataset = TensorDataset(X_train, y_train)\n", + "test_dataset = TensorDataset(X_test, y_test)\n", + "\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 3. Create DataLoaders\n", + "\n", + "train_loader = DataLoader(train_dataset, batch_size=32, shuffle=True)\n", + "test_loader = DataLoader(test_dataset, batch_size=32, shuffle=False)\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 4. Print shape of one batch\n", + "\n", + "X_batch, y_batch = next(iter(train_loader))\n", + "print(f\"Training batch input shape: {X_batch.shape}\")\n", + "print(f\"Training batch labels shape: {y_batch.shape}\")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 5. Display sample images\n", + "\n", + "print(\"Train dataset:\", len(train_dataset))\n", + "print(\"Test dataset:\", len(test_dataset))" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your model class here:\n", + "class NN4Layer(nn.Module):\n", + " def __init__(self, input_dim, hidden_dim):\n", + " super(NN3Layer, self).__init__()\n", + " self.layer1 = nn.Linear(input_dim, hidden_dim)\n", + "\n", + " self.layer2 = nn.Linear(hidden_dim, hidden_dim)\n", + " self.layer3 = nn.Linear(hidden_dim, hidden_dim)\n", + "\n", + " self.layer4 = nn.Linear(hidden_dim, output_dim)\n", + " # ReLU activation\n", + " self.relu = nn.ReLU()\n", + "\n", + " def forward(self, x):\n", + " #First hidden layer with ReLU\n", + " a1 = self.relu(self.layer1(x))\n", + "\n", + " a2 = self.relu(self.layer1(a1))\n", + " a3 = self.relu(self.layer1(a2))\n", + " output = self.layer4(a3)\n", + "\n", + " return output" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your training loop here:\n", + "def train_one_epoch(model, optimizer, criterion, train_loader, device):\n", + " # : Set the model to training mode\n", + " model.train()\n", + " running_loss = 0.0\n", + "\n", + " for X_batch, y_batch in train_loader:\n", + " # : Move batch to the selected device\n", + " X_batch = X_batch.to(device)\n", + " y_batch = y_batch.to(device)\n", + " y_batch = y_batch.view(-1,1)\n", + "\n", + " # : Forward pass - get model predictions\n", + " outputs = model(X_batch)\n", + "\n", + " # Compute loss using criterion\n", + " loss = criterion(outputs, y_batch)\n", + "\n", + " # Step 1: Clear previous gradients\n", + " optimizer.zero_grad()\n", + "\n", + " # Step 2: Compute gradients (backward pass)\n", + " loss.backward()\n", + " # Step 3: Update model parameters\n", + " optimizer.step()\n", + "\n", + " running_loss += loss.item()\n", + "\n", + " # Calculate average loss over all batches\n", + " avg_loss = running_loss / len(train_loader)\n", + "\n", + " return avg_loss" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your validation loop here:\n", + "def validate(model, criterion, test_loader, device):\n", + " model.eval()\n", + "\n", + " running_loss = 0.0\n", + "\n", + " with torch.no_grad():\n", + " for X_batch, y_batch in test_loader:\n", + " X_batch = X_batch.to(device)\n", + " y_batch = y_batch.to(device)\n", + "\n", + " outputs = model(X_batch)\n", + " loss = criterion(outputs, y_batch)\n", + "\n", + " running_loss += loss.item()\n", + "\n", + " avg_loss = running_loss / len(test_loader)\n", + "\n", + " return avg_loss" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Define device, model, loss, optimizer:\n", + "device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n", + "\n", + "# Model parameters\n", + "input_dim = X_train.shape[1] # Number of tabular features\n", + "hidden_dim = 64 # Design choice\n", + "\n", + "model = NN4Layer(input_dim, hidden_dim).to(device)\n", + "\n", + "print(\"Model Architecture:\\n\")\n", + "print(model)\n", + "\n", + "# Calculate the total number of trainable parameters\n", + "total_params = sum(p.numel() for p in model.parameters() if p.requires_grad)\n", + "print(f\"\\nTotal trainable parameters: {total_params}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Start training for 20 epochs:\n", + "num_epochs = 20\n", + "learning_rate = 0.001\n", + "train_losses = []\n", + "val_losses = []\n", + "\n", + "print('Starting Training...')\n", + "for epoch in range(num_epochs):\n", + " train_loss = train_one_epoch(model, optimizer, criterion, train_loader, device) # \n", + "\n", + " val_loss = validate(model, criterion, test_loader, device) # \n", + "\n", + " train_losses.append(train_loss)\n", + " val_losses.append(val_loss)\n", + "\n", + " print(f'Epoch [{epoch+1}/{num_epochs}], Train Loss: {train_loss:.4f}, Val Loss: {val_loss:.4f}')\n", + "\n", + "print('Training Complete!')\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Get predictions on test set\n", + "model.eval()\n", + "with torch.no_grad():\n", + " predictions = model(X_test).to(device='cuda')\n", + "mse = mean_squared_error(y_train,y_pred)\n", + "rmse = np.sqrt(mse)\n", + "r2 = r2_score(y_train,y_pred)\n", + "\n", + "print(\"Model Evaluation\")\n", + "print(f\" MAE: ${mae:.2f}\")\n", + "print(f\" MSE: {mse:.2f}\")\n", + "print(f\" RMSE: ${rmse:.2f}\")\n", + "print(f\" R2: {r2:.4f}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "# Plotting results\n", + "plt.figure(figsize=(7, 5))\n", + "\n", + "plt.plot(train_losses, label='Train Loss')\n", + "plt.plot(val_losses, label='Validation Loss')\n", + "plt.title('Loss over Epochs')\n", + "plt.xlabel('Epoch')\n", + "plt.ylabel('Loss (MSE)')\n", + "plt.legend()\n", + "\n", + "plt.tight_layout()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2 (Bonus): Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/416/Q3.ipynb b/submissions_extracted/416/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..e9179e6af9ed86d2a976911d39836d5397120f08 --- /dev/null +++ b/submissions_extracted/416/Q3.ipynb @@ -0,0 +1,305 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "import torch\n", + "import torch.nn as nn\n", + "from torch.optim import Adam\n", + "from torch.utils.data import DataLoader\n", + "from torchvision.datasets import MNIST\n", + "from torchvision.transforms import ToTensor, Compose, Normalize\n", + "\n", + "from sklearn.decomposition import PCA\n", + "from sklearn.manifold import TSNE\n", + "from sklearn.cluster import KMeans\n", + "\n", + "import matplotlib.pyplot as plt\n", + "import numpy as np\n", + "from collections import Counter\n", + "\n", + "\n", + "# Download latest version\n", + "\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q3-exam-data\")\n", + "\n", + "\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "import os\n", + "import pandas as pd\n", + "Q3_data = os.path.join(path, 'Q3_data.csv')\n", + "df = pd.read_csv(Q3_data)\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "df.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "df.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "# function to check\n", + "def check_missing_values(df):\n", + " missing_values = df.isnull().sum()\n", + " print(\"Missing Values per Column:\")\n", + " print(missing_values[missing_values > 0])\n", + " if missing_values.any():\n", + " print(\"\\nHandle Missing Values as needed.\")\n", + " else:\n", + " print(\"\\nNo Missing Values Found.\")\n", + "\n", + "check_missing_values(df)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "df['Target'] = df['Target'].map({'Default': 1, 'No Default': 0}) #to make it numbers instead of letters" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "\n", + "def check_duplicates(df):\n", + " duplicates = df.duplicated().sum()\n", + " print(f\"Number of Duplicate Samples: {duplicates}\")\n", + " if duplicates > 0:\n", + " print(\"Dropping Duplicates...\")\n", + " df.drop_duplicates(inplace=True)\n", + " print(\"Duplicates Dropped.\")\n", + " else:\n", + " print(\"No Duplicate Samples Found.\")\n", + "\n", + "check_duplicates(df)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "from sklearn.preprocessing import StandardScaler, OneHotEncoder\n", + "\n", + "oneH = OneHotEncoder()\n", + "data_onehot_encoded = oneH.fit_transform(df)\n", + "# Apply fit_transform to the copied\n", + "data_onehot_encoded.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "\n", + "standard_scaler = StandardScaler() # Instantiate StandardScaler\n", + "data_standard_scaled = standard_scaler.fit_transform(df)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "\n", + "print(df_data['Target'].value_counts())\n", + "# to check if imbalanced" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "X = df.drop(\"credit\", axis=1).astype(float)\n", + "y = df['Target'].astype(float) #target" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "n_splits = 5 # K\n", + "\n", + "# Stratified 5-Fold Cross-Validation, shuffled\n", + "skf = StratifiedKFold(n_splits=n_splits, shuffle=True, random_state=42)\n", + "for fold_idx, (train_index, test_index) in enumerate(skf.split(X, y)):\n", + " print(f\"\\nFold {fold_idx + 1}/{n_splits}\")\n", + "\n", + " # 1. Split data\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", + " # 2. Train & Validate sklearn models\n", + " for model_name, model in sklearn_models.items():\n", + " print(f\"Training {model_name}...\")\n", + " model.fit(X_train, y_train) # train\n", + " y_pred = model.predict(X_test) # validate\n", + "\n", + " # 3. Save metrics for that model in this fold\n", + " accuracy = accuracy_score(y_test, y_pred)\n", + " precision = precision_score(y_test, y_pred, zero_division=0)\n", + " recall = recall_score(y_test, y_pred, zero_division=0)\n", + " f1 = f1_score(y_test, y_pred, zero_division=0)\n", + "\n", + " all_results[model_name]['accuracy'].append(accuracy)\n", + " all_results[model_name]['precision'].append(precision)\n", + " all_results[model_name]['recall'].append(recall)\n", + " all_results[model_name]['f1'].append(f1)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "for model_name in all_results:\n", + " print(f\"\\n{model_name}:\")\n", + " print(f\" Accuracy: {np.mean(all_results[model_name]['accuracy']):.4f}\")\n", + " print(f\" Precision: {np.mean(all_results[model_name]['precision']):.4f}\")\n", + " print(f\" Recall: {np.mean(all_results[model_name]['recall']):.4f}\")\n", + " print(f\" F1-Score: {np.mean(all_results[model_name]['f1']):.4f}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:\n", + "!pip install CatBoost\n", + "\n", + "from catboost import CatBoostClassifier\n", + "sklearn_models = {\n", + "\n", + " \"CatBoost\": CatBoostClassifier(\n", + " verbose=0,\n", + " n_estimators=320,\n", + " max_depth=4\n", + " )\n", + "}" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "importances = {}\n", + "importances['CatBoost'] = sklearn_models['CatBoost'].feature_importances_\n", + "fig, axes = plt.subplots(1, 3, figsize=(18, 6))\n", + "axes = axes.flatten()\n", + "features = X.columns\n", + "\n", + "for i, (model_name, imp) in enumerate(importances.items()):\n", + " # Sort features by importance for a cleaner plot\n", + " sorted_idx = np.argsort(imp)\n", + "\n", + " ax = axes[i]\n", + " ax.barh(features[sorted_idx], imp[sorted_idx])\n", + " ax.set_title(f\"{model_name} Feature Importance\")\n", + " ax.set_xlabel(\"Importance Score\")\n", + "\n", + "plt.tight_layout()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/417/Q1.ipynb b/submissions_extracted/417/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..f4f413b6930048347dcc0589931babbf6b0ffeca --- /dev/null +++ b/submissions_extracted/417/Q1.ipynb @@ -0,0 +1,407 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import pandas as pd\n", + "import numpy as np\n", + "import matplotlib.pyplot as plt\n", + "import seaborn as sns\n", + "from sklearn.model_selection import KFold\n", + "from sklearn.ensemble import RandomForestRegressor\n", + "from sklearn.preprocessing import StandardScaler\n", + "from sklearn.metrics import mean_absolute_error\n", + "import warnings\n", + "warnings.filterwarnings('ignore')\n", + "\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q1-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "delivery_path = os.path.join(path, 'Q1_data.csv')\n", + "df = pd.read_csv(delivery_path)\n", + "\n", + "print(f\"Dataset shape: {df.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "df.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "df.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Plot target distribution\n", + "plt.figure(figsize=(10, 6))\n", + "plt.hist(df['Delivery_Time'], bins=30, edgecolor='black', alpha=0.7)\n", + "plt.xlabel('Delivery Time (minutes)')\n", + "plt.ylabel('Frequency')\n", + "plt.title('Distribution of Delivery Time')\n", + "plt.grid(True, alpha=0.3)\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "df = df.drop(columns=['Order_ID'], axis=1)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "print(\"Missing values before handling:\")\n", + "print(df.isnull().sum())\n", + "print(\"\\n\")\n", + "\n", + "for col in df.columns:\n", + " if df[col].isnull().sum() > 0:\n", + " print(f\"\\n{col}:\")\n", + " print(f\"Missing count: {df[col].isnull().sum()}\")\n", + " print(f\"Data type: {df[col].dtype}\")\n", + "\n", + "for col in df.columns:\n", + " if df[col].isnull().sum() > 0:\n", + " if df[col].dtype in ['float64', 'int64']:\n", + " df[col].fillna(df[col].median(), inplace=True)\n", + " else:\n", + " df[col].fillna(df[col].mode(), inplace=True)\n", + "\n", + "print(\"\\nMissing values after handling:\")\n", + "print(df.isnull().sum())" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "print(f\"Number of duplicates: {df.duplicated().sum()}\")\n", + "df = df.drop_duplicates()\n", + "print(f\"Duplicates removed. New shape: {df.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "categorical_cols = df_delivery.select_dtypes(include=[\"object\"]).columns\n", + "\n", + "print(\"Categorical Columns:\", list(categorical_cols))" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "categorical_cols = df.select_dtypes(include=['object']).columns.tolist()\n", + "if 'delivery_time' in categorical_cols:\n", + " categorical_cols.remove('delivery_time')\n", + "\n", + "print(f\"Categorical columns: {categorical_cols}\")\n", + "\n", + "df_encoded = pd.get_dummies(df, columns=categorical_cols, drop_first=True)\n", + "print(f\"\\nShape after encoding: {df_encoded.shape}\")\n", + "print(f\"Columns after encoding: {df_encoded.columns.tolist()}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "X = df_encoded.drop('Delivery_Time', axis=1)\n", + "y = df_encoded['Delivery_Time']\n", + "\n", + "scaler = StandardScaler()\n", + "\n", + "X_scaled = scaler.fit_transform(X)\n", + "X_scaled = pd.DataFrame(X_scaled, columns=X.columns)\n", + "\n", + "print(\"Feature scaling applied using StandardScaler\")\n", + "print(f\"X shape: {X_scaled.shape}\")\n", + "print(f\"y shape: {y.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 6: Write your code here:\n", + "plt.figure(figsize=(10, 6))\n", + "plt.hist(y, bins=30, edgecolor='black', alpha=0.7)\n", + "plt.xlabel('Delivery Time')\n", + "plt.ylabel('Frequency')\n", + "plt.title('Target Variable Distribution')\n", + "plt.grid(True, alpha=0.3)\n", + "plt.show()\n", + "\n", + "print(f\"Target statistics:\")\n", + "print(f\"Mean: {y.mean():.2f}\")\n", + "print(f\"Median: {y.median():.2f}\")\n", + "print(f\"Std: {y.std():.2f}\")\n", + "print(\"\\nThis is a regression problem, so we don't check for class imbalance.\")\n", + "print(\"The distribution appears relatively normal/continuous.\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "X = df.drop(\"Delivery_Time\", axis=1).astype(float)\n", + "y = df[\"Delivery_Time\"].astype(float)\n", + "print(f\"Features (X) shape: {X_scaled.shape}\")\n", + "print(f\"Target (y) shape: {y.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:\n", + "from sklearn.model_selection import KFold\n", + "\n", + "kf = KFold(n_splits=5, shuffle=True, random_state=42)\n", + "\n", + "rf_model = RandomForestRegressor(n_estimators=100, random_state=42, n_jobs=-1)\n", + "\n", + "mae_scores = []\n", + "\n", + "for fold, (train_idx, val_idx) in enumerate(kf.split(X_scaled), 1):\n", + " X_train, X_val = X_scaled.iloc[train_idx], X_scaled.iloc[val_idx]\n", + " y_train, y_val = y.iloc[train_idx], y.iloc[val_idx]\n", + "\n", + " rf_model.fit(X_train, y_train)\n", + "\n", + " y_pred = rf_model.predict(X_val)\n", + "\n", + " mae = mean_absolute_error(y_val, y_pred)\n", + " mae_scores.append(mae)\n", + "\n", + " print(f\"Fold {fold} - MAE: {mae:.4f}\")\n", + "\n", + "print(f\"\\n{'='*50}\")\n", + "print(f\"Average MAE across all folds: {np.mean(mae_scores):.4f}\")\n", + "print(f\"Standard deviation: {np.std(mae_scores):.4f}\")\n", + "print(f\"{'='*50}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "rf_final = RandomForestRegressor(n_estimators=100, random_state=42, n_jobs=-1)\n", + "rf_final.fit(X_scaled, y)\n", + "\n", + "feature_importance = pd.DataFrame({\n", + " 'feature': X_scaled.columns,\n", + " 'importance': rf_final.feature_importances_\n", + "}).sort_values('importance', ascending=False)\n", + "\n", + "plt.figure(figsize=(12, 8))\n", + "plt.barh(feature_importance['feature'][:15], feature_importance['importance'][:15])\n", + "plt.xlabel('Importance')\n", + "plt.ylabel('Feature')\n", + "plt.title('Top 15 Feature Importances from Random Forest')\n", + "plt.gca().invert_yaxis()\n", + "plt.tight_layout()\n", + "plt.show()\n", + "\n", + "print(\"\\nTop 10 Most Important Features:\")\n", + "print(feature_importance.head(10))" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "y_pred_all = rf_final.predict(X_scaled)\n", + "\n", + "plt.figure(figsize=(12, 6))\n", + "\n", + "plt.subplot(1, 2, 1)\n", + "plt.hist(y, bins=30, edgecolor='black', alpha=0.7, color='blue')\n", + "plt.xlabel('Delivery Time (minutes)')\n", + "plt.ylabel('Frequency')\n", + "plt.title('Actual Delivery Time Distribution')\n", + "plt.grid(True, alpha=0.3)\n", + "\n", + "plt.subplot(1, 2, 2)\n", + "plt.hist(y_pred_all, bins=30, edgecolor='black', alpha=0.7, color='green')\n", + "plt.xlabel('Delivery Time (minutes)')\n", + "plt.ylabel('Frequency')\n", + "plt.title('Predicted Delivery Time Distribution')\n", + "plt.grid(True, alpha=0.3)\n", + "\n", + "plt.tight_layout()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "\n", + "%pip install kagglehub catboost xgboost tqdm -q\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:\n", + "from catboost import CatBoostRegressor\n", + "\n", + "kf = KFold(n_splits=5, shuffle=True, random_state=42)\n", + "\n", + "rf_model = RandomForestRegressor(n_estimators=100, random_state=42, n_jobs=-1)\n", + "cb_model = CatBoostRegressor(iterations=100, random_state=42, verbose=0)\n", + "\n", + "ensemble_mae_scores = []\n", + "rf_mae_scores = []\n", + "cb_mae_scores = []\n", + "\n", + "for fold, (train_idx, val_idx) in enumerate(kf.split(X_scaled), 1):\n", + "\n", + " X_train, X_val = X_scaled.iloc[train_idx], X_scaled.iloc[val_idx]\n", + " y_train, y_val = y.iloc[train_idx], y.iloc[val_idx]\n", + "\n", + " rf_model.fit(X_train, y_train)\n", + " rf_pred = rf_model.predict(X_val)\n", + " rf_mae = mean_absolute_error(y_val, rf_pred)\n", + " rf_mae_scores.append(rf_mae)\n", + "\n", + " cb_model.fit(X_train, y_train)\n", + " cb_pred = cb_model.predict(X_val)\n", + " cb_mae = mean_absolute_error(y_val, cb_pred)\n", + " cb_mae_scores.append(cb_mae)\n", + "\n", + " ensemble_pred = (rf_pred + cb_pred) / 2\n", + "\n", + " ensemble_mae = mean_absolute_error(y_val, ensemble_pred)\n", + " ensemble_mae_scores.append(ensemble_mae)\n", + "\n", + " print(f\"Fold {fold}:\")\n", + " print(f\" RandomForest MAE: {rf_mae:.4f}\")\n", + " print(f\" CatBoost MAE: {cb_mae:.4f}\")\n", + " print(f\" Ensemble MAE: {ensemble_mae:.4f}\")\n", + " print()\n", + "\n", + "print(f\"{'='*60}\")\n", + "print(f\"Average RandomForest MAE: {np.mean(rf_mae_scores):.4f} (+/- {np.std(rf_mae_scores):.4f})\")\n", + "print(f\"Average CatBoost MAE: {np.mean(cb_mae_scores):.4f} (+/- {np.std(cb_mae_scores):.4f})\")\n", + "print(f\"Average Ensemble MAE: {np.mean(ensemble_mae_scores):.4f} (+/- {np.std(ensemble_mae_scores):.4f})\")\n", + "print(f\"{'='*60}\")\n", + "\n", + "plt.figure(figsize=(10, 6))\n", + "models = ['RandomForest', 'CatBoost', 'Ensemble']\n", + "avg_scores = [np.mean(rf_mae_scores), np.mean(cb_mae_scores), np.mean(ensemble_mae_scores)]\n", + "colors = ['blue', 'orange', 'green']\n", + "\n", + "plt.bar(models, avg_scores, color=colors, alpha=0.7, edgecolor='black')\n", + "plt.ylabel('Mean Absolute Error')\n", + "plt.title('Model Performance Comparison')\n", + "plt.grid(True, alpha=0.3, axis='y')\n", + "for i, v in enumerate(avg_scores):\n", + " plt.text(i, v + 0.01, f'{v:.4f}', ha='center', va='bottom', fontweight='bold')\n", + "plt.tight_layout()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/417/Q2.ipynb b/submissions_extracted/417/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..f619ce849532025aff5de097b3db0eb9820da206 --- /dev/null +++ b/submissions_extracted/417/Q2.ipynb @@ -0,0 +1,323 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q2-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import os\n", + "import pandas as pd\n", + "import numpy as np\n", + "from PIL import Image\n", + "from sklearn.model_selection import train_test_split\n", + "\n", + "# Load Labels\n", + "labels_df = pd.read_csv(os.path.join(path, \"labels.csv\"))\n", + "img_dir = os.path.join(path, \"images\")\n", + "\n", + "images = []\n", + "ages = []\n", + "\n", + "# Load Images and Resize\n", + "print(\"Loading images...\")\n", + "for index, row in labels_df.iterrows():\n", + " img_name = row.iloc[0]\n", + " age = row.iloc[1]\n", + " img_path = os.path.join(img_dir, img_name)\n", + "\n", + " if os.path.exists(img_path):\n", + " img = Image.open(img_path).convert('RGB')\n", + " img_array = np.array(img) / 255.0 # Normalize pixel values to [0, 1]\n", + " images.append(img_array)\n", + " ages.append(age)\n", + "\n", + "X = np.array(images)\n", + "y = np.array(ages)\n", + "\n", + "# Transpose image dimensions to match PyTorch format (N, C, H, W)\n", + "X = np.transpose(X, (0, 3, 1, 2))\n", + "\n", + "# Split Data\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n", + "\n", + "print(f\"X_train shape: {X_train.shape}\")\n", + "print(f\"X_test shape: {X_test.shape}\")\n", + "print(f\"y_train shape: {y_train.shape}\")\n", + "print(f\"y_test shape: {y_test.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 1. Convert Numpy arrays to PyTorch Tensors\n", + "\n", + "# Part 1: Prepare Data for PyTorch\n", + "import torch\n", + "import torch.nn as nn\n", + "import torch.optim as optim\n", + "from torch.utils.data import TensorDataset, DataLoader\n", + "import matplotlib.pyplot as plt\n", + "import numpy as np\n", + "\n", + "# 1. Convert Numpy arrays to PyTorch Tensors\n", + "X_train_tensor = torch.FloatTensor(X_train)\n", + "X_test_tensor = torch.FloatTensor(X_test)\n", + "y_train_tensor = torch.FloatTensor(y_train).unsqueeze(1)\n", + "y_test_tensor = torch.FloatTensor(y_test).unsqueeze(1)\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 2. Create TensorDataset objects\n", + "\n", + "train_dataset = TensorDataset(X_train_tensor, y_train_tensor)\n", + "test_dataset = TensorDataset(X_test_tensor, y_test_tensor)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 3. Create DataLoaders\n", + "train_loader = DataLoader(train_dataset, batch_size=32, shuffle=True)\n", + "test_loader = DataLoader(test_dataset, batch_size=32, shuffle=False)\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 4. Print shape of one batch\n", + "for batch_X, batch_y in train_loader:\n", + " print(f\"Batch shape - X: {batch_X.shape}, y: {batch_y.shape}\")\n", + " break\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 5. Display sample images\n", + "import matplotlib.pyplot as plt\n", + "import numpy as np\n", + "\n", + "def imshow(img):\n", + " img = img / 2 + 0.5 # Unnormalize\n", + " npimg = img.numpy()\n", + " plt.imshow(np.transpose(npimg, (1, 2, 0)))\n", + " plt.show()\n", + "\n", + "# Display first 5 images from training batch\n", + "for batch_X, batch_y in train_loader:\n", + " for i in range(5):\n", + " imshow(batch_X[i])\n", + " break\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your model class here:\n", + "\n", + "print(f\"X_train shape: {X_train.shape}\")\n", + "batch_size, img_channels, img_height, img_width = X_train.shape\n", + "flattened_size = img_channels * img_height * img_width\n", + "print(f\"Flattened size: {flattened_size}\")\n", + "\n", + "class AgePredictor(nn.Module):\n", + " def __init__(self, input_size):\n", + " super(AgePredictor, self).__init__()\n", + " self.fc1 = nn.Linear(input_size, 512)\n", + " self.fc2 = nn.Linear(512, 256)\n", + " self.fc3 = nn.Linear(256, 128)\n", + " self.fc4 = nn.Linear(128, 1)\n", + " self.relu = nn.ReLU()\n", + " self.dropout = nn.Dropout(0.3)\n", + "\n", + " def forward(self, x):\n", + " x = x.view(x.size(0), -1) # Flatten\n", + " x = self.relu(self.fc1(x))\n", + " x = self.dropout(x)\n", + " x = self.relu(self.fc2(x))\n", + " x = self.dropout(x)\n", + " x = self.relu(self.fc3(x))\n", + " x = self.dropout(x)\n", + " x = self.fc4(x)\n", + " return x\n", + "\n", + "\n", + "\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your training loop here:\n", + "def train_loop(model, train_loader, optimizer, criterion, device):\n", + " model.train()\n", + " train_loss = 0\n", + " for X_batch, y_batch in train_loader:\n", + " X_batch, y_batch = X_batch.to(device), y_batch.to(device)\n", + " optimizer.zero_grad()\n", + " outputs = model(X_batch)\n", + " loss = criterion(outputs, y_batch)\n", + " loss.backward()\n", + " optimizer.step()\n", + " train_loss += loss.item()\n", + " return train_loss / len(train_loader)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your validation loop here:\n", + "\n", + "def val_loop(model, val_loader, criterion, device):\n", + " model.eval()\n", + " val_loss = 0\n", + " with torch.no_grad():\n", + " for X_batch, y_batch in val_loader:\n", + " X_batch, y_batch = X_batch.to(device), y_batch.to(device)\n", + " outputs = model(X_batch)\n", + " loss = criterion(outputs, y_batch)\n", + " val_loss += loss.item()\n", + " return val_loss / len(val_loader)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Define device, model, loss, optimizer:\n", + "device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n", + "model = AgePredictor(flattened_size).to(device)\n", + "criterion = nn.MSELoss()\n", + "optimizer = optim.Adam(model.parameters(), lr=0.001)\n", + "\n", + "print(f\"Model initialized with input size: {flattened_size}\")\n", + "print(f\"Device: {device}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Start training for 20 epochs:\n", + "train_losses = []\n", + "val_losses = []\n", + "\n", + "for epoch in range(20):\n", + " train_loss = train_loop(model, train_loader, optimizer, criterion, device)\n", + " val_loss = val_loop(model, test_loader, criterion, device)\n", + " train_losses.append(train_loss)\n", + " val_losses.append(val_loss)\n", + " print(f\"Epoch {epoch+1}/20 - Train Loss: {train_loss:.4f}, Val Loss: {val_loss:.4f}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "\n", + "plt.figure(figsize=(10, 5))\n", + "plt.plot(train_losses, label='Training Loss')\n", + "plt.plot(val_losses, label='Validation Loss')\n", + "plt.xlabel('Epoch')\n", + "plt.ylabel('Loss')\n", + "plt.title('Training and Validation Loss')\n", + "plt.legend()\n", + "plt.show()\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2 (Bonus): Write your code here:\n", + "\n", + "model.eval()\n", + "with torch.no_grad():\n", + " for X_batch, y_batch in test_loader:\n", + " X_batch, y_batch = X_batch.to(device), y_batch.to(device)\n", + " predictions = model(X_batch).cpu().numpy().flatten()\n", + " actual = y_batch.cpu().numpy().flatten()\n", + "\n", + "\n", + " for i in range(5):\n", + " print(f\"Image {i+1}: Predicted age = {predictions[i]:.1f}, Actual age = {actual[i]}\")\n", + " imshow(X_batch[i].cpu())\n", + "\n", + " break" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/417/Q3.ipynb b/submissions_extracted/417/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..773b87f9b45b352aa7d453a34e36b98a8f5a662a --- /dev/null +++ b/submissions_extracted/417/Q3.ipynb @@ -0,0 +1,284 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "import pandas as pd\n", + "import numpy as np\n", + "from sklearn.model_selection import StratifiedKFold\n", + "from sklearn.preprocessing import StandardScaler, LabelEncoder\n", + "from sklearn.metrics import accuracy_score, f1_score\n", + "import matplotlib.pyplot as plt\n", + "import seaborn as sns\n", + "from IPython.display import clear_output\n", + "import os\n", + "%pip install kagglehub catboost xgboost tqdm -q\n", + "\n", + "clear_output()\n", + "from catboost import CatBoostClassifier\n", + "\n", + "# Download latest version\n", + "\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q3-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "pathh = os.path.join(path, 'Q3_data.csv')\n", + "df = pd.read_csv(pathh)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "print(\"First 5 rows:\")\n", + "print(df.head())" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:# Display dataset information\n", + "print(\"\\nDataset info:\")\n", + "print(df.info())" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "print(\"\\nStatistical description:\")\n", + "print(df.describe())" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "print(\"\\nMissing values:\")\n", + "print(df.isnull().sum())\n", + "\n", + "df = df.fillna(df.median(numeric_only=True))\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "print(f\"\\nNumber of duplicates: {df.duplicated().sum()}\")\n", + "df = df.drop_duplicates()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "#I made it so i dont need to do this part\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "scaler = StandardScaler()\n", + "numerical_cols = df.select_dtypes(include=[np.number]).columns\n", + "df[numerical_cols] = scaler.fit_transform(df[numerical_cols])" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "\n", + "print(f\"\\nTarget distribution:\\n{df['Target'].value_counts()}\")\n", + "print(f\"Target imbalance: {'Yes' if df['Target'].value_counts().max() / df['Target'].value_counts().sum() > 0.7 else 'No'}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "\n", + "X = df.drop('Target', axis=1)\n", + "y = df['Target'].astype(int)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:\n", + "\n", + "skf = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)\n", + "model = CatBoostClassifier(random_state=42, verbose=0)\n", + "\n", + "accuracies = []\n", + "f1_scores = []\n", + "\n", + "for train_idx, val_idx in skf.split(X, y):\n", + " X_train, X_val = X.iloc[train_idx], X.iloc[val_idx]\n", + " y_train, y_val = y.iloc[train_idx], y.iloc[val_idx]\n", + "\n", + " model.fit(X_train, y_train)\n", + " y_pred = model.predict(X_val)\n", + "\n", + " accuracies.append(accuracy_score(y_val, y_pred))\n", + " f1_scores.append(f1_score(y_val, y_pred))\n", + "\n", + "print(f\"\\nAverage Accuracy: {np.mean(accuracies):.4f}\")\n", + "print(f\"Average F1 Score: {np.mean(f1_scores):.4f}\")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "\n", + "feature_importance = pd.DataFrame({\n", + " 'feature': X.columns,\n", + " 'importance': model.feature_importances_\n", + "}).sort_values('importance', ascending=False)\n", + "\n", + "print(\"\\nTop 5 Feature Importances:\")\n", + "print(feature_importance.head(5))" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "\n", + "coeffs = {}\n", + "\n", + "coeffs['Lasso'] = model['LASSO Regression'].coef_\n", + "coeffs['Ridge'] = model['Ridge Regression'].coef_\n", + "\n", + "fig, axes = plt.subplots(1, 2, figsize=(15, 6))\n", + "axes = axes.flatten()\n", + "features = X.columns\n", + "\n", + "for i, (model_name, coef) in enumerate(coeffs.items()):\n", + " # Sort features by absolute coefficient value\n", + " absolute_coef = np.abs(coef)\n", + " sorted_idx = np.argsort(absolute_coef)\n", + "\n", + " ax = axes[i]\n", + " ax.barh(features[sorted_idx], coef[sorted_idx])\n", + " ax.set_title(f\"{model_name} Coefficients\")\n", + " ax.set_xlabel(\"Coefficient Value (Impact)\")\n", + "\n", + "plt.tight_layout()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "golden_feature = df.iloc['feature']\n", + "print(f\"\\nGolden Feature: {golden_feature}\")\n", + "\n", + "plt.figure(figsize=(10, 6))\n", + "sns.barplot(data=feature_importance.head(10), x='importance', y='feature')\n", + "plt.title('Top 10 Feature Importances')\n", + "plt.tight_layout()\n", + "plt.show()\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:\n", + "X_golden = df[[golden_feature]]\n", + "\n", + "# Retrain with only golden feature\n", + "accuracies_golden = []\n", + "f1_scores_golden = []\n", + "\n", + "for train_idx, val_idx in skf.split(X_golden, y):\n", + " X_train_golden, X_val_golden = X_golden.iloc[train_idx], X_golden.iloc[val_idx]\n", + " y_train, y_val = y.iloc[train_idx], y.iloc[val_idx]\n", + "\n", + " model.fit(X_train_golden, y_train)\n", + " y_pred = model.predict(X_val_golden)\n", + "\n", + " accuracies_golden.append(accuracy_score(y_val, y_pred))\n", + " f1_scores_golden.append(f1_score(y_val, y_pred))\n", + "\n", + "print(f\"\\nAverage Accuracy (Golden Feature Only): {np.mean(accuracies_golden):.4f}\")\n", + "print(f\"Average F1 Score (Golden Feature Only): {np.mean(f1_scores_golden):.4f}\")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/418/Q1.ipynb b/submissions_extracted/418/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..f1adc3ac53c269a0a7135fe159e4fda300cf1d6f --- /dev/null +++ b/submissions_extracted/418/Q1.ipynb @@ -0,0 +1,435 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import numpy as np\n", + "import pandas as pd\n", + "import matplotlib.pyplot as plt\n", + "import os\n", + "from sklearn.model_selection import train_test_split, KFold\n", + "from sklearn.preprocessing import StandardScaler, LabelEncoder\n", + "from sklearn.ensemble import RandomForestRegressor\n", + "from sklearn.metrics import mean_absolute_error, mean_squared_error" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q1-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "\n", + "df_path = os.path.join(path, 'Q1_data.csv')\n", + "\n", + "df = pd.read_csv(df_path)\n", + "df" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "\n", + "df.head() # show first 5 rows" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "\n", + "df.info() # to get all information" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "\n", + "df.describe() #show statistical information" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "\n", + "df[\"Delivery_Time\"].hist(bins=30, edgecolor='black')\n", + "\n", + "plt.title(\"Target Distribution (Delivery_Time)\")\n", + "plt.xlabel('Delivery_Time')\n", + "plt.ylabel(\"Frequency\")\n", + "plt.grid(False)\n", + "plt.show()\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "df = df.drop('Order_ID', axis=1)\n", + "df" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "# check duplicate\n", + "def check_duplicates(df):\n", + " duplicates = df.duplicated().sum()\n", + " print(f\"Number of Duplicate Samples: {duplicates}\")\n", + " if duplicates > 0:\n", + " print(\"Dropping Duplicates...\")\n", + " df.drop_duplicates(inplace=True)\n", + " print(\"Duplicates Dropped.\")\n", + " else:\n", + " print(\"No Duplicate Samples Found.\")\n", + "\n", + "check_duplicates(df)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# check shape after dropping duplicate Samples\n", + "df.shape" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "df.isnull().sum()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# check unique values\n", + "print(df['Traffic_Level'].unique())\n", + "print(df['Time_of_Day'].unique())\n", + "print(df['Courier_Experience_yrs'].unique())\n", + "print(df['Weather'].unique())" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "''' we can say that nan mean: no traffic in that time.'''\n", + "df['Traffic_Level'] = df['Traffic_Level'].fillna('none')\n", + "df['Traffic_Level'].isnull().sum()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "''' handle weather '''\n", + "df['Weather']= df['Weather'].fillna('Clear')\n", + "print(df['Weather'].isnull().sum())\n", + "print(df['Weather'].unique())" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "''' handle Time_of_Day'''\n", + "\n", + "from numpy._core.fromnumeric import mean\n", + "\n", + "df['Time_of_Day']= df['Time_of_Day'].fillna('Evening')\n", + "print(df['Time_of_Day'].isnull().sum())\n", + "print(df['Time_of_Day'].unique())" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "from numpy._core.fromnumeric import mean\n", + "''' handle Courier_Experience_yrs'''\n", + "\n", + "df['Courier_Experience_yrs']= df['Courier_Experience_yrs'].fillna(mean)\n", + "print(df['Courier_Experience_yrs'].isnull().sum())" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "df.isnull().sum()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "''' for the target i would drop missing '''\n", + "df['Delivery_Time']= df['Delivery_Time'].dropna()\n", + "df.isnull().sum()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "df['Delivery_Time'].unique()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "# categorical columns\n", + "categorical_cols = df.select_dtypes(include=[\"object\"]).columns\n", + "\n", + "print(\"Categorical Columns:\", list(categorical_cols))" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "from sklearn.preprocessing import LabelEncoder\n", + "\n", + "la = LabelEncoder()\n", + "df['Weather']= la.fit_transform(df['Weather'])\n", + "df['Traffic_Level']= la.fit_transform(df['Traffic_Level'])\n", + "df['Vehicle_Type']= la.fit_transform(df['Vehicle_Type'])\n", + "df['Time_of_Day']= la.fit_transform(df['Time_of_Day'])\n", + "df" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "from sklearn.preprocessing import StandardScaler\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 6: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "X = df.drop('Delivery_Time', axis=1)\n", + "y = df['Delivery_Time']\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y , random_state=42, test_size=0.2)\n", + "\n", + "print(f\"Train: {X_train.shape}, Test: {X_test.shape}\")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "from sklearn.preprocessing import StandardScaler\n", + "from sklearn.preprocessing import MinMaxScaler\n", + "\n", + "scaler = MinMaxScaler()\n", + "X_train_scaled = scaler.fit_transform(X_train)\n", + "X_test_scaled = scaler.fit_transform(X_test)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:\n", + "from sklearn.ensemble import RandomForestClassifier\n", + "from sklearn.model_selection import StratifiedKFold\n", + "\n", + "models = {\n", + "\n", + " \"Random Forest\": RandomForestClassifier(\n", + " n_estimators=200,\n", + " max_depth=50\n", + " )\n", + "}\n", + "results = {}\n", + "\n", + "for model_name in models:\n", + " results[model_name] = {'MSE': []}\n", + "\n", + "n_splits = 10\n", + "\n", + "skf = StratifiedKFold(\n", + " n_splits=n_splits, shuffle=True, random_state=42)\n", + "\n", + "for fold_idx, (train_index, test_index) in enumerate(skf.split(X, y)):\n", + " print(f\"\\nFold {fold_idx + 1}/{n_splits}\")\n", + "\n", + " # Get the train & test split for this fold\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", + " # Train & Validate Models\n", + " for model_name, model in models.items():\n", + "\n", + " print(f\"Training {model_name}...\")\n", + "\n", + " # Fit the model on train data\n", + " model.fit(X_train, y_train)\n", + "\n", + " # Use the model to predict the test data\n", + " y_pred = model.predict(X_test)\n", + "\n", + " # Calculate evaluation metrics\n", + " MSE = mean_squared_error(y_test, y_pred)\n", + "\n", + " results[model_name]['accuracy'].append(MSE)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "for model_name in results:\n", + " print(f\"\\n{model_name}:\")\n", + " # Print the average\n", + " print(f\" MSE: {np.mean(results[model_name]['MSE']):.4f}\")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/418/Q2.ipynb b/submissions_extracted/418/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..80d79abe224f18a4acbcb6c5fc806d464fe99830 --- /dev/null +++ b/submissions_extracted/418/Q2.ipynb @@ -0,0 +1,364 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q2-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import os\n", + "import pandas as pd\n", + "import numpy as np\n", + "from PIL import Image\n", + "from sklearn.model_selection import train_test_split\n", + "\n", + "# Load Labels\n", + "labels_df = pd.read_csv(os.path.join(path, \"labels.csv\"))\n", + "img_dir = os.path.join(path, \"images\")\n", + "\n", + "images = []\n", + "ages = []\n", + "\n", + "# Load Images and Resize\n", + "print(\"Loading images...\")\n", + "for index, row in labels_df.iterrows():\n", + " img_name = row.iloc[0]\n", + " age = row.iloc[1]\n", + " img_path = os.path.join(img_dir, img_name)\n", + "\n", + " if os.path.exists(img_path):\n", + " img = Image.open(img_path).convert('RGB')\n", + " img_array = np.array(img) / 255.0 # Normalize pixel values to [0, 1]\n", + " images.append(img_array)\n", + " ages.append(age)\n", + "\n", + "X = np.array(images)\n", + "y = np.array(ages)\n", + "\n", + "# Transpose image dimensions to match PyTorch format (N, C, H, W)\n", + "X = np.transpose(X, (0, 3, 1, 2))\n", + "\n", + "# Split Data\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n", + "\n", + "print(f\"X_train shape: {X_train.shape}\")\n", + "print(f\"X_test shape: {X_test.shape}\")\n", + "print(f\"y_train shape: {y_train.shape}\")\n", + "print(f\"y_test shape: {y_test.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import torch\n", + "import torch.nn as nn\n", + "from torch.optim import Adam\n", + "import matplotlib.pyplot as plt\n", + "from sklearn.preprocessing import StandardScaler\n", + "from torch.utils.data import TensorDataset\n", + "from torch.utils.data import DataLoader" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 1. Convert Numpy arrays to PyTorch Tensors\n", + "\n", + "# transform to tensors\n", + "X_train = torch.tensor(X_train, dtype=torch.float32)\n", + "X_test = torch.tensor(X_test, dtype=torch.float32)\n", + "y_train = torch.tensor(y_train, dtype=torch.float32)\n", + "y_test = torch.tensor(y_test, dtype=torch.float32)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 2. Create TensorDataset objects\n", + "\n", + "\n", + "# Create TensorDatasets for training and testing\n", + "train_dataset = TensorDataset(X_train, y_train)\n", + "test_dataset = TensorDataset(X_test, y_test)\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 3. Create DataLoaders\n", + "\n", + "\n", + "# Create Dataloaders to train and test data in batches\n", + "train_loader = DataLoader(train_dataset, batch_size=32, shuffle=True)\n", + "test_loader = DataLoader(test_dataset, batch_size=32, shuffle=False)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 4. Print shape of one batch\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 5. Display sample images\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your model class here:\n", + "class NN4Layer(nn.Module):\n", + "\n", + " def __init__(self, input_dim, output_dim):\n", + " super(NN4Layer, self).__init__()\n", + "\n", + " # First linear layer: input features -> hidden layer\n", + " self.layer1 = nn.Linear(input_dim, 1)\n", + "\n", + " # Second linear layer: hidden layer -> hidden layer\n", + " self.layer2 = nn.Linear(1, 1)\n", + "\n", + " # thired layer: hidden layer -> number of classes (logits)\n", + " self.layer3 = nn.Linear(1, 1)\n", + "\n", + " # Output layer: hidden layer -> number of classes (logits)\n", + " self.layer4 = nn.Linear(1, output_dim)\n", + "\n", + " # ReLU activation for non-linearity\n", + " self.relu = nn.ReLU()\n", + "\n", + " # Defines how input data flows through the network\n", + " def forward(self, x):\n", + " # First hidden layer\n", + " z1 = self.layer1(x)\n", + " a1 = self.relu(z1)\n", + "\n", + " # Second hidden layer\n", + " z2 = self.layer2(a1)\n", + " a2 = self.relu(z2)\n", + "\n", + " # thired hidden layer\n", + " z3 = self.layer2(a2)\n", + " a3 = self.relu(z3)\n", + "\n", + " output = self.layer4(a3)\n", + "\n", + " return output\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your training loop here:\n", + "def train_one_epoch(model, optimizer, criterion, train_loader, device):\n", + " # Set the model to training mode\n", + " model.train()\n", + "\n", + " running_loss = 0.0\n", + "\n", + " for X_batch, y_batch in train_loader:\n", + " # Move batch to the selected device\n", + " X_batch = X_batch.to(device)\n", + " y_batch = y_batch.view(-1, 1).to(device)\n", + "\n", + " # Forward pass\n", + " outputs = model(X_batch)\n", + " loss = criterion(outputs, y_batch)\n", + "\n", + " # Backward pass & optimization\n", + " optimizer.zero_grad() # Clear previous gradients\n", + " loss.backward() # Compute gradients\n", + " optimizer.step() # Update model parameters\n", + "\n", + " running_loss += loss.item()\n", + "\n", + " # Average loss over all batches\n", + " avg_loss = running_loss / len(train_loader)\n", + "\n", + " return avg_loss" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your validation loop here:\n", + "def validate(model, criterion, test_loader, device):\n", + " # Set the model to evaluation mode\n", + " model.eval()\n", + "\n", + " running_loss = 0.0\n", + " correct = 0\n", + " total = 0\n", + "\n", + " with torch.no_grad():\n", + " for X_batch, y_batch in test_loader:\n", + " # Move data to device\n", + " X_batch = X_batch.view(X_batch.size(0), -1).to(device)\n", + " y_batch = y_batch.to(device)\n", + "\n", + " # Forward pass\n", + " outputs = model(X_batch) # shape: (batch_size, 10)\n", + " loss = criterion(outputs, y_batch)\n", + " running_loss += loss.item()\n", + "\n", + " # Apply Softmax to get probabilities\n", + " probabilities = F.softmax(outputs, dim=1)\n", + "\n", + " # Multiclass predictions\n", + " predicted = torch.argmax(probabilities, dim=1)# take indx of max prob\n", + "\n", + " # Accuracy calculation\n", + " correct += (predicted == y_batch).sum().item()\n", + " total += y_batch.size(0)\n", + "\n", + " avg_loss = running_loss / len(test_loader)\n", + " accuracy = correct / total\n", + "\n", + " return avg_loss, accuracy\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Define device, model, loss, optimizer:\n", + "# Device setup\n", + "device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n", + "\n", + "# Model parameters\n", + "input_dim = 36 *36 *3\n", + "output_dim = 1\n", + "\n", + "# Instantiate model\n", + "model = NN4Layer(input_dim, output_dim).to(device)\n", + "\n", + "# Print the model architecture\n", + "print(\"Model Architecture:\\n\")\n", + "print(model)\n", + "\n", + "# Calculate the total number of trainable parameters\n", + "total_params = sum(p.numel() for p in model.parameters() if p.requires_grad)\n", + "print(f\"\\nTotal trainable parameters: {total_params}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Start training for 20 epochs:\n", + "num_epochs = 20\n", + "learning_rate = 0.001\n", + "\n", + "criterion = nn.MSELoss()\n", + "optimizer = Adam(model.parameters(), learning_rate)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Run Training\n", + "train_losses = []\n", + "val_losses = []\n", + "val_MSE = []\n", + "\n", + "print('Starting Training...')\n", + "for epoch in range(num_epochs):\n", + " # Train one epoch\n", + " train_loss = train_one_epoch(model, optimizer, criterion, train_loader, device)\n", + "\n", + " # Validate\n", + " val_loss, val_accuracy = validate(model, criterion, test_loader, device)\n", + "\n", + " train_losses.append(train_loss)\n", + " val_losses.append(val_loss)\n", + " val_MSE.append(val_accuracy)\n", + "\n", + " print(f'Epoch [{epoch+1}/{num_epochs}], Train Loss: {train_loss:.4f}, Val Loss: {val_loss:.4f}, Val Accuracy: {val_accuracy:.4f}')\n", + "\n", + "print('Training Complete!')" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2 (Bonus): Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/418/Q3.ipynb b/submissions_extracted/418/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..5328243fecadafa5741499a0da59454251603b65 --- /dev/null +++ b/submissions_extracted/418/Q3.ipynb @@ -0,0 +1,361 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "\n", + "\n", + "# Download latest version\n", + "\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q3-exam-data\")\n", + "\n", + "\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import numpy as np\n", + "import pandas as pd\n", + "import matplotlib.pyplot as plt\n", + "import os\n", + "from sklearn.model_selection import train_test_split, KFold\n", + "from sklearn.preprocessing import StandardScaler, LabelEncoder\n", + "from sklearn.ensemble import RandomForestRegressor\n", + "from sklearn.metrics import mean_absolute_error, mean_squared_error" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "df_path = os.path.join(path, 'Q3_data.csv')\n", + "\n", + "df = pd.read_csv(df_path)\n", + "df" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "df.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "df.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "def check_missing_values(df):\n", + " missing_values = df.isnull().sum()\n", + " print(\"Missing Values per Column:\")\n", + " print(missing_values[missing_values > 0])\n", + "\n", + " if missing_values.any():\n", + " print(\"\\nHandle Missing Values as needed.\")\n", + " else:\n", + " print(\"\\nNo Missing Values Found.\")\n", + "\n", + "check_missing_values(df)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "# check duplicate\n", + "def check_duplicates(df):\n", + " duplicates = df.duplicated().sum()\n", + " print(f\"Number of Duplicate Samples: {duplicates}\")\n", + " if duplicates > 0:\n", + " print(\"Dropping Duplicates...\")\n", + " df.drop_duplicates(inplace=True)\n", + " print(\"Duplicates Dropped.\")\n", + " else:\n", + " print(\"No Duplicate Samples Found.\")\n", + "\n", + "check_duplicates(df)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "# categorical columns\n", + "categorical_cols = df.select_dtypes(include=[\"object\"]).columns\n", + "\n", + "print(\"Categorical Columns:\", list(categorical_cols))" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "from sklearn.preprocessing import StandardScaler\n", + "\n", + "sc = StandardScaler()\n", + "df2 = df.columns.drop(\"Target\")\n", + "\n", + "df[df2] = sc.fit_transform(df[df2])\n", + "\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "df['Target'].hist()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "from IPython.display import clear_output\n", + "\n", + "%pip install kagglehub catboost xgboost tqdm imbalanced-learn -q\n", + "\n", + "clear_output()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "from sklearn.model_selection import StratifiedKFold\n", + "import matplotlib.pyplot as plt\n", + "from catboost import CatBoostClassifier\n", + "from sklearn.metrics import accuracy_score, f1_score\n", + "from sklearn.linear_model import Ridge, Lasso\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "models = {\n", + "\n", + " \"CatBoost\": CatBoostClassifier(\n", + " verbose=0,\n", + " n_estimators=20,\n", + " max_depth=6)\n", + "\n", + "\n", + "\n", + "}" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "results = {}\n", + "\n", + "for model_name in models:\n", + " results[model_name] = {'accuracy': [], 'f1': []}" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "n_splits = 10\n", + "\n", + "skf = StratifiedKFold(\n", + " n_splits=n_splits, shuffle=True, random_state=42)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "from sklearn.metrics import accuracy_score, f1_score\n", + "X = df.drop(['Target'], axis=1)\n", + "y = df['Target']\n", + "\n", + "for fold_idx, (train_index, test_index) in enumerate(skf.split(X, y)):\n", + " print(f\"\\nFold {fold_idx + 1}/{n_splits}\")\n", + "\n", + " # Get the train & test split for this fold\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", + " # Train & Validate Models\n", + " for model_name, model in models.items():\n", + "\n", + " print(f\"Training {model_name}...\")\n", + "\n", + " # Fit the model on train data\n", + " model.fit(X_train, y_train)\n", + "\n", + " # Use the model to predict the test data\n", + " y_pred = model.predict(X_test)\n", + "\n", + " # Calculate evaluation metrics\n", + " accuracy = accuracy_score(y_test, y_pred)\n", + " f1 = f1_score(y_test, y_pred, average='macro') # for multiclass f1 score, you should set the average hyperparameter (\"macro\", \"micro\", \"weighted\")\n", + "\n", + " results[model_name]['accuracy'].append(accuracy)\n", + " results[model_name]['f1'].append(f1)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "for model_name in results:\n", + " print(f\"\\n{model_name}:\")\n", + " # Print the average of each evaluation metric across folds\n", + " print(f\" Accuracy: {np.mean(results[model_name]['accuracy']):.4f}\")\n", + " print(f\" F1-Score: {np.mean(results[model_name]['f1']):.4f}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "coeffs = {}\n", + "\n", + "coeffs['Lasso'] = models['LASSO Regression'].coef_\n", + "coeffs['Ridge'] = models['Ridge Regression'].coef_\n", + "\n", + "fig, axes = plt.subplots(1, 2, figsize=(15, 6))\n", + "axes = axes.flatten()\n", + "features = X.columns\n", + "\n", + "for i, (model_name, coef) in enumerate(coeffs.items()):\n", + " # Sort features by absolute coefficient value\n", + " absolute_coef = np.abs(coef)\n", + " sorted_idx = np.argsort(absolute_coef)\n", + "\n", + " ax = axes[i]\n", + " ax.barh(features[sorted_idx], coef[sorted_idx])\n", + " ax.set_title(f\"{model_name} Coefficients\")\n", + " ax.set_xlabel(\"Coefficient Value (Impact)\")\n", + "\n", + "plt.tight_layout()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/419/Q1.ipynb b/submissions_extracted/419/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..2d6554f1ad98f6fd65d144491615d5d9e45824b3 --- /dev/null +++ b/submissions_extracted/419/Q1.ipynb @@ -0,0 +1,374 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q1-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)\n", + "import pandas as pd\n", + "import numpy as np\n", + "import matplotlib.pyplot as plt\n", + "import seaborn as sns\n", + "import kagglehub\n", + "import os\n", + "from tqdm import tqdm\n", + "from sklearn.preprocessing import LabelEncoder, OneHotEncoder, StandardScaler\n", + "\n", + "%matplotlib inline" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "\n", + "\n", + "csv_path = os.path.join(path, \"Q1_data.csv\")\n", + "\n", + "df = pd.read_csv(csv_path)\n", + "# df = df.drop(columns=\"Unnamed: 0\", axis=1)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "df.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "df.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "def check_target_distribution(df, target_column):\n", + " df[target_column].hist(bins=30, edgecolor='black')\n", + "\n", + " plt.title(f\"Target Distribution ({target_column})\")\n", + " plt.xlabel(target_column)\n", + " plt.ylabel(\"Frequency\")\n", + " plt.grid(False)\n", + "\n", + " plt.show()\n", + "\n", + "check_target_distribution(df, \"Delivery_Time\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "df = df.drop(\"Order_ID\",axis=1)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "# Analyze missing values\n", + "missing_percentage = (df.isnull().sum() / len(df)) * 100\n", + "missing_data = pd.DataFrame({\n", + " 'Column': missing_percentage.index,\n", + " 'Missing_Percentage': missing_percentage.values\n", + "})\n", + "missing_data = missing_data[missing_data['Missing_Percentage'] > 0].sort_values('Missing_Percentage', ascending=False)\n", + "\n", + "print(\"Missing Data Analysis:\")\n", + "missing_data.head(10)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "#drop the rows with missing values in all columns since percanteges are low.\n", + "df = df.dropna(subset=['Delivery_Time', 'Weather', 'Traffic_Level',\"Time_of_Day\",\"Courier_Experience_yrs\"])\n", + "df.info()\n", + "#lost about 300 rows! maybe filling some values was better\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "def check_duplicates(df):\n", + " duplicates = df.duplicated().sum()\n", + " print(f\"Number of Duplicate Samples: {duplicates}\")\n", + " if duplicates > 0:\n", + " print(\"Dropping Duplicates...\")\n", + " df.drop_duplicates(inplace=True)\n", + " print(\"Duplicates Dropped.\")\n", + " else:\n", + " print(\"No Duplicate Samples Found.\")\n", + "\n", + "check_duplicates(df)\n", + "df.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "categorical_cols = df.select_dtypes(include=[\"object\"]).columns\n", + "# df_forOneHot = df[categorical_cols]\n", + "# onehot_encoder = OneHotEncoder(handle_unknown='ignore', sparse_output=False)\n", + "# df_encoded = pd.DataFrame(onehot_encoder.fit_transform(df_forOneHot), columns=onehot_encoder.get_feature_names_out(df_forOneHot.columns))\n", + "#dont know how to merge so..\n", + "\n", + "label_encoders = {}\n", + "for col in categorical_cols:\n", + " le = LabelEncoder()\n", + " df[col] = le.fit_transform(df[col])\n", + " label_encoders[col] = le\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "from sklearn.preprocessing import StandardScaler\n", + "\n", + "numerical_cols = df.select_dtypes(include=[\"int64\", \"float64\"]).columns.drop(\"Delivery_Time\") # DON'T SCALE THE TARGET\n", + "\n", + "scaler = StandardScaler()\n", + "df[numerical_cols] = scaler.fit_transform(df[numerical_cols])\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 6: Write your code here:\n", + "check_target_distribution(df, \"Delivery_Time\")\n", + "# no target imbalance, target seems normally distributed" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "X = df.drop(\"Delivery_Time\", axis=1).astype(float)\n", + "y = df['Delivery_Time'].astype(float)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:\n", + "# since the data is not very imbalanced we can just do kfold with shuffling\n", + "from sklearn.model_selection import KFold\n", + "from sklearn.metrics import mean_squared_error as sklearn_mae, mean_absolute_error, r2_score\n", + "from sklearn.ensemble import RandomForestRegressor\n", + "\n", + "n_splits = 5 # K=5 Folds\n", + "\n", + "# 5-Fold Cross-Validation, shuffled\n", + "kf = KFold(n_splits=n_splits, shuffle=True, random_state=42)\n", + "\n", + "lr_losses = []\n", + "lr_mae = []\n", + "\n", + "model = RandomForestRegressor(n_estimators=200)\n", + "for fold_idx, (train_index, test_index) in enumerate(kf.split(X)):\n", + " print(f\"\\nFold {fold_idx + 1}/{n_splits}\")\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) # train\n", + " y_pred = model.predict(X_test) # validate\n", + "\n", + " # Calculate evaluation metrics\n", + " mae = sklearn_mae(y_test, y_pred)\n", + "\n", + "\n", + " # Store results\n", + " lr_mae.append(mae)\n", + "\n", + "print(np.mean(lr_mae))\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "importances = {}\n", + "\n", + "importances['Random Forest'] = model.feature_importances_\n", + "fig, axes = plt.subplots(1, 3, figsize=(18, 6))\n", + "axes = axes.flatten()\n", + "features = X.columns\n", + "\n", + "for i, (model_name, imp) in enumerate(importances.items()):\n", + " # Sort features by importance for a cleaner plot\n", + " sorted_idx = np.argsort(imp)\n", + "\n", + " ax = axes[i]\n", + " ax.barh(features[sorted_idx], imp[sorted_idx])\n", + " ax.set_title(f\"{model_name} Feature Importance\")\n", + " ax.set_xlabel(\"Importance Score\")\n", + "\n", + "plt.tight_layout()\n", + "plt.show()\n", + "\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "plt.figure(figsize=(8, 6))\n", + "\n", + "# Plot: Predicted vs Actual scatter\n", + "plt.scatter(y_test, y_pred, alpha=0.5, s=10, c='steelblue')\n", + "\n", + "# Add perfect prediction line\n", + "min_val = min(y_test.min(), y_pred.min())\n", + "max_val = max(y_test.max(), y_pred.max())\n", + "plt.plot([min_val, max_val], [min_val, max_val], 'r--', lw=2, label='Perfect Prediction')\n", + "\n", + "plt.xlabel('Actual Delivery(minutes) ', fontsize=12)\n", + "plt.ylabel('Predicted Delivery(minutes) ', fontsize=12)\n", + "plt.title('Predicted vs Actual ', fontsize=14)\n", + "plt.legend()\n", + "plt.grid(True, alpha=0.3)\n", + "\n", + "plt.tight_layout()\n", + "plt.show()\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:\n", + "from sklearn.model_selection import KFold\n", + "from sklearn.metrics import mean_squared_error as sklearn_mae, mean_absolute_error, r2_score\n", + "from sklearn.ensemble import RandomForestRegressor\n", + "from catboost import CatBoostRegressor\n", + "\n", + "n_splits = 5 # K=5 Folds\n", + "\n", + "# 5-Fold Cross-Validation, shuffled\n", + "kf = KFold(n_splits=n_splits, shuffle=True, random_state=42)\n", + "\n", + "lr_losses = []\n", + "lr_mae = []\n", + "\n", + "model1 = RandomForestRegressor(n_estimators=200)\n", + "model2 = CatBoostRegressor(verbose=0)\n", + "for fold_idx, (train_index, test_index) in enumerate(kf.split(X)):\n", + " print(f\"\\nFold {fold_idx + 1}/{n_splits}\")\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", + " model1.fit(X_train, y_train) # train\n", + " model2.fit(X_train,y_train)\n", + " y_pred1 = model1.predict(X_test) # validate\n", + " y_pred2 = model2.predict(X_test) # validate\n", + " y_pred_avg = (y_pred1 + y_pred2) / 2\n", + "\n", + "\n", + " # Calculate evaluation metrics\n", + " mae = sklearn_mae(y_test, y_pred_avg)\n", + "\n", + "\n", + " # Store results\n", + " lr_mae.append(mae)\n", + "\n", + "print(np.mean(lr_mae))" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/419/Q2.ipynb b/submissions_extracted/419/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..fa427f92312254047d9bd12aa8f27ac50cb3173c --- /dev/null +++ b/submissions_extracted/419/Q2.ipynb @@ -0,0 +1,411 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q2-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import os\n", + "import pandas as pd\n", + "import numpy as np\n", + "from PIL import Image\n", + "from sklearn.model_selection import train_test_split\n", + "\n", + "# Load Labels\n", + "labels_df = pd.read_csv(os.path.join(path, \"labels.csv\"))\n", + "img_dir = os.path.join(path, \"images\")\n", + "\n", + "images = []\n", + "ages = []\n", + "\n", + "# Load Images and Resize\n", + "print(\"Loading images...\")\n", + "for index, row in labels_df.iterrows():\n", + " img_name = row.iloc[0]\n", + " age = row.iloc[1]\n", + " img_path = os.path.join(img_dir, img_name)\n", + "\n", + " if os.path.exists(img_path):\n", + " img = Image.open(img_path).convert('RGB')\n", + " img_array = np.array(img) / 255.0 # Normalize pixel values to [0, 1]\n", + " images.append(img_array)\n", + " ages.append(age)\n", + "\n", + "X = np.array(images)\n", + "y = np.array(ages)\n", + "\n", + "# Transpose image dimensions to match PyTorch format (N, C, H, W)\n", + "X = np.transpose(X, (0, 3, 1, 2))\n", + "\n", + "# Split Data\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n", + "\n", + "print(f\"X_train shape: {X_train.shape}\")\n", + "print(f\"X_test shape: {X_test.shape}\")\n", + "print(f\"y_train shape: {y_train.shape}\")\n", + "print(f\"y_test shape: {y_test.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 1. Convert Numpy arrays to PyTorch Tensors\n", + "import kagglehub\n", + "import pandas as pd\n", + "import torch\n", + "import torch.nn as nn\n", + "from torch.optim import AdamW\n", + "import matplotlib.pyplot as plt\n", + "import torch.nn.functional as F\n", + "from torch.utils.data import DataLoader, TensorDataset\n", + "from sklearn.model_selection import train_test_split\n", + "from sklearn.preprocessing import StandardScaler, LabelEncoder\n", + "\n", + "# transform to tensors\n", + "X_train = torch.tensor(X_train, dtype=torch.float32)\n", + "X_test = torch.tensor(X_test, dtype=torch.float32)\n", + "y_train = torch.tensor(y_train, dtype=torch.float32)\n", + "y_test = torch.tensor(y_test, dtype=torch.float32)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 2. Create TensorDataset objects\n", + "train_dataset = TensorDataset(X_train, y_train)\n", + "test_dataset = TensorDataset(X_test, y_test)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 3. Create DataLoaders\n", + "train_loader = DataLoader(train_dataset, batch_size=32, shuffle=True)\n", + "test_loader = DataLoader(test_dataset, batch_size=32, shuffle=False)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 4. Print shape of one batch\n", + "\n", + "X_batch, y_batch = next(iter(train_loader))\n", + "print(f\"Training batch input shape: {X_batch.shape}\")\n", + "print(f\"Training batch labels shape: {y_batch.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 5. Display sample images\n", + "# Get one batch of images and labels\n", + "images, labels = next(iter(train_loader))\n", + "# images[0].size()\n", + "# Display the first 6 images in the batch\n", + "# plt.figure(figsize=(8, 4))\n", + "plt.imshow(images[0])\n", + "# # for i in range(6\n", + "# # plt.subplot(2, 3, i + 1)\n", + "# # plt.imshow(images[i].squeeze(), cmap='gray')\n", + "# # plt.title(f\"Label: {labels[i].item()}\")\n", + "# # plt.axis('off')\n", + "\n", + "# plt.tight_layout()\n", + "# plt.show()\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your model class here:\n", + "class NN4Layer(nn.Module):\n", + "\n", + " def __init__(self, input_dim, hidden_dim, output_dim):\n", + " super(NN4Layer, self).__init__()\n", + "\n", + " # First linear layer: input features -> hidden layer\n", + " self.layer1 = nn.Linear(input_dim, hidden_dim)\n", + "\n", + " # Second linear layer: hidden layer -> hidden layer\n", + " self.layer2 = nn.Linear(hidden_dim, hidden_dim)\n", + "\n", + " # Output layer: hidden layer -> number of classes (logits)\n", + " self.layer3 = nn.Linear(hidden_dim, hidden_dim)\n", + "\n", + " # Output layer: hidden layer -> number of classes (logits)\n", + " self.layer4 = nn.Linear(hidden_dim, output_dim)\n", + "\n", + " # ReLU activation for non-linearity\n", + " self.relu = nn.ReLU()\n", + "\n", + " # Defines how input data flows through the network\n", + " def forward(self, x):\n", + " # First hidden layer\n", + " z1 = self.layer1(x)\n", + " a1 = self.relu(z1)\n", + "\n", + " # Second hidden layer\n", + " z2 = self.layer2(a1)\n", + " a2 = self.relu(z2)\n", + "\n", + " z3 = self.layer3(a2)\n", + " a3 = self.relu(z3)\n", + " # Output layer (raw scores / logits)\n", + "\n", + " output = self.layer4(a3)\n", + "\n", + " return output\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your training loop here:\n", + "def train_one_epoch(model, optimizer, criterion, train_loader, device):\n", + " # Set the model to training mode\n", + " model.train()\n", + "\n", + " running_loss = 0.0\n", + "\n", + " for X_batch, y_batch in train_loader:\n", + " # Move batch to the selected device\n", + " X_batch = X_batch.view(X_batch.size(0), -1).to(device)\n", + " y_batch = y_batch.view(-1, 1).squeeze().to(device)\n", + " # print(X_batch.size())\n", + " # print(y_batch.size())\n", + "\n", + " # Forward pass\n", + " outputs = model(X_batch) # shape: (batch_size, 10)\n", + " loss = criterion(outputs, y_batch)\n", + "\n", + " # Backward pass & optimization\n", + " optimizer.zero_grad() # Clear previous gradients\n", + " loss.backward() # Compute gradients\n", + " optimizer.step() # Update model parameters\n", + "\n", + " running_loss += loss.item()\n", + "\n", + " # Average loss over all batches\n", + " avg_loss = running_loss / len(train_loader)\n", + "\n", + " return avg_loss" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your validation loop here:\n", + "def validate(model, criterion, test_loader, device):\n", + " # Set the model to evaluation mode\n", + " model.eval()\n", + "\n", + " running_loss = 0.0\n", + " correct = 0\n", + " total = 0\n", + "\n", + " with torch.no_grad():\n", + " for X_batch, y_batch in test_loader:\n", + " # Move data to device\n", + " X_batch = X_batch.view(X_batch.size(0), -1).to(device)\n", + " y_batch = y_batch.view(-1, 1).to(device)\n", + " #.view(X_batch.size(0), -1)\n", + " # Forward pass\n", + " outputs = model(X_batch) # shape: (batch_size, 10)\n", + " loss = criterion(outputs, y_batch)\n", + " running_loss += loss.item()\n", + "\n", + "\n", + "\n", + "\n", + " avg_loss = running_loss / len(test_loader)\n", + "\n", + "\n", + " return avg_loss\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Define device, model, loss, optimizer:\n", + "\n", + "# Device setup\n", + "device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n", + "\n", + "# Model parameters\n", + "input_dim = 36 * 36 # images flattened\n", + "hidden_dim = 64 # Design choice\n", + "output_dim = 1 # Regression\n", + "\n", + "# Instantiate model\n", + "model = NN4Layer(input_dim, hidden_dim, output_dim).to(device)\n", + "\n", + "# Print the model architecture\n", + "print(\"Model Architecture:\\n\")\n", + "print(model)\n", + "\n", + "# Calculate the total number of trainable parameters\n", + "total_params = sum(p.numel() for p in model.parameters() if p.requires_grad)\n", + "print(f\"\\nTotal trainable parameters: {total_params}\")\n", + "\n", + "from torch.optim import Adam" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Start training for 20 epochs:\n", + "num_epochs = 20\n", + "learning_rate = 0.001\n", + "\n", + "# Define criterion (loss function) - using CrossEntropyLoss as model now outputs logits\n", + "criterion = nn.MSELoss()\n", + "# Define optimizer\n", + "optimizer = Adam(model.parameters(), learning_rate)\n", + "\n", + "train_losses = []\n", + "val_losses = []\n", + "val_accuracies = []\n", + "\n", + "print('Starting Training...')\n", + "for epoch in range(num_epochs):\n", + " # Train one epoch\n", + " train_loss = train_one_epoch(model, optimizer, criterion, train_loader, device)\n", + "\n", + " # Validate\n", + " val_loss = validate(model, criterion, test_loader, device)\n", + "\n", + " train_losses.append(train_loss)\n", + " val_losses.append(val_loss)\n", + "\n", + "\n", + " print(f'Epoch [{epoch+1}/{num_epochs}], Train Loss: {train_loss:.4f}, Val Loss: {val_loss:.4f}')\n", + "\n", + "print('Training Complete!')" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "plt.figure(figsize=(7, 5))\n", + "\n", + "plt.plot(train_losses, label='Train Loss')\n", + "plt.plot(val_losses, label='Validation Loss')\n", + "plt.title('Loss over Epochs')\n", + "plt.xlabel('Epoch')\n", + "plt.ylabel('Loss')\n", + "plt.legend()\n", + "\n", + "plt.tight_layout()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2 (Bonus): Write your code here:\n", + "\n", + "model.eval()\n", + "with torch.no_grad():\n", + " # TODO: Get predictions for X_test\n", + "\n", + " predictions = model(X_test.to(device)).cpu().numpy()\n", + "\n", + "# TODO: Calculate evaluation metrics\n", + "\n", + "mae = mean_absolute_error(y_test.numpy(), predictions)\n", + "mse = mean_squared_error(y_test.numpy(), predictions)\n", + "rmse = np.sqrt(mse)\n", + "r2 = r2_score(y_test.numpy(), predictions)\n", + "\n", + "print(\"Model Evaluation\")\n", + "print(f\" MAE: ${mae:.2f}\")\n", + "print(f\" MSE: {mse:.2f}\")\n", + "print(f\" RMSE: ${rmse:.2f}\")\n", + "print(f\" R2: {r2:.4f}\")\n", + "\n", + "# Scatter plot: Predicted vs Actual\n", + "plt.figure(figsize=(8, 6))\n", + "\n", + "# Plot: Predicted vs Actual scatter\n", + "plt.scatter(y_test.numpy(), predictions.flatten(), alpha=0.5, s=10, c='steelblue')\n", + "\n", + "# Add perfect prediction line\n", + "min_val = min(y_test.min(), predictions.min())\n", + "max_val = max(y_test.max(), predictions.max())\n", + "plt.plot([min_val, max_val], [min_val, max_val], 'r--', lw=2, label='Perfect Prediction')\n", + "\n", + "plt.xlabel('Actual Price ($)', fontsize=12)\n", + "plt.ylabel('Predicted Price ($)', fontsize=12)\n", + "plt.title('Predicted vs Actual Diamond Prices', fontsize=14)\n", + "plt.legend()\n", + "plt.grid(True, alpha=0.3)\n", + "\n", + "plt.tight_layout()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/419/Q3.ipynb b/submissions_extracted/419/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..5a09c582e98fa8560b02c43c316754996288bf2a --- /dev/null +++ b/submissions_extracted/419/Q3.ipynb @@ -0,0 +1,280 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "import pandas as pd\n", + "import numpy as np\n", + "import matplotlib.pyplot as plt\n", + "import seaborn as sns\n", + "import kagglehub\n", + "import os\n", + "from tqdm import tqdm\n", + "from sklearn.preprocessing import LabelEncoder, OneHotEncoder, StandardScaler\n", + "\n", + "%matplotlib inline\n", + "# Download latest version\n", + "\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q3-exam-data\")\n", + "\n", + "\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "csv_path = os.path.join(path, \"Q3_data.csv\")\n", + "\n", + "df = pd.read_csv(csv_path)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "df.head()\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "df.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "df.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "\n", + "\n", + "categorical_cols = df.select_dtypes(include=[\"object\"]).columns\n", + "numerical_cols = df.select_dtypes(exclude=[\"object\"]).columns\n", + "for col in categorical_cols:\n", + " if df[col].any:\n", + " df[categorical_cols].fillna(df[categorical_cols].mode()[0])\n", + " else:\n", + " df.drop(columns=[col])\n", + "for col in numerical_cols:\n", + " if df[col].any():\n", + " df[numerical_cols].fillna(df[numerical_cols].median())\n", + " else:\n", + " df.drop(columns=[col])\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "def check_duplicates(df):\n", + " duplicates = df.duplicated().sum()\n", + " print(f\"Number of Duplicate Samples: {duplicates}\")\n", + " if duplicates > 0:\n", + " print(\"Dropping Duplicates...\")\n", + " df.drop_duplicates(inplace=True)\n", + " print(\"Duplicates Dropped.\")\n", + " else:\n", + " print(\"No Duplicate Samples Found.\")\n", + "\n", + "check_duplicates(df)\n", + "df.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "\n", + "\n", + "\n", + "# Task 3: Write your code here:\n", + "label_encoders = {}\n", + "for col in categorical_cols:\n", + " le = LabelEncoder()\n", + " df[col] = le.fit_transform(df[col])\n", + " label_encoders[col] = le" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "from sklearn.preprocessing import StandardScaler\n", + "scaler = StandardScaler()\n", + "df[numerical_cols] = scaler.fit_transform(df[numerical_cols])\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "\n", + "check_target_distribution(df, \"Target\")\n", + "# no target imbalance, target seems normally distributed" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "X = df.drop(\"Target\", axis=1).astype(float)\n", + "y = df['Target'].astype(float)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:\n", + "# Task 2,3,4,5: Write your code here:\n", + "\n", + "from sklearn.model_selection import SKFold\n", + "from sklearn.metrics import mean_squared_error as sklearn_mae, mean_absolute_error, r2_score\n", + "from sklearn.ensemble import\n", + "from catboost import CatBoostClassifier\n", + "\n", + "n_splits = 5 # K=5 Folds\n", + "\n", + "# 5-Fold Cross-Validation, shuffled\n", + "kf = SKFold(n_splits=n_splits, shuffle=True, random_state=42)\n", + "\n", + "lr_losses = []\n", + "lr_mae = []\n", + "\n", + "model = CatBoostClassifier(n_estimators=200)\n", + "for fold_idx, (train_index, test_index) in enumerate(kf.split(X)):\n", + " print(f\"\\nFold {fold_idx + 1}/{n_splits}\")\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) # train\n", + " y_pred = model.predict(X_test) # validate\n", + "\n", + " # Calculate evaluation metrics\n", + " mae = sklearn_mae(y_test, y_pred)\n", + "\n", + "\n", + " # Store results\n", + " lr_mae.append(mae)\n", + "\n", + "print(np.mean(lr_mae))\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "importances = {}\n", + "\n", + "importances['CatBoost classiefier'] = model.feature_importances_\n", + "fig, axes = plt.subplots(1, 3, figsize=(18, 6))\n", + "axes = axes.flatten()\n", + "features = X.columns\n", + "\n", + "for i, (model_name, imp) in enumerate(importances.items()):\n", + " # Sort features by importance for a cleaner plot\n", + " sorted_idx = np.argsort(imp)\n", + "\n", + " ax = axes[i]\n", + " ax.barh(features[sorted_idx], imp[sorted_idx])\n", + " ax.set_title(f\"{model_name} Feature Importance\")\n", + " ax.set_xlabel(\"Importance Score\")\n", + "\n", + "plt.tight_layout()\n", + "plt.show()\n", + "\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/42/Q1.ipynb b/submissions_extracted/42/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..f89997ac9c2080ca42474bbb43771604a99b1c10 --- /dev/null +++ b/submissions_extracted/42/Q1.ipynb @@ -0,0 +1,173 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q1-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 6: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/42/Q2.ipynb b/submissions_extracted/42/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..c8937ff34d658b6340ef5c82e1d71e84083e0ea8 --- /dev/null +++ b/submissions_extracted/42/Q2.ipynb @@ -0,0 +1,192 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q2-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import os\n", + "import pandas as pd\n", + "import numpy as np\n", + "from PIL import Image\n", + "from sklearn.model_selection import train_test_split\n", + "\n", + "# Load Labels\n", + "labels_df = pd.read_csv(os.path.join(path, \"labels.csv\"))\n", + "img_dir = os.path.join(path, \"images\")\n", + "\n", + "images = []\n", + "ages = []\n", + "\n", + "# Load Images and Resize\n", + "print(\"Loading images...\")\n", + "for index, row in labels_df.iterrows():\n", + " img_name = row.iloc[0]\n", + " age = row.iloc[1]\n", + " img_path = os.path.join(img_dir, img_name)\n", + "\n", + " if os.path.exists(img_path):\n", + " img = Image.open(img_path).convert('RGB')\n", + " img_array = np.array(img) / 255.0 # Normalize pixel values to [0, 1]\n", + " images.append(img_array)\n", + " ages.append(age)\n", + "\n", + "X = np.array(images)\n", + "y = np.array(ages)\n", + "\n", + "# Transpose image dimensions to match PyTorch format (N, C, H, W)\n", + "X = np.transpose(X, (0, 3, 1, 2))\n", + "\n", + "# Split Data\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n", + "\n", + "print(f\"X_train shape: {X_train.shape}\")\n", + "print(f\"X_test shape: {X_test.shape}\")\n", + "print(f\"y_train shape: {y_train.shape}\")\n", + "print(f\"y_test shape: {y_test.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 1. Convert Numpy arrays to PyTorch Tensors\n", + "\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 2. Create TensorDataset objects\n", + "\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 3. Create DataLoaders\n", + "\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 4. Print shape of one batch\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 5. Display sample images\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your model class here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your training loop here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your validation loop here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Define device, model, loss, optimizer:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Start training for 20 epochs:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2 (Bonus): Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/42/Q3.ipynb b/submissions_extracted/42/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..c97832709061629f03a86d1f40306ca8a3e2a744 --- /dev/null +++ b/submissions_extracted/42/Q3.ipynb @@ -0,0 +1,160 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "\n", + "\n", + "# Download latest version\n", + "\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q3-exam-data\")\n", + "\n", + "\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/420/Q1.ipynb b/submissions_extracted/420/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..dd181cfb524ec71635b751384864c78e12eb28c6 --- /dev/null +++ b/submissions_extracted/420/Q1.ipynb @@ -0,0 +1,378 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "import numpy as np\n", + "import pandas as pd\n", + "import matplotlib.pyplot as plt\n", + "import os\n", + "import kagglehub\n", + "\n", + "from sklearn.model_selection import train_test_split, KFold\n", + "from sklearn.preprocessing import StandardScaler, LabelEncoder\n", + "from sklearn.ensemble import RandomForestRegressor\n", + "from sklearn.metrics import mean_absolute_error, mean_squared_error\n", + "\n", + "import warnings\n", + "warnings.filterwarnings('ignore')\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q1-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "food_path = os.path.join(path, 'Q1_data.csv')\n", + "df = pd.read_csv(food_path)\n", + "\n", + "print(f\"Dataset shape: {df.shape}\")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "df.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "df.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "plt.figure(figsize=(10, 6))\n", + "plt.hist(df['Delivery_Time'], bins=60, edgecolor='black')\n", + "plt.title('Distribution of delivery_time')\n", + "plt.xlabel('delivery_time')\n", + "plt.ylabel('Count')\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "df" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "df = df.drop(\"Order_ID\", axis=1)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "# 2. Do we have missing values?\n", + "def check_missing_values(df):\n", + " missing_values = df.isnull().sum()\n", + " print(\"Missing Values per Column:\")\n", + " print(missing_values[missing_values > 0])\n", + " if missing_values.any():\n", + " print(\"\\nHandle Missing Values as needed.\")\n", + " else:\n", + " print(\"\\nNo Missing Values Found.\")\n", + "\n", + "check_missing_values(df)\n", + "\n", + "df['Weather'] = df['Weather'].fillna(df['Weather'].mode()[0])\n", + "df['Traffic_Level'] = df['Traffic_Level'].fillna(df['Traffic_Level'].mode()[0])\n", + "df['Time_of_Day'] = df['Time_of_Day'].fillna(df['Time_of_Day'].mode()[0])\n", + "df['Courier_Experience_yrs'] = df['Courier_Experience_yrs'].fillna(df['Courier_Experience_yrs'].mode()[0])\n", + "\n", + "df = df.dropna(subset=['Delivery_Time'])\n", + "\n", + "print(\"\\n\\nMissing now : \\n\")\n", + "check_missing_values(df)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "def check_duplicates(df):\n", + " duplicates = df.duplicated().sum()\n", + " print(f\"Number of Duplicate Samples: {duplicates}\")\n", + " if duplicates > 0:\n", + " print(\"Dropping Duplicates...\")\n", + " df.drop_duplicates(inplace=True)\n", + " print(\"Duplicates Dropped.\")\n", + " else:\n", + " print(\"No Duplicate Samples Found.\")\n", + "\n", + "check_duplicates(df)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "categorical_cols = df.select_dtypes(include=[\"object\"]).columns\n", + "\n", + "print(\"Categorical Columns:\", list(categorical_cols))\n", + "\n", + "from sklearn.preprocessing import LabelEncoder\n", + "\n", + "label_encoders = {}\n", + "for col in categorical_cols:\n", + " le = LabelEncoder()\n", + " df[col] = le.fit_transform(df[col])\n", + " label_encoders[col] = le\n", + "print(\"Done\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "\n", + "feature_cols = df.columns.drop(\"Delivery_Time\") # DON'T SCALE THE TARGET\n", + "\n", + "scaler = StandardScaler()\n", + "df[feature_cols] = scaler.fit_transform(df[feature_cols])\n", + "df.head()\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 6: Write your code here:\n", + "\n", + "#implance happen in claasification only in catogiral" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "X = df.drop(\"Delivery_Time\", axis=1).astype(float)\n", + "y = df['Delivery_Time'].astype(float)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:\n", + "\n", + "model = RandomForestRegressor(n_estimators=100, max_depth=20, random_state=42, n_jobs=-1)\n", + "n_splits = 5\n", + "\n", + "mae_scores = []\n", + "\n", + "kf = KFold(n_splits= n_splits, shuffle=True, random_state=42)\n", + "\n", + "for fold_idx, (train_index, test_index) in enumerate(kf.split(X)):\n", + " print(f\"\\nFold {fold_idx + 1}/{n_splits}\")\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", + "\n", + "\n", + "\n", + " # Train\n", + " model.fit(X_train, y_train)\n", + "\n", + " # Predict and evaluate\n", + " y_pred = model.predict(X_test)\n", + "\n", + " # Calculate metrics evaluate\n", + " mae_scores.append(mean_absolute_error(y_test, y_pred))\n", + "\n", + " # Store results\n", + "mae_scores = np.array(mae_scores)\n", + "print(f\"\\nMAE: ${mae_scores.mean():,.2f}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "# Plot feature importance\n", + "importance = pd.DataFrame({\n", + " 'feature': feature_cols,\n", + " 'importance': model.feature_importances_\n", + "})\n", + "importance = importance.sort_values('importance', ascending=True).tail(10)\n", + "\n", + "plt.figure(figsize=(10, 6))\n", + "plt.barh(importance['feature'], importance['importance'])\n", + "plt.title('Top 10 Feature Importance')\n", + "plt.xlabel('Importance')\n", + "plt.tight_layout()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "plt.figure(figsize=(10, 6))\n", + "plt.hist(y_pred, bins=30, edgecolor='black')\n", + "plt.title('Distribution of delivery time')\n", + "plt.xlabel('delivery time')\n", + "plt.ylabel('Count')\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "!pip install catboost" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "from sklearn.ensemble import RandomForestRegressor\n", + "from catboost import CatBoostRegressor" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:\n", + "\n", + "models = {\n", + "\n", + " \"Random Forest Regressor\": RandomForestRegressor(n_estimators=200),\n", + "\n", + " \"CatBoost\": CatBoostRegressor(verbose=0)\n", + "}\n", + "all_results = {}\n", + "for name in models:\n", + " all_results[name] = {'mae': [], 'rmse': [], 'r2': []}\n", + "\n", + "for name in sklearn_models:\n", + " all_results[name] = {'mae': [], 'rmse': [], 'r2': []}\n", + " kf = KFold(n_splits=5, shuffle=True, random_state=42)\n", + "\n", + "for fold_idx, (train_index, test_index) in enumerate(kf.split(X)):\n", + " print(f\"\\nFold {fold_idx + 1}/{n_splits}\")\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", + " for model_name, model in models.items():\n", + " print(f\"Training {model_name}...\")\n", + "\n", + " # Train\n", + " model.fit(X_train, y_train)\n", + "\n", + " # Predict\n", + " y_pred = model.predict(X_test)\n", + "\n", + " # Calculate metrics\n", + " mae = mean_absolute_error(y_test, y_pred)\n", + "\n", + "\n", + " # Store results\n", + " all_results[model_name][\"mae\"].append(mae)\n", + "\n", + "for model_name in all_results:\n", + " print(f\"\\n{model_name}:\")\n", + " print(f\" MSE: {np.mean(all_results[model_name]['mae']):.4f}\")\n", + "" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/420/Q2.ipynb b/submissions_extracted/420/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..9c9229369f67eb7bdf8db816ec28d8ad032b090b --- /dev/null +++ b/submissions_extracted/420/Q2.ipynb @@ -0,0 +1,372 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q2-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import os\n", + "import pandas as pd\n", + "import numpy as np\n", + "from PIL import Image\n", + "from sklearn.model_selection import train_test_split\n", + "import pandas as pd\n", + "import numpy as np\n", + "import torch\n", + "import torch.nn as nn\n", + "from torch.optim import AdamW\n", + "import matplotlib.pyplot as plt\n", + "from torch.utils.data import DataLoader, TensorDataset\n", + "from sklearn.model_selection import train_test_split\n", + "from sklearn.preprocessing import StandardScaler, LabelEncoder\n", + "from sklearn.metrics import mean_absolute_error, mean_squared_error, r2_score\n", + "\n", + "# Load Labels\n", + "labels_df = pd.read_csv(os.path.join(path, \"labels.csv\"))\n", + "img_dir = os.path.join(path, \"images\")\n", + "\n", + "images = []\n", + "ages = []\n", + "\n", + "# Load Images and Resize\n", + "print(\"Loading images...\")\n", + "for index, row in labels_df.iterrows():\n", + " img_name = row.iloc[0]\n", + " age = row.iloc[1]\n", + " img_path = os.path.join(img_dir, img_name)\n", + "\n", + " if os.path.exists(img_path):\n", + " img = Image.open(img_path).convert('RGB')\n", + " img_array = np.array(img) / 255.0 # Normalize pixel values to [0, 1]\n", + " images.append(img_array)\n", + " ages.append(age)\n", + "\n", + "X = np.array(images)\n", + "y = np.array(ages)\n", + "\n", + "# Transpose image dimensions to match PyTorch format (N, C, H, W)\n", + "X = np.transpose(X, (0, 3, 1, 2))\n", + "\n", + "# Split Data\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n", + "\n", + "print(f\"X_train shape: {X_train.shape}\")\n", + "print(f\"X_test shape: {X_test.shape}\")\n", + "print(f\"y_train shape: {y_train.shape}\")\n", + "print(f\"y_test shape: {y_test.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 1. Convert Numpy arrays to PyTorch Tensors\n", + "\n", + "X_train = torch.tensor(X_train, dtype=torch.float32)\n", + "X_test = torch.tensor(X_test, dtype=torch.float32)\n", + "y_train = torch.tensor(y_train, dtype=torch.float32)\n", + "y_test = torch.tensor(y_test, dtype=torch.float32)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 2. Create TensorDataset objects\n", + "\n", + "train_dataset = TensorDataset(X_train, y_train)\n", + "test_dataset = TensorDataset(X_test, y_test)\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 3. Create DataLoaders\n", + "\n", + "train_loader = DataLoader(train_dataset, batch_size=32, shuffle=True)\n", + "test_loader = DataLoader(test_dataset, batch_size=32, shuffle=False)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 4. Print shape of one batch\n", + "X_batch, y_batch = next(iter(train_loader))\n", + "print(f\"Training batch input shape: {X_batch.shape}\")\n", + "print(f\"Training batch labels shape: {y_batch.shape}\")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 5. Display sample images\n", + "\n", + "images, labels = next(iter(train_loader))\n", + "\n", + "# Display the first 6 images in the batch\n", + "plt.figure(figsize=(8, 4))\n", + "\n", + "for i in range(6):\n", + " plt.subplot(2, 3, i + 1)\n", + " plt.imshow(images[i].squeeze(), cmap='gray')\n", + " plt.title(f\"Label: {labels[i].item()}\")\n", + " plt.axis('off')\n", + "\n", + "plt.tight_layout()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your model class here:\n", + "\n", + "class NN4Layer(nn.Module):\n", + "\n", + " def __init__(self, input_dim, hidden_dim):\n", + " super(NN4Layer, self).__init__()\n", + "\n", + " # TODO: What are the dimensions of the first layer? (hint: features? hidden neurons?)\n", + " self.layer1 = nn.Linear(input_dim, hidden_dim)# \n", + "\n", + " # TODO: What are the dimensions from previous and next layer?\n", + " self.layer2 = nn.Linear(hidden_dim, hidden_dim)# \n", + "\n", + " # TODO: What are the dimensions from previous and next layer?\n", + " self.layer3 = nn.Linear(hidden_dim, hidden_dim)# \n", + "\n", + " # TODO: What are the dimensions from previous and next layer?\n", + " self.layer4 = nn.Linear(hidden_dim, hidden_dim)# \n", + "\n", + " # TODO: What are the dimensions of previous and output layer? (hint: hidden neurons? num of classes?)\n", + " self.layer5 =nn.Linear(hidden_dim, 1) # \n", + "\n", + " # activation function for non-linearity\n", + " self.relu = nn.ReLU()\n", + "\n", + " # Defines how input data flows through the network\n", + " def forward(self, x):\n", + " # Layer 1: TODO\n", + " z1 = self.layer1(x)\n", + " a1 = self.relu(z1)\n", + "\n", + " # Layer 2 TODO\n", + " z2 = self.layer2(a1)\n", + " a2 = self.relu(z2)\n", + "\n", + " # Layer 3 TODO\n", + " z3 = self.layer3(a2)\n", + " a3 = self.relu(z3)\n", + "\n", + " # Layer 4 TODO\n", + " z4 = self.layer4(a3)\n", + "\n", + "\n", + "\n", + "\n", + " return z4" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your training loop here:\n", + "def train_one_epoch(model, optimizer, criterion, train_loader, device):\n", + " # Set the model to training mode\n", + " model.train()\n", + "\n", + " running_loss = 0.0\n", + "\n", + " for X_batch, y_batch in train_loader:\n", + " # Move batch to the selected device\n", + " X_batch = X_batch.to(device) # shape: (batch_size, num_features)\n", + " y_batch = y_batch.view(-1, 1).to(device) # shape: (batch_size, 1)\n", + "\n", + " # Forward pass (continuous output)\n", + " outputs = model(X_batch) # shape: (batch_size, 1)\n", + " loss = criterion(outputs, y_batch)\n", + "\n", + " # Backward pass & optimization\n", + " optimizer.zero_grad() # Clear previous gradients\n", + " loss.backward() # Compute gradients\n", + " optimizer.step() # Update model parameters\n", + "\n", + " running_loss += loss.item()\n", + "\n", + " # Average loss over all batches\n", + " avg_loss = running_loss / len(train_loader)\n", + "\n", + " return avg_loss" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your validation loop here:\n", + "\n", + "def validate(model, criterion, test_loader, device):\n", + " # Set the model to evaluation mode\n", + " model.eval()\n", + "\n", + " running_loss = 0.0\n", + "\n", + " with torch.no_grad():\n", + " for X_batch, y_batch in test_loader:\n", + " # Move data to device\n", + " X_batch = X_batch.to(device) # shape: (batch_size, num_features)\n", + " y_batch = y_batch.view(-1, 1).to(device) # shape: (batch_size, 1)\n", + "\n", + " # Forward pass (continuous output)\n", + " outputs = model(X_batch) # shape: (batch_size, 1)\n", + " loss = criterion(outputs, y_batch)\n", + "\n", + " running_loss += loss.item()\n", + "\n", + " # Average loss over all batches\n", + " avg_loss = running_loss / len(test_loader)\n", + "\n", + " return avg_loss\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Define device, model, loss, optimizer:\n", + "device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n", + "# Model parameters\n", + "input_dim = X_train.shape[1] # Number of tabular features\n", + "hidden_dim = 64 # Design choice\n", + "num_epochs = 50\n", + "learning_rate = 0.001\n", + "\n", + "# Instantiate regression model\n", + "model = NN4Layer(input_dim, hidden_dim).to(device)\n", + "# Define criterion (loss function)\n", + "criterion = nn.MSELoss()\n", + "# Define optimizer\n", + "optimizer = AdamW(model.parameters(), learning_rate)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Start training for 20 epochs:\n", + "train_losses = []\n", + "val_losses = []\n", + "\n", + "print('Starting Training...')\n", + "for epoch in range(num_epochs):\n", + " # Train one epoch\n", + " train_loss = train_one_epoch(model, optimizer, criterion, train_loader, device)\n", + "\n", + " # Validate\n", + " val_loss = validate(model, criterion, test_loader, device)\n", + "\n", + " train_losses.append(train_loss)\n", + " val_losses.append(val_loss)\n", + "\n", + " if (epoch + 1) % 5 == 0:\n", + " print(\n", + " f'Epoch [{epoch+1}/{num_epochs}], '\n", + " f'Train Loss: {train_loss:.4f}, '\n", + " f'Val Loss: {val_loss:.4f}'\n", + " )\n", + "\n", + "print('Training Complete!')" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "predictions = model(X_test.to(device)).cpu().numpy()\n", + "# Scatter plot: Predicted vs Actual\n", + "plt.figure(figsize=(8, 6))\n", + "\n", + "# Plot: Predicted vs Actual scatter\n", + "plt.scatter(y_test.numpy(), predictions.flatten(), alpha=0.5, s=10, c='steelblue')\n", + "\n", + "# Add perfect prediction line\n", + "min_val = min(y_test.min(), predictions.min())\n", + "max_val = max(y_test.max(), predictions.max())\n", + "plt.plot([min_val, max_val], [min_val, max_val], 'r--', lw=2, label='Perfect Prediction')\n", + "\n", + "plt.xlabel('Actual Price ($)', fontsize=12)\n", + "plt.ylabel('Predicted Price ($)', fontsize=12)\n", + "plt.title('Predicted vs Actual Diamond Prices', fontsize=14)\n", + "plt.legend()\n", + "plt.grid(True, alpha=0.3)\n", + "\n", + "plt.tight_layout()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2 (Bonus): Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/420/Q3.ipynb b/submissions_extracted/420/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..f6c460489d756f11dee757e54c57c40983194869 --- /dev/null +++ b/submissions_extracted/420/Q3.ipynb @@ -0,0 +1,385 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "from sklearn.model_selection import train_test_split, StratifiedKFold, cross_val_score\n", + "from sklearn.preprocessing import StandardScaler, LabelEncoder\n", + "from sklearn.ensemble import RandomForestClassifier\n", + "from sklearn.metrics import classification_report, confusion_matrix, accuracy_score\n", + "import os\n", + "import numpy as np\n", + "import pandas as pd\n", + "import matplotlib.pyplot as plt\n", + "import seaborn as sns\n", + "from scipy import stats\n", + "from tqdm import tqdm\n", + "from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score\n", + "# Download latest version\n", + "\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q3-exam-data\")\n", + "\n", + "\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "fraud_path = os.path.join(path, 'Q3_data.csv')\n", + "df = pd.read_csv(fraud_path)\n", + "\n", + "print(f\"Dataset shape: {df.shape}\")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "df.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "df.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "missing_value = (df.isnull().sum() / len(df))\n", + "\n", + "\n", + "missing_data = pd.DataFrame({\n", + " 'Column': missing_value.index,\n", + " 'Missing_Percentage': missing_value.values\n", + "})\n", + "\n", + "missing_data = missing_data[missing_data['Missing_Percentage'] > 0].sort_values('Missing_Percentage', ascending=False)\n", + "print(\"Missing Data Analysis:\")\n", + "missing_data.head(10)\n", + "\n", + "def check_missing_values(df):\n", + " missing_values = df.isnull().sum()\n", + " print(\"Missing Values per Column:\")\n", + " print(missing_values[missing_values > 0])\n", + " if missing_values.any():\n", + " print(\"\\nHandle Missing Values as needed.\")\n", + " else:\n", + " print(\"\\nNo Missing Values Found.\")\n", + "\n", + "\n", + "# handle them\n", + "for col in missing_data.Column:\n", + " df[col].fillna(df[col].median(), inplace=True)\n", + "\n", + "check_missing_values(df)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "\n", + "def check_duplicates(df):\n", + " duplicates = df.duplicated().sum()\n", + " print(f\"Number of Duplicate Samples: {duplicates}\")\n", + " if duplicates > 0:\n", + " print(\"Dropping Duplicates...\")\n", + " df.drop_duplicates(inplace=True)\n", + " print(\"Duplicates Dropped.\")\n", + " else:\n", + " print(\"No Duplicate Samples Found.\")\n", + "\n", + "check_duplicates(df)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "categorical_cols = df.select_dtypes(include=[\"object\"]).columns\n", + "\n", + "print(\"Categorical Columns:\", list(categorical_cols))\n", + "\n", + "# if there any I just write it , for you to know I understand , Iknow there is non catagoris\n", + "label_encoders = {}\n", + "for col in categorical_cols:\n", + " le = LabelEncoder()\n", + " df[col] = le.fit_transform(df[col])\n", + " label_encoders[col] = le" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "numerical_cols = df.select_dtypes(include=[\"int64\", \"float64\"]).columns.drop(\"Target\") # DON'T SCALE THE TARGET\n", + "\n", + "scaler = StandardScaler()\n", + "df[numerical_cols] = scaler.fit_transform(df[numerical_cols])\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "def check_target_imbalance(df, target_column):\n", + " print(\"Target Distribution:\")\n", + " print(df[target_column].value_counts(normalize=True) * 100)\n", + " sns.countplot(x=df[target_column])\n", + " plt.title(\"Target Distribution\")\n", + " plt.show()\n", + "check_target_imbalance(df, \"Target\")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "X = df.drop(\"Target\", axis=1).astype(float)\n", + "y = df['Target'].astype(float)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "\n", + "!pip install catboost" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "from catboost import CatBoostClassifier" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:\n", + "\n", + "n_splits = 5 # K=5 Folds\n", + "\n", + "# Stratified 5-Fold Cross-Validation, shuffled\n", + "skf = StratifiedKFold(n_splits=n_splits, shuffle=True, random_state=42)\n", + "\n", + "# Storage for logistic regression results for each fold\n", + "\n", + "lr_accuracy = []\n", + "lr_f1 = []\n", + "\n", + "model = CatBoostClassifier(\n", + " verbose=0,\n", + " n_estimators=320,\n", + " max_depth=4)\n", + "\n", + "for fold_idx, (train_index, test_index) in enumerate(skf.split(X, y)):\n", + " print(f\"\\nFold {fold_idx + 1}/{n_splits}\")\n", + "\n", + " # 1. Split data\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", + " # 2. Train & Validate sklearn models\n", + "\n", + "\n", + " model.fit(X_train, y_train) # train\n", + " y_pred = model.predict(X_test) # validate\n", + "\n", + " # 3. Save metrics for that model in this fold\n", + " accuracy = accuracy_score(y_test, y_pred)\n", + " f1 = f1_score(y_test, y_pred, zero_division=0)\n", + "\n", + " lr_f1.append(f1)\n", + " lr_accuracy.append(accuracy)\n", + "\n", + "lr_accuracy = np.array(lr_accuracy)\n", + "print(f\"\\nMAE: ${lr_accuracy.mean():,.2f}\")\n", + "lr_f1 = np.array(lr_f1)\n", + "print(f\"\\nMAE: ${lr_f1.mean():,.2f}\")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "# Plot feature importance\n", + "feature = X.columns\n", + "importance = pd.DataFrame({\n", + " 'feature': feature,\n", + " 'importance': model.feature_importances_\n", + "})\n", + "importance = importance.sort_values('importance', ascending=True).tail(10)\n", + "\n", + "plt.figure(figsize=(10, 6))\n", + "plt.barh(importance['feature'], importance['importance'])\n", + "plt.title('Top 10 Feature Importance')\n", + "plt.xlabel('Importance')\n", + "plt.tight_layout()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "# from plot above we notice that P_2 is the most important\n", + "print(\"The most imortant feature , the golde one :\\n(P_2)\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:\n", + "X = df[\"P_2\"]\n", + "\n", + "# Task 2,3,4,5: Write your code here:\n", + "\n", + "n_splits = 5 # K=5 Folds\n", + "\n", + "# Stratified 5-Fold Cross-Validation, shuffled\n", + "skf = StratifiedKFold(n_splits=n_splits, shuffle=True, random_state=42)\n", + "\n", + "# Storage for logistic regression results for each fold\n", + "\n", + "lr_accuracy_golden = []\n", + "lr_f1_golden = []\n", + "\n", + "model = CatBoostClassifier(\n", + " verbose=0,\n", + " n_estimators=320,\n", + " max_depth=4)\n", + "\n", + "for fold_idx, (train_index, test_index) in enumerate(skf.split(X, y)):\n", + " print(f\"\\nFold {fold_idx + 1}/{n_splits}\")\n", + "\n", + " # 1. Split data\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", + " # 2. Train & Validate sklearn models\n", + "\n", + "\n", + " model.fit(X_train, y_train) # train\n", + " y_pred = model.predict(X_test) # validate\n", + " y_pred.numpy()\n", + "\n", + " # 3. Save metrics for that model in this fold\n", + " accuracy = accuracy_score(y_test, y_pred)\n", + " f1 = f1_score(y_test, y_pred, zero_division=0)\n", + "\n", + " lr_f1.append(f1)\n", + " lr_accuracy.append(accuracy)\n", + "\n", + "\n", + "\n", + "lr_accuracy_golden = np.array(lr_accuracy_golden)\n", + "print(\"Model with golden feature : \\n\")\n", + "print(f\"\\nMAE: ${lr_accuracy_golden.mean():,.2f}\")\n", + "lr_f1_golden = np.array(lr_f1_golden)\n", + "print(f\"\\nMAE: ${lr_f1_golden.mean():,.2f}\")\n", + "\n", + "\n", + "\n", + "print(\"\\n\\nModel with all feature : \\n\")\n", + "print(f\"\\nMAE: ${lr_accuracy.mean():,.2f}\")\n", + "lr_f1 = np.array(lr_f1)\n", + "print(f\"\\nMAE: ${lr_f1.mean():,.2f}\")\n", + "\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/421/Q1.ipynb b/submissions_extracted/421/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..b8a024e82f451336220a42724eaf7179ee288353 --- /dev/null +++ b/submissions_extracted/421/Q1.ipynb @@ -0,0 +1,283 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q1-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "import numpy as np\n", + "import pandas as pd\n", + "import matplotlib.pyplot as plt\n", + "import os\n", + "import kagglehub\n", + "\n", + "df_path = os.path.join(path, 'Q1_data.csv')\n", + "my_df = pd.read_csv(df_path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "my_df.head(10)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "my_df.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "my_df.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "plt.figure(figsize=(10, 5))\n", + "plt.hist(my_df[\"Delivery_Time\"])\n", + "plt.title(\"Delivery Time\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "my_cleaned_df = my_df.drop(\"Order_ID\", axis = 1).copy()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "missing_percentage = (my_cleaned_df.isnull().sum() / len(my_cleaned_df)) * 100\n", + "missing_data = pd.DataFrame({\n", + " 'Column': missing_percentage.index,\n", + " 'Missing_Percentage': missing_percentage.values\n", + "})\n", + "# Not a lot of data is missing so dropping NA is approprite because data will still be enough\n", + "my_cleaned_df1 = my_cleaned_df.dropna()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "duplicates = my_cleaned_df1.duplicated().sum()\n", + "print(f\"Number of Duplicate Samples: {duplicates}\")\n", + "# LOTS ??!!!\n", + "my_cleaned_df1.drop_duplicates(inplace = True)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "from sklearn.preprocessing import LabelEncoder\n", + "# Task 4: Write your code here:\n", + "categorical_cols = my_cleaned_df1.select_dtypes(include=[\"object\"]).columns\n", + "print(categorical_cols)\n", + "label_encoders = {}\n", + "for col in categorical_cols:\n", + " le = LabelEncoder()\n", + " my_cleaned_df1[col] = le.fit_transform(my_cleaned_df1[col])\n", + " label_encoders[col] = le\n", + " # One-hot is too hard for me oops" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "from sklearn.preprocessing import StandardScaler\n", + "# Task 5: Write your code here:\n", + "scaler = StandardScaler()\n", + "my_columns = my_cleaned_df1.drop(\"Delivery_Time\", axis = 1).columns\n", + "my_cleaned_df1[my_columns] = scaler.fit_transform(my_cleaned_df1[my_columns])" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 6: Write your code here:\n", + "def check_target_imbalance(df, target_column):\n", + " print(\"Target Distribution:\")\n", + "\n", + " df[target_column].hist() # Yeah you can just do this :)\n", + " plt.show()\n", + "\n", + "check_target_imbalance(my_cleaned_df1, \"Delivery_Time\")\n", + "# it is so yeah......" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "X = my_cleaned_df1.drop(\"Delivery_Time\", axis=1)\n", + "y = my_cleaned_df1[\"Delivery_Time\"]" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:\n", + "from sklearn.model_selection import train_test_split , KFold # Not strat cause it is regression.... I think inshallah\n", + "from sklearn.ensemble import RandomForestRegressor\n", + "from sklearn.metrics import mean_absolute_error, mean_squared_error\n", + "\n", + "rf = RandomForestRegressor(\n", + " n_estimators=200, max_depth=20, random_state=42, n_jobs=-1\n", + ")\n", + "\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n", + "print(f\"Train: {X_train.shape}, Test: {X_test.shape}\")\n", + "\n", + "rf.fit(X_train, y_train)\n", + "y_pred = rf.predict(X_test)\n", + "# Without KFold\n", + "mae = mean_absolute_error(y_test, y_pred)\n", + "rmse = np.sqrt(mean_squared_error(y_test, y_pred))\n", + "\n", + "print(f\"MAE: ${mae:,.2f}\")\n", + "print(f\"RMSE: ${rmse:,.2f}\")\n", + "\n", + "kfold = KFold(n_splits=5, shuffle=True, random_state=42)\n", + "mae_scores = []\n", + "rmse_scores = []\n", + "\n", + "for train_idx, val_idx in kfold.split(X):\n", + " X_train, X_test = X.iloc[train_idx], X.iloc[val_idx]\n", + " y_train, y_test = y.iloc[train_idx], y.iloc[val_idx]\n", + " rf.fit(X_train, y_train)\n", + " y_pred = rf.predict(X_test)\n", + "\n", + " mae_scores.append(mean_absolute_error(y_test, y_pred))\n", + " rmse_scores.append(np.sqrt(mean_squared_error(y_test, y_pred)))\n", + "\n", + "\n", + "mae_scores = np.array(mae_scores)\n", + "rmse_scores = np.array(rmse_scores)\n", + "\n", + "print(f\"5-Fold CV Results:\")\n", + "print(f\"MAE: ${mae_scores.mean():,.2f}\")\n", + "print(f\"RMSE: ${rmse_scores.mean():,.2f}\")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "feature_importance = pd.DataFrame({\n", + " 'feature': my_columns,\n", + " 'importance': rf.feature_importances_\n", + "}).sort_values('importance', ascending=False)\n", + "\n", + "plt.figure(figsize=(10, 6))\n", + "plt.barh(feature_importance['feature'], feature_importance['importance'])\n", + "plt.xlabel('Importance')\n", + "plt.title('Feature Importance')\n", + "plt.gca().invert_yaxis()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "plt.figure(figsize=(6, 4))\n", + "plt.scatter(y_test, y_pred, alpha=0.7)\n", + "plt.plot([min(y_test), max(y_test)], [min(y_test), max(y_test)], 'r--', linewidth=2)\n", + "plt.xlabel(\"Actual y_test (Ground Truth)\")\n", + "plt.ylabel(\"Predicted y_pred (Linear Regression)\")\n", + "plt.title(\"Linear Regression: Predictions vs. Ground Truth\")\n", + "plt.grid(True)\n", + "\n", + "plt.tight_layout()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/421/Q2.ipynb b/submissions_extracted/421/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..5bdff4452bd569d21faa161c72d26c5b03330919 --- /dev/null +++ b/submissions_extracted/421/Q2.ipynb @@ -0,0 +1,317 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import torch\n", + "import torch.nn as nn\n", + "from torch.utils.data import DataLoader\n", + "from torch.optim import Adam\n", + "from torchvision.transforms.functional import to_tensor\n", + "import torch.nn.functional as F\n", + "import matplotlib.pyplot as plt" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q2-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import os\n", + "import pandas as pd\n", + "import numpy as np\n", + "from PIL import Image\n", + "from sklearn.model_selection import train_test_split\n", + "\n", + "# Load Labels\n", + "labels_df = pd.read_csv(os.path.join(path, \"labels.csv\"))\n", + "img_dir = os.path.join(path, \"images\")\n", + "\n", + "images = []\n", + "ages = []\n", + "\n", + "# Load Images and Resize\n", + "print(\"Loading images...\")\n", + "for index, row in labels_df.iterrows():\n", + " img_name = row.iloc[0]\n", + " age = row.iloc[1]\n", + " img_path = os.path.join(img_dir, img_name)\n", + "\n", + " if os.path.exists(img_path):\n", + " img = Image.open(img_path).convert('RGB')\n", + " img_array = np.array(img) / 255.0 # Normalize pixel values to [0, 1]\n", + " images.append(img_array)\n", + " ages.append(age)\n", + "\n", + "X = np.array(images)\n", + "y = np.array(ages)\n", + "\n", + "# Transpose image dimensions to match PyTorch format (N, C, H, W)\n", + "X = np.transpose(X, (0, 3, 1, 2))\n", + "\n", + "# Split Data\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n", + "\n", + "print(f\"X_train shape: {X_train.shape}\")\n", + "print(f\"X_test shape: {X_test.shape}\")\n", + "print(f\"y_train shape: {y_train.shape}\")\n", + "print(f\"y_test shape: {y_test.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 1. Convert Numpy arrays to PyTorch Tensors\n", + "\n", + "X_train_t = torch.tensor(X_train, dtype=torch.float32)\n", + "y_train_t = torch.tensor(y_train, dtype=torch.float32).view(-1, 1)\n", + "\n", + "X_test_t = torch.tensor(X_test, dtype=torch.float32)\n", + "y_test_t = torch.tensor(y_test, dtype=torch.float32).view(-1, 1)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "from torch.utils.data import TensorDataset\n", + "# 2. Create TensorDataset objects\n", + "train_ds = TensorDataset(X_train_t, y_train_t)\n", + "test_ds = TensorDataset(X_test_t, y_test_t)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 3. Create DataLoaders\n", + "\n", + "# DataLoader for training data\n", + "train_loader = DataLoader(train_ds, batch_size=32, shuffle=True)\n", + "test_loader = DataLoader(test_ds, batch_size=32, shuffle=False)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 4. Print shape of one batch\n", + "sample_batch_images, sample_batch_labels = next(iter(train_loader))\n", + "\n", + "print(f\"Batch image shape: {sample_batch_images.shape}\")\n", + "print(f\"Batch label shape: {sample_batch_labels.shape}\")\n", + "print(f\"First few labels in batch: {sample_batch_labels[:5]}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 5. Display sample images" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your model class here:\n", + "class NN4Layer(nn.Module):\n", + "\n", + " def __init__(self, input_dim, hidden_dim, output_dim):\n", + " super(NN4Layer, self).__init__()\n", + "\n", + " # First linear layer: input features -> hidden layer\n", + " self.layer1 = nn.Linear(input_dim, hidden_dim)\n", + "\n", + " # Second linear layer: hidden layer -> hidden layer\n", + " self.layer2 = nn.Linear(hidden_dim, hidden_dim)\n", + "\n", + " self.layer3 = nn.Linear(hidden_dim, hidden_dim)\n", + "\n", + " self.layer4 = nn.Linear(hidden_dim, 1)\n", + "\n", + " # ReLU activation for non-linearity\n", + " self.relu = nn.ReLU()\n", + "\n", + " # Defines how input data flows through the network\n", + " def forward(self, x):\n", + " # First hidden layer\n", + " z1 = self.layer1(x)\n", + " a1 = self.relu(z1)\n", + "\n", + " # Second hidden layer\n", + " z2 = self.layer2(a1)\n", + " a2 = self.relu(z2)\n", + "\n", + "\n", + " z3 = self.layer2(a2)\n", + " a3 = self.relu(z3)\n", + " # Output layer (raw scores / logits)\n", + " output = self.layer3(a3)\n", + "\n", + " return output\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your training loop here:\n", + "\n", + "def train_one_epoch(model, loader, criterion, optimizer, device):\n", + " model.train()\n", + " running_loss = 0.0\n", + "\n", + " for Xb, yb in loader:\n", + " Xb, yb = Xb.to(device), yb.to(device)\n", + "\n", + " optimizer.zero_grad()\n", + " pred = model(Xb)\n", + " loss = criterion(pred, yb)\n", + " loss.backward()\n", + " optimizer.step()\n", + "\n", + " running_loss += loss.item() * Xb.size(0)\n", + "\n", + " return running_loss / len(loader.dataset)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your validation loop here:\n", + "@torch.no_grad()\n", + "def validate(model, loader, criterion, device):\n", + " model.eval()\n", + " running_loss = 0.0\n", + "\n", + " for Xb, yb in loader:\n", + " Xb, yb = Xb.to(device), yb.to(device)\n", + " pred = model(Xb)\n", + " loss = criterion(pred, yb)\n", + " running_loss += loss.item() * Xb.size(0)\n", + "\n", + " return running_loss / len(loader.dataset)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Define device, model, loss, optimizer:\n", + "num_classes = int(np.unique(y_train).size)\n", + "\n", + "model = NN4Layer(input_dim=X_train_t.shape[1], hidden_dim=20, output_dim=num_classes).to(device)\n", + "\n", + "\n", + "device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n", + "print(\"Device:\", device)\n", + "\n", + "torch.manual_seed(42)\n", + "if torch.cuda.is_available():\n", + " torch.cuda.manual_seed_all(42)\n", + "\n", + "criterion = nn.CrossEntropyLoss()\n", + "optimizer = torch.optim.AdamW(model.parameters(), lr=1e-3)\n", + "\n", + "def accuracy_from_logits(logits, y_true):\n", + " preds = logits.argmax(dim=1)\n", + " return (preds == y_true).float().mean().item()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Start training for 20 epochs:input_dim = X_train_t.shape[1]\n", + "\n", + "epochs = 20\n", + "train_losses, val_losses = [], []\n", + "\n", + "for epoch in range(epochs):\n", + " tr = train_one_epoch(model, train_loader, criterion, optimizer, device)\n", + " va = validate(model, test_loader, criterion, device)\n", + " train_losses.append(tr); val_losses.append(va)\n", + "\n", + " print(f\"Epoch {epoch+1}/{epochs} | train={tr:.4f} | val={va:.4f}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "model.eval()\n", + "with torch.no_grad():\n", + " preds = model(X_test_t.to(device)).cpu().numpy().ravel()\n", + "\n", + "rmse = mean_squared_error(y_test.values, preds, squared=False)\n", + "mae = mean_absolute_error(y_test.values, preds)\n", + "r2 = r2_score(y_test.values, preds)\n", + "print(\"RMSE:\", rmse, \"MAE:\", mae, \"R2:\", r2)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2 (Bonus): Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/421/Q3.ipynb b/submissions_extracted/421/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..c32d03d9d5578786fcb6eef0a83b2ba7100d91e4 --- /dev/null +++ b/submissions_extracted/421/Q3.ipynb @@ -0,0 +1,188 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "%pip install CatBoost\n", + "import pandas as pd\n", + "import numpy as np\n", + "import matplotlib.pyplot as plt\n", + "import seaborn as sns\n", + "import kagglehub\n", + "import os\n", + "from catboost import CatBoostRegressor" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "\n", + "\n", + "# Download latest version\n", + "\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q3-exam-data\")\n", + "\n", + "\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "csv_path = os.path.join(path, \"Q3_data.csv\")\n", + "df = pd.read_csv(csv_path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "df.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "df.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "missing_percentage = (df.isnull().sum() / len(df)) * 100\n", + "missing_data = pd.DataFrame({\n", + " 'Column': missing_percentage.index,\n", + " 'Missing_Percentage': missing_percentage.values\n", + "}) # Since many columns have NA values I will drop them\n", + "print(missing_data)\n", + "columns_with_NA = missing_data[missing_data[\"Missing_Percentage\"].values> 10][\"Column\"]\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/422/Q1.ipynb b/submissions_extracted/422/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..0d2bcc2ad84795f9394b72e86f002e76027e3ec1 --- /dev/null +++ b/submissions_extracted/422/Q1.ipynb @@ -0,0 +1,317 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "import numpy as np\n", + "import pandas as pd\n", + "import matplotlib.pyplot as plt\n", + "import os\n", + "import kagglehub\n", + "import seaborn as sns\n", + "\n", + "from sklearn.model_selection import train_test_split, KFold\n", + "from sklearn.preprocessing import StandardScaler, LabelEncoder\n", + "from sklearn.ensemble import RandomForestRegressor\n", + "from sklearn.metrics import mean_absolute_error, mean_squared_error\n", + "from sklearn.model_selection import StratifiedKFold\n", + "from sklearn.model_selection import KFold, StratifiedKFold, cross_val_score\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q1-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "food_path = os.path.join(path, 'Q1_data.csv')\n", + "df_food = pd.read_csv(food_path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "df_food.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "df_food.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "df_food.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "def check_target_distribution(df, target_column):\n", + " df[target_column].hist(bins=30, edgecolor='black')\n", + "\n", + " plt.title(f\"Target Distribution ({target_column})\")\n", + " plt.xlabel(target_column)\n", + " plt.ylabel(\"Frequency\")\n", + " plt.grid(False)\n", + "\n", + " plt.show()\n", + "\n", + "check_target_distribution(df_food, \"Delivery_Time\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "df_food.drop(columns=['Order_ID'])" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "#df_food.shape()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "missing_percentage = (df_food.isnull().sum() / len(df_food)) * 100\n", + "missing_data = pd.DataFrame({\n", + " 'Column': missing_percentage.index,\n", + " 'Missing_Percentage': missing_percentage.values\n", + "})\n", + "missing_data = missing_data[missing_data['Missing_Percentage'] > 0].sort_values('Missing_Percentage',ascending=False)\n", + "\n", + "print(\"Missing Data Analysis:\")\n", + "missing_data.head(20)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "\n", + "print(\"Missing values before cleaning:\")\n", + "print(df_food.isnull().sum())\n", + "df_food['Delivery_Time'] = df_food['Delivery_Time'].fillna(df_food['Delivery_Time'].mean())\n", + "df_food['Weather']=df_food['Weather'].fillna(df_food['Weather'].mode()[0])\n", + "df_food['Traffic_Level']=df_food['Traffic_Level'].fillna(df_food['Traffic_Level'].mode()[0])\n", + "df_food['Time_of_Day']=df_food['Time_of_Day'].fillna(df_food['Time_of_Day'].mode()[0])\n", + "df_food['Courier_Experience_yrs']=df_food['Courier_Experience_yrs'].fillna(df_food['Courier_Experience_yrs'].mean())\n", + "\n", + "print(\"Missing values after cleaning:\")\n", + "print(df_food.isnull().sum())" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "duplicates = df_food.duplicated().sum()\n", + "print(f\"Number of duplicate rows: {duplicates}\")\n", + "\n", + "if duplicates > 0:\n", + " df_food.drop_duplicates(inplace=True)\n", + " print(f\"Removed {duplicates} duplicate rows\")\n", + "else:\n", + " print(\"No duplicates found!\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "\n", + "categorical_cols = ['Weather', 'Traffic_Level', 'Time_of_Day', 'Vehicle_Type']\n", + "for col in categorical_cols:\n", + " le = LabelEncoder()\n", + " df_food[col] = le.fit_transform(df_food[col].astype(str))\n", + "\n", + "df_food.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "numerical_cols = df_food.select_dtypes(include=[\"int64\", \"float64\"]).columns.drop(\"Delivery_Time\") # DON'T SCALE THE TARGET\n", + "\n", + "scaler = StandardScaler()\n", + "df_food[numerical_cols] = scaler.fit_transform(df_food[numerical_cols])\n", + "df_food.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 6: Write your code here:\n", + "\n", + "\n", + "def check_target_imbalance(df, target_column):\n", + " print(\"Target Distribution:\")\n", + " print(df[target_column].value_counts(normalize=True))\n", + " sns.countplot(x=df[target_column])\n", + " plt.title(\"Target Distribution\")\n", + " print(f\"Legendary: {df_food['Delivery_Time'].sum()}\")\n", + " print(f\"Normal: {(df_food['Delivery_Time'] == 0).sum()}\")\n", + " plt.show()\n", + "\n", + "check_target_imbalance(df_food, \"Delivery_Time\")\n", + "\n", + "\n", + "#imbalance" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "X = df_food.drop(\"Delivery_Time\",axis=1)\n", + "y = df_food['Delivery_Time'].astype(float)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:\n", + "model = RandomForestRegressor(n_estimators=200)\n", + "kf = KFold(n_splits=5, shuffle=True, random_state=42)\n", + "\n", + "# Iterate through folds\n", + "for fold, (train_idx, test_idx) in enumerate(kf.split(X), start=1):\n", + " # indexing for each fold\n", + " X_train, X_test = X.iloc[train_idx], X.iloc[test_idx]\n", + " y_train, y_test = y.iloc[train_idx], y.iloc[test_idx]\n", + " # print shapes\n", + " print(f\"Fold {fold}\")\n", + " print(\" X_train shape:\", X_train.shape)\n", + " print(\" X_test shape :\", X_test.shape)\n", + " print(\" y_train shape:\", y_train.shape)\n", + " print(\" y_test shape :\", y_test.shape)\n", + " print(\"-\" * 30)\n", + "\n", + "model.fit(X_train, y_train)\n", + "y_pred = model.predict(X_test)\n", + "mae = mean_absolute_error(y_test, y_pred)\n", + "\n", + "\n", + "print(\"MAE :\", mae)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "importance = model({\n", + " 'feature': features,\n", + " 'importance': model.feature_importances_\n", + "})\n", + "importance = importance.sort_values('importance', ascending=True).tail(10)\n", + "\n", + "plt.figure(figsize=(10, 6))\n", + "plt.barh(importance['feature'], importance['importance'])\n", + "plt.title('Top 10 Feature Importance')\n", + "plt.xlabel('Importance')\n", + "plt.tight_layout()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/422/Q2.ipynb b/submissions_extracted/422/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..15fa2e5d406e0a1ff644e53f3318d06992a34cac --- /dev/null +++ b/submissions_extracted/422/Q2.ipynb @@ -0,0 +1,380 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q2-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import os\n", + "import pandas as pd\n", + "import numpy as np\n", + "from PIL import Image\n", + "from sklearn.model_selection import train_test_split\n", + "\n", + "import torch\n", + "import torch.nn as nn\n", + "from torch.optim import AdamW\n", + "import matplotlib.pyplot as plt\n", + "from torch.utils.data import DataLoader, TensorDataset\n", + "from sklearn.model_selection import train_test_split\n", + "from sklearn.preprocessing import StandardScaler, LabelEncoder\n", + "from sklearn.metrics import mean_absolute_error, mean_squared_error, r2_score\n", + "\n", + "\n", + "# Load Labels\n", + "labels_df = pd.read_csv(os.path.join(path, \"labels.csv\"))\n", + "img_dir = os.path.join(path, \"images\")\n", + "\n", + "images = []\n", + "ages = []\n", + "\n", + "# Load Images and Resize\n", + "print(\"Loading images...\")\n", + "for index, row in labels_df.iterrows():\n", + " img_name = row.iloc[0]\n", + " age = row.iloc[1]\n", + " img_path = os.path.join(img_dir, img_name)\n", + "\n", + " if os.path.exists(img_path):\n", + " img = Image.open(img_path).convert('RGB')\n", + " img_array = np.array(img) / 255.0 # Normalize pixel values to [0, 1]\n", + " images.append(img_array)\n", + " ages.append(age)\n", + "\n", + "X = np.array(images)\n", + "y = np.array(ages)\n", + "\n", + "# Transpose image dimensions to match PyTorch format (N, C, H, W)\n", + "X = np.transpose(X, (0, 3, 1, 2))\n", + "\n", + "# Split Data\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n", + "\n", + "print(f\"X_train shape: {X_train.shape}\")\n", + "print(f\"X_test shape: {X_test.shape}\")\n", + "print(f\"y_train shape: {y_train.shape}\")\n", + "print(f\"y_test shape: {y_test.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "type(X_train)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 1. Convert Numpy arrays to PyTorch Tensors\n", + "\n", + "X_train = torch.tensor(X_train.values, dtype=torch.float32)\n", + "X_test = torch.tensor(X_test.values, dtype=torch.float32)\n", + "y_train = torch.tensor(y_train.values, dtype=torch.long)\n", + "y_test = torch.tensor(y_test.values, dtype=torch.long)\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 2. Create TensorDataset objects\n", + "\n", + "# Create TensorDatasets for training and testing\n", + "train_dataset = TensorDataset(X_train, y_train)\n", + "test_dataset = TensorDataset(X_test, y_test)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 3. Create DataLoaders\n", + "train_loader = DataLoader( train_dataset, batch_size=32, shuffle=True, num_workers=2)\n", + "# DataLoader for test data\n", + "test_loader = DataLoader( test_dataset, batch_size=32, shuffle=False, num_workers=2)\n", + "\n", + "# Get the first batch from the training DataLoader\n", + "X_batch, y_batch = next(iter(train_loader))\n", + "print(f\"Training batch input shape: {X_batch.shape}\")\n", + "print(f\"Training batch labels shape: {y_batch.shape}\")\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 4. Print shape of one batch\n", + "images, labels = next(iter(train_loader))\n", + "\n", + "# Display the first 6 images in the batch\n", + "plt.figure(figsize=(8, 4))\n", + "\n", + "for i in range(6):\n", + " plt.subplot(2, 3, i + 1)\n", + "\n", + " # Convert from (C, H, W) to (H, W, C) for matplotlib\n", + " img = images[i].permute(1, 2, 0)\n", + "\n", + " plt.imshow(img)\n", + " plt.title(f\"Label: {labels[i].item()}\")\n", + " plt.axis('off')\n", + "\n", + "plt.tight_layout()\n", + "plt.show()\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 5. Display sample images\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your model class here:\n", + "class NN4Layer(nn.Module):\n", + "\n", + " def __init__(self, input_dim, hidden_dim, output_dim):\n", + " super(NN4Layer, self).__init__()\n", + "\n", + " # First linear layer: input features -> hidden layer\n", + " self.layer1 = nn.Linear(input_dim, hidden_dim)\n", + "\n", + " # Second linear layer: hidden layer -> hidden layer\n", + " self.layer2 = nn.Linear(hidden_dim, hidden_dim)\n", + "\n", + " # Third linear layer: hidden layer -> hidden layer\n", + " self.layer3 = nn.Linear(hidden_dim, hidden_dim)\n", + "\n", + " # Output layer: hidden layer -> number of classes (logits)\n", + " self.layer4 = nn.Linear(hidden_dim, output_dim)\n", + "\n", + " # ReLU activation for non-linearity\n", + " self.relu = nn.ReLU()\n", + "\n", + " # Defines how input data flows through the network\n", + " def forward(self, x):\n", + " # First hidden layer\n", + " a1 = self.relu(self.layer1(x))\n", + "\n", + " # Second hidden layer\n", + " a2 = self.relu(self.layer2(a1))\n", + "\n", + " # Third hidden layer\n", + " a3 = self.relu(self.layer3(a2))\n", + "\n", + " # Output layer (raw scores / logits)\n", + " output = self.layer4(a3) # we said we'll use softmax, where is it? ¯\\(ツ)/¯\n", + "\n", + " return output" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your training loop here:\n", + "def train_one_epoch(model, optimizer, criterion, train_loader, device):\n", + " # Set the model to training mode\n", + " model.train()\n", + "\n", + " running_loss = 0.0\n", + "\n", + " for X_batch, y_batch in train_loader:\n", + " # Move batch to the selected device\n", + " X_batch = X_batch.to(device) # shape: (batch_size, num_features)\n", + " y_batch = y_batch.to(device) # shape: (batch_size,)\n", + "\n", + " # Forward pass (outputs are logits)\n", + " outputs = model(X_batch) # shape: (batch_size, num_classes)\n", + " loss = criterion(outputs, y_batch)\n", + "\n", + " # Backward pass & optimization\n", + " optimizer.zero_grad() # Clear previous gradients\n", + " loss.backward() # Compute gradients\n", + " optimizer.step() # Update model parameters\n", + "\n", + " running_loss += loss.item()\n", + "\n", + " # Average loss over all batches\n", + " avg_loss = running_loss / len(train_loader)\n", + "\n", + " return avg_loss" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your validation loop here:\n", + "def validate(model, criterion, test_loader, device):\n", + " # Set the model to evaluation mode\n", + " model.eval()\n", + "\n", + " running_loss = 0.0\n", + " correct = 0\n", + " total = 0\n", + "\n", + " with torch.no_grad():\n", + " for X_batch, y_batch in test_loader:\n", + " # Move data to device\n", + " X_batch = X_batch.to(device) # shape: (batch_size, num_features)\n", + " y_batch = y_batch.to(device) # shape: (batch_size,)\n", + "\n", + " # Forward pass\n", + " outputs = model(X_batch) # shape: (batch_size, num_classes)\n", + " loss = criterion(outputs, y_batch)\n", + " running_loss += loss.item()\n", + "\n", + " # Apply Softmax to get probabilities\n", + " probabilities = F.softmax(outputs, dim=1)\n", + "\n", + " # Pick the classes with highest probabilities\n", + " predicted = torch.argmax(probabilities, dim=1)\n", + "\n", + " # Accuracy calculation\n", + " correct += (predicted == y_batch).sum().item()\n", + " total += y_batch.size(0)\n", + "\n", + " avg_loss = running_loss / len(test_loader)\n", + " accuracy = correct / total\n", + "\n", + " return avg_loss, accuracy" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Define device, model, loss, optimizer:\n", + "# Device setup\n", + "device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n", + "\n", + "# Model parameters\n", + "input_dim = X_train.shape[1] # Number of tabular features\n", + "hidden_dim = 14 # Design choice\n", + "output_dim = 4 # Weather classes: Rainy, Sunny, Cloudy, Snowy\n", + "\n", + "# Instantiate model\n", + "model = NN4Layer(input_dim, hidden_dim, output_dim).to(device)\n", + "\n", + "# Print the model architecture\n", + "print(\"Model Architecture:\\n\")\n", + "print(model)\n", + "\n", + "# Calculate the total number of trainable parameters\n", + "total_params = sum(p.numel() for p in model.parameters() if p.requires_grad)\n", + "print(f\"\\nTotal trainable parameters: {total_params}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Start training for 20 epochs:\n", + "num_epochs = 20\n", + "learning_rate = 0.001\n", + "\n", + "# Define criterion (loss function) - using CrossEntropyLoss as model now outputs logits\n", + "criterion = nn.CrossEntropyLoss()\n", + "# Define optimizer\n", + "optimizer = AdamW(model.parameters(), learning_rate)\n", + "\n", + "\n", + "train_losses = []\n", + "val_losses = []\n", + "val_accuracies = []\n", + "\n", + "print('Starting Training...')\n", + "for epoch in range(num_epochs):\n", + " # Train one epoch\n", + " train_loss = train_one_epoch(model, optimizer, criterion, train_loader, device)\n", + "\n", + " # Validate\n", + " val_loss, val_accuracy = validate(model, criterion, test_loader, device)\n", + "\n", + " train_losses.append(train_loss)\n", + " val_losses.append(val_loss)\n", + " val_accuracies.append(val_accuracy)\n", + "\n", + " print(f'Epoch [{epoch+1}/{num_epochs}], Train Loss: {train_loss:.4f}, Val Loss: {val_loss:.4f}, Val Accuracy: {val_accuracy:.4f}')\n", + "\n", + "print('Training Complete!')" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2 (Bonus): Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/423/Q1.ipynb b/submissions_extracted/423/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..1c18bf8e1d39d773ab34fb4d22b0ae621ab9df6d --- /dev/null +++ b/submissions_extracted/423/Q1.ipynb @@ -0,0 +1,262 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "import numpy as np\n", + "import pandas as pd\n", + "import matplotlib.pyplot as plt\n", + "import os\n", + "import kagglehub\n", + "\n", + "from sklearn.model_selection import train_test_split, StratifiedKFold, cross_val_score\n", + "from sklearn.preprocessing import StandardScaler, LabelEncoder\n", + "from sklearn.ensemble import RandomForestClassifier\n", + "from sklearn.metrics import classification_report, confusion_matrix, accuracy_score\n", + "\n", + "import warnings\n", + "warnings.filterwarnings('ignore')\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q1-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "## Task: Predict Food Delivery Time\n", + "deliverypath= os.path.join(path, 'Q1_data.csv')\n", + "df_delivery = pd.read_csv(deliverypath)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "df_delivery.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "df_delivery.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "df_delivery.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Delivery_Time distribution\n", + "plt.figure(figsize=(10, 5))\n", + "plt.hist(df_delivery['Delivery_Time'].dropna(), bins=30, edgecolor='black')\n", + "plt.title('Delivery_Time Distribution')\n", + "plt.xlabel('Delivery_Time')\n", + "plt.ylabel('Frequency')\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "df_delivery=df_delivery.drop(columns=\"Order_ID\", axis=1)\n", + "df_delivery" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "def check_missing_values(df):\n", + " missing_values = df.isnull().sum()\n", + " print(\"Missing Values per Column:\")\n", + " print(missing_values[missing_values > 0])\n", + " if missing_values.any():\n", + " print(\"\\nHandle Missing Values as needed.\")\n", + " else:\n", + " print(\"\\nNo Missing Values Found.\")\n", + "\n", + "check_missing_values(df_delivery)\n", + "\n", + "colsWNan=['Weather', 'Traffic_Level', 'Time_of_Day', 'Courier_Experience_yrs', 'Delivery_Time']\n", + "\n", + "df_clean = df_delivery.dropna(subset=colsWNan).copy()\n", + "\n", + "check_missing_values(df_clean)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "def check_duplicates(df):\n", + " duplicates = df.duplicated().sum()\n", + " print(f\"Number of Duplicate Samples: {duplicates}\")\n", + " if duplicates > 0:\n", + " print(\"Dropping Duplicates...\")\n", + " df.drop_duplicates(inplace=True)\n", + " print(\"Duplicates Dropped.\")\n", + " else:\n", + " print(\"No Duplicate Samples Found.\")\n", + "\n", + "check_duplicates(df_clean)\n", + "print('-'*20)\n", + "check_duplicates(df_clean)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Encode categorical columns - converts text to integers\n", + "categorical_cols = ['Traffic_Level', 'Time_of_Day', 'Vehicle_Type', 'Weather']\n", + "for col in categorical_cols:\n", + " le = LabelEncoder()\n", + " df_clean[col] = le.fit_transform(df_clean[col].astype(str))\n", + "\n", + "df_clean.head()\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "#scaler = StandardScaler()\n", + "#df_scaled = scaler.fit_transform(df_clean)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "def check_target_imbalance(df, target_column):\n", + " print(\"Target Distribution:\")\n", + "\n", + " df[target_column].hist()\n", + " plt.show()\n", + "\n", + "check_target_imbalance(df_clean, \"Delivery_Time\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "feature_cols=['Courier_Experience_yrs', 'Preparation_Time_min', 'Vehicle_Type', 'Vehicle_Type'\n", + ", 'Time_of_Day', 'Traffic_Level', 'Weather', 'Distance_km',]\n", + "\n", + "X=df_clean[feature_cols]\n", + "y=df_clean['Delivery_Time']\n", + "\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n", + "print(f\"Train: {X_train.shape}, Test: {X_test.shape}\")\n", + "\n", + "scaler = StandardScaler()\n", + "X_train_scaled = scaler.fit_transform(X_train)\n", + "X_test_scaled = scaler.transform(X_test)\n", + "\n", + "model = RandomForestClassifier(n_estimators=100, max_depth=15,\n", + " class_weight='balanced', random_state=42)\n", + "model.fit(X_train_scaled, y_train)\n", + "print(\"Model trained!\")\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Feature importance\n", + "importance = pd.DataFrame({\n", + " 'feature': feature_cols,\n", + " 'importance': model.feature_importances_\n", + "}).sort_values('importance', ascending=False)\n", + "\n", + "plt.figure(figsize=(10, 6))\n", + "plt.barh(importance['feature'], importance['importance'], color='purple')\n", + "plt.xlabel('Importance')\n", + "plt.title('Feature Importance')\n", + "plt.gca().invert_yaxis()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/423/Q2.ipynb b/submissions_extracted/423/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..117721d91d4a44da92edb43024a20b77d2b09255 --- /dev/null +++ b/submissions_extracted/423/Q2.ipynb @@ -0,0 +1,360 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q2-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import os\n", + "import pandas as pd\n", + "import numpy as np\n", + "from PIL import Image\n", + "from sklearn.model_selection import train_test_split\n", + "import kagglehub\n", + "import torch\n", + "import torch.nn as nn\n", + "from torch.optim import Adam\n", + "import matplotlib.pyplot as plt\n", + "from torch.utils.data import DataLoader, TensorDataset\n", + "from sklearn.model_selection import train_test_split\n", + "from sklearn.preprocessing import StandardScaler, LabelEncoder\n", + "from sklearn.metrics import mean_absolute_error, mean_squared_error, r2_score\n", + "import torch.nn.functional as F\n", + "\n", + "# Load Labels\n", + "labels_df = pd.read_csv(os.path.join(path, \"labels.csv\"))\n", + "img_dir = os.path.join(path, \"images\")\n", + "\n", + "images = []\n", + "ages = []\n", + "\n", + "# Load Images and Resize\n", + "print(\"Loading images...\")\n", + "for index, row in labels_df.iterrows():\n", + " img_name = row.iloc[0]\n", + " age = row.iloc[1]\n", + " img_path = os.path.join(img_dir, img_name)\n", + "\n", + " if os.path.exists(img_path):\n", + " img = Image.open(img_path).convert('RGB')\n", + " img_array = np.array(img) / 255.0 # Normalize pixel values to [0, 1]\n", + " images.append(img_array)\n", + " ages.append(age)\n", + "\n", + "X = np.array(images)\n", + "y = np.array(ages)\n", + "\n", + "# Transpose image dimensions to match PyTorch format (N, C, H, W)\n", + "X = np.transpose(X, (0, 3, 1, 2))\n", + "\n", + "# Split Data\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n", + "\n", + "print(f\"X_train shape: {X_train.shape}\")\n", + "print(f\"X_test shape: {X_test.shape}\")\n", + "print(f\"y_train shape: {y_train.shape}\")\n", + "print(f\"y_test shape: {y_test.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "X_test = torch.tensor(X_test, dtype=torch.float32)\n", + "y_train = torch.tensor(y_train, dtype=torch.float32)\n", + "X_train = torch.tensor(X_train, dtype=torch.float32)\n", + "y_test = torch.tensor(y_test, dtype=torch.float32)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "train_dataset = TensorDataset(X_train, y_train)\n", + "test_dataset = TensorDataset(X_test, y_test)\n", + "\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "train_loader = DataLoader(train_dataset, batch_size=32, shuffle=True)\n", + "test_loader = DataLoader(test_dataset, batch_size=32, shuffle=False)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "X_batch, y_batch = next(iter(train_loader))\n", + "print(f\"Training batch input shape: {X_batch.shape}\")\n", + "print(f\"Training batch labels shape: {y_batch.shape}\")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Get one batch of images and labels\n", + "images, labels = next(iter(train_loader))\n", + "\n", + "# Display the first 6 images in the batch\n", + "plt.figure(figsize=(8, 4))\n", + "\n", + "for i in range(6):\n", + " plt.subplot(2, 3, i + 1)\n", + "\n", + " # Convert from (C, H, W) to (H, W, C) for matplotlib\n", + " img = images[i].permute(1, 2, 0)\n", + "\n", + " plt.imshow(img)\n", + " plt.title(f\"Label: {labels[i].item()}\")\n", + " plt.axis('off')\n", + "\n", + "plt.tight_layout()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "class NN4Layer(nn.Module):\n", + "\n", + " def __init__(self, input_dim, hidden_dim, output_dim):\n", + " super(NN4Layer, self).__init__()\n", + "\n", + " # First linear layer: input features -> hidden layer\n", + " self.layer1 = nn.Linear(input_dim, hidden_dim)\n", + "\n", + " # Second linear layer: hidden layer -> hidden layer\n", + " self.layer2 = nn.Linear(hidden_dim, hidden_dim)\n", + "\n", + " # Output layer: hidden layer -> number of classes (logits)\n", + " self.layer3 = nn.Linear(hidden_dim, output_dim)\n", + "\n", + " # Output layer: hidden layer -> number of classes (logits)\n", + " self.layer4 = nn.Linear(hidden_dim, output_dim)\n", + " # ReLU activation for non-linearity\n", + " self.relu = nn.ReLU()\n", + "\n", + " # Defines how input data flows through the network\n", + " def forward(self, x):\n", + " # First hidden layer\n", + " z1 = self.layer1(x)\n", + " a1 = self.relu(z1)\n", + "\n", + " # Second hidden layer\n", + " z2 = self.layer2(a1)\n", + " a2 = self.relu(z2)\n", + "\n", + " # third hidden layer\n", + " z3 = self.layer2(a2)\n", + " a3 = self.relu(z1)\n", + " # Output layer (raw scores / logits)\n", + " output = self.layer3(a3) # there is something missing here, remember? :)\n", + "\n", + " return output\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "def train_one_epoch(model, optimizer, criterion, train_loader, device):\n", + " # Set the model to training mode\n", + " model.train()\n", + "\n", + " running_loss = 0.0\n", + "\n", + " for X_batch, y_batch in train_loader:\n", + " # Move batch to the selected device\n", + " X_batch = X_batch.view(X_batch.size(0), -1).to(device)\n", + " y_batch = y_batch.to(device)\n", + "\n", + " # Forward pass\n", + " # TODO: make predictions\n", + " outputs = model(X_batch) # shape: (batch_size, 10)\n", + " # TODO: compute loss\n", + " loss = criterion(outputs, y_batch)\n", + "\n", + " # Backward pass & optimization\n", + " optimizer.zero_grad() # Clear previous gradients\n", + " loss.backward() # Compute gradients\n", + " optimizer.step() # Update model parameters\n", + "\n", + " running_loss += loss.item()\n", + "\n", + " # Average loss over all batches\n", + " avg_loss = running_loss / len(train_loader)\n", + "\n", + " return avg_loss" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "def validate(model, criterion, test_loader, device):\n", + " # Set the model to evaluation mode\n", + " model.eval()\n", + "\n", + " running_loss = 0.0\n", + " correct = 0\n", + " total = 0\n", + "\n", + " with torch.no_grad():\n", + " for X_batch, y_batch in test_loader:\n", + " # Move data to device\n", + " X_batch = X_batch.view(X_batch.size(0), -1).to(device)\n", + " y_batch = y_batch.to(device)\n", + "\n", + " # Forward pass\n", + " # TODO: make predictions\n", + " outputs = model(X_batch) # shape: (batch_size, 10)\n", + " # TODO: compute loss\n", + " loss = criterion(outputs, y_batch)\n", + " running_loss += loss.item()\n", + "\n", + " # TODO: Apply Softmax to get probabilities\n", + " probabilities = F.softmax(outputs, dim=1)\n", + "\n", + " # TODO: Multiclass predictions\n", + " predicted = torch.argmax(probabilities, dim=1)\n", + "\n", + " # Accuracy calculation\n", + " correct += (predicted == y_batch).sum().item()\n", + " total += y_batch.size(0)\n", + "\n", + " avg_loss = running_loss / len(test_loader)\n", + " # TODO: how do we calculate accuracy?\n", + " accuracy = correct / total\n", + "\n", + " return avg_loss, accuracy\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n", + "# Model parameters\n", + "input_dim = 36 * 36 *3 #\n", + "hidden_dim = 64 # Design choice\n", + "output_dim = 80 #\n", + "\n", + "model = NN4Layer(input_dim, hidden_dim, output_dim).to(device)\n", + "\n", + "num_epochs = 20\n", + "learning_rate = 0.001\n", + "\n", + "criterion=nn.CrossEntropyLoss()\n", + "\n", + "optimizer = Adam(model.parameters(), learning_rate)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Run Training\n", + "train_losses = []\n", + "val_losses = []\n", + "val_accuracies = []\n", + "\n", + "print('Starting Training...')\n", + "for epoch in range(num_epochs):\n", + " # Train one epoch\n", + " train_loss = train_one_epoch(model, optimizer, criterion, train_loader, device)\n", + "\n", + " # Validate\n", + " val_loss, val_accuracy = validate(model, criterion, test_loader, device)\n", + "\n", + " train_losses.append(train_loss)\n", + " val_losses.append(val_loss)\n", + " val_accuracies.append(val_accuracy)\n", + "\n", + " print(f'Epoch [{epoch+1}/{num_epochs}], Train Loss: {train_loss:.4f}, Val Loss: {val_loss:.4f}, Val Accuracy: {val_accuracy:.4f}')\n", + "\n", + "print('Training Complete!')" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Plotting results\n", + "plt.figure(figsize=(7, 5))\n", + "\n", + "plt.plot(train_losses, label='Train Loss')\n", + "plt.plot(val_losses, label='Validation Loss')\n", + "plt.title('Loss over Epochs')\n", + "plt.xlabel('Epoch')\n", + "plt.ylabel('Loss')\n", + "plt.legend()\n", + "\n", + "plt.tight_layout()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2 (Bonus): Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/423/Q3.ipynb b/submissions_extracted/423/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..3ae8ab56b0b4d8a143a16adfdbd13dba78d65866 --- /dev/null +++ b/submissions_extracted/423/Q3.ipynb @@ -0,0 +1,215 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "import numpy as np\n", + "import pandas as pd\n", + "import matplotlib.pyplot as plt\n", + "import os\n", + "from sklearn.model_selection import train_test_split, StratifiedKFold, cross_val_score\n", + "from sklearn.preprocessing import StandardScaler, LabelEncoder\n", + "from sklearn.ensemble import RandomForestClassifier\n", + "from sklearn.metrics import classification_report, confusion_matrix, accuracy_score\n", + "import warnings\n", + "warnings.filterwarnings('ignore')\n", + "# Download latest version\n", + "\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q3-exam-data\")\n", + "\n", + "\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "os.listdir(path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "credit_path = os.path.join(path, 'Q3_data.csv')\n", + "df_credit = pd.read_csv(credit_path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "df_credit.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "df_credit.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "df_credit.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Missing values\n", + "print(\"Missing values:\")\n", + "print(df_credit.isnull().sum())\n", + "\n", + "\n", + "print(df_credit.columns)\n", + "\n", + "for col in df_credit.columns:\n", + "\n", + " if(df_credit)\n", + " df_credit=df_credit[col].fillna(df_credit[col].mean())\n", + "\n", + "print(df_credit.isnull().sum())\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "def check_duplicates(df):\n", + " duplicates = df.duplicated().sum()\n", + " print(f\"Number of Duplicate Samples: {duplicates}\")\n", + " if duplicates > 0:\n", + " print(\"Dropping Duplicates...\")\n", + " df.drop_duplicates(inplace=True)\n", + " print(\"Duplicates Dropped.\")\n", + " else:\n", + " print(\"No Duplicate Samples Found.\")\n", + "\n", + "check_duplicates(df_credit)\n", + "print('-'*20)\n", + "check_duplicates(df_credit)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "categorical_cols = df_credit.select_dtypes(include=[\"object\"]).columns\n", + "\n", + "for col in categorical_cols:\n", + " print(f\"Encoding column: {col}\")\n", + " le = LabelEncoder()\n", + " # TODO: Apply fit_transform to encode the column\n", + " df_credit[col] = le.fit_transform(check_duplicates[col])\n", + "\n", + "df_credit.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "def check_target_imbalance(df, target_column):\n", + " print(\"Target Distribution:\")\n", + "\n", + " df[target_column].hist()\n", + " plt.show()\n", + "\n", + "check_target_imbalance(df_credit, \"Delivery_Time\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/424/Q1.ipynb b/submissions_extracted/424/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..6383966a0dcafb82f99ed481e76a0ca9dcdc763f --- /dev/null +++ b/submissions_extracted/424/Q1.ipynb @@ -0,0 +1,488 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q1-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import numpy as np\n", + "import pandas as pd\n", + "import matplotlib.pyplot as plt\n", + "import os\n", + "import kagglehub\n", + "\n", + "from sklearn.model_selection import train_test_split, KFold\n", + "from sklearn.preprocessing import StandardScaler, LabelEncoder\n", + "from sklearn.ensemble import RandomForestRegressor\n", + "from sklearn.metrics import mean_absolute_error, mean_squared_error\n", + "\n", + "import warnings\n", + "warnings.filterwarnings('ignore')\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "food_path = os.path.join(path, 'Q1_data.csv')\n", + "df_food = pd.read_csv(food_path)\n", + "\n", + "print(f\"Dataset shape: {df_food.shape}\")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "df_food.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "df_food.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "df_food.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "plt.figure(figsize=(10, 5))\n", + "plt.hist(df_food['Delivery_Time'].dropna(), bins=30, edgecolor='black', color='blue')\n", + "plt.title('Delivery_Time Distribution')\n", + "plt.xlabel('Delivery_Time')\n", + "plt.ylabel('Frequency')\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "df = df_food.drop(columns=['Order_ID'])" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "df_food.isna().any()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "df = df_food['Traffic_Level'].fillna(df_food['Traffic_Level'].mode()[0])\n", + "df = df_food['Weather'].fillna(df_food['Weather'].mode()[0])\n", + "df = df_food['Time_of_Day'].fillna(df_food['Time_of_Day'].mode()[0])\n", + "df = df_food['Courier_Experience_yrs'].fillna(df_food['Courier_Experience_yrs'].mean())\n", + "df" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "df.isna().any()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "df.duplicated().any()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "df = df_food.drop_duplicates()\n", + "df.duplicated().any()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "df" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "df" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "categorical_cols = ['Weather', 'Traffic_Level', 'Time_of_Day', 'Vehicle_Type']\n", + "for col in categorical_cols:\n", + " le = LabelEncoder()\n", + " df[col] = le.fit_transform(df[col].astype(str))\n", + "\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "feature_cols = ['Distance_km',\t'Weather',\t'Traffic_Level',\t'Time_of_Day',\t'Vehicle_Type',\t'Preparation_Time_min',\t'Courier_Experience_yrs']\n", + "X = df[feature_cols]\n", + "y = df['Delivery_Time']\n", + "\n", + "# Train-test split (80% train, 20% test)\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n", + "print(f\"Train: {X_train.shape}, Test: {X_test.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "print(f\"\\nFeature ranges - Min: {X_train.min().min():.2f}, Max: {X_train.max().max():.2f}\")\n", + "X_train.head(3)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 6: Write your code here:\n", + "def check_target_imbalance(df, target_column):\n", + " print(\"Target Distribution:\")\n", + "\n", + " df[target_column].hist() # Yeah you can just do this :)\n", + " plt.show()\n", + "\n", + "check_target_imbalance(df, \"Delivery_Time\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here: i allready did it before scaling" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "df.isna().any()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "df.dropna()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:\n", + "from sklearn.linear_model import Ridge, Lasso\n", + "from sklearn.svm import SVR\n", + "from sklearn.tree import DecisionTreeRegressor\n", + "from sklearn.ensemble import RandomForestRegressor\n", + "from lightgbm import LGBMRegressor\n", + "models = {\n", + " \"Ridge Regression\": Ridge(alpha=1.0, max_iter=10000),\n", + " \"LASSO Regression\": Lasso(alpha=1.0, max_iter=10000),\n", + " \"Support Vector Machine\": SVR(kernel='rbf'),\n", + " \"Decision Tree Regressor\": DecisionTreeRegressor(max_depth=10),\n", + " \"Random Forest Regressor\": RandomForestRegressor(n_estimators=200),\n", + " \"LightGBM\": LGBMRegressor(verbose=-1)\n", + "}\n", + "all_results = {}\n", + "\n", + "for name in models:\n", + " all_results[name] = {'mse': [], 'rmse': [], 'r2': []}\n", + "all_results\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "df.isna().any()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "df = df.dropna()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "df.isna().any()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "df" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "def check_missing_values(df):\n", + " missing_values = df.isnull().sum()\n", + " print(\"Missing Values per Column:\")\n", + " print(missing_values[missing_values > 0])\n", + " if missing_values.any():\n", + " print(\"\\nHandle Missing Values as needed.\")\n", + " else:\n", + " print(\"\\nNo Missing Values Found.\")\n", + "\n", + "check_missing_values(df)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "df.isnull().any()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "from sklearn.model_selection import StratifiedKFold\n", + "from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score\n", + "from sklearn.ensemble import RandomForestClassifier\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "sklearn_models = {\n", + " \"Random Forest\": RandomForestClassifier(\n", + " n_estimators=320, # Number of trees\n", + " max_depth=4\n", + " )\n", + "}" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "n_splits = 5 # K\n", + "\n", + "# Stratified 5-Fold Cross-Validation, shuffled\n", + "skf = StratifiedKFold(n_splits=n_splits, shuffle=True, random_state=42)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "for fold_idx, (train_index, test_index) in enumerate(skf.split(X, y)):\n", + " print(f\"\\nFold {fold_idx + 1}/{n_splits}\")\n", + "\n", + " # 1. Split data\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", + " # 2. Train & Validate sklearn models\n", + " for model_name, model in sklearn_models.items():\n", + " print(f\"Training {model_name}...\")\n", + " model.fit(X_train, y_train) # train\n", + " y_pred = model.predict(X_test) # validate\n", + "\n", + " # 3. Save metrics for that model in this fold\n", + " accuracy = accuracy_score(y_test, y_pred)\n", + " f1 = f1_score(y_test, y_pred, zero_division=0)\n", + "\n", + " all_results[model_name]['accuracy'].append(accuracy)\n", + " all_results[model_name]['f1'].append(f1)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "for model_name in all_results:\n", + " print(f\"\\n{model_name}:\")\n", + " print(f\" Accuracy: {np.mean(all_results[model_name]['accuracy']):.4f}\")\n", + " print(f\" Precision: {np.mean(all_results[model_name]['precision']):.4f}\")\n", + " print(f\" Recall: {np.mean(all_results[model_name]['recall']):.4f}\")\n", + " print(f\" F1-Score: {np.mean(all_results[model_name]['f1']):.4f}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Gather importances from the models (from the last fold)\n", + "importances = {}\n", + "\n", + "importances['Random Forest'] = sklearn_models['Random Forest'].feature_importances_\n", + "\n", + "# Create a 1x3 plot\n", + "fig, axes = plt.subplots(1, 3, figsize=(18, 6))\n", + "axes = axes.flatten()\n", + "features = X.columns\n", + "\n", + "for i, (model_name, imp) in enumerate(importances.items()):\n", + " # Sort features by importance for a cleaner plot\n", + " sorted_idx = np.argsort(imp)\n", + "\n", + " ax = axes[i]\n", + " ax.barh(features[sorted_idx], imp[sorted_idx])\n", + " ax.set_title(f\"{model_name} Feature Importance\")\n", + " ax.set_xlabel(\"Importance Score\")\n", + "\n", + "plt.tight_layout()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:\n" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/424/Q2.ipynb b/submissions_extracted/424/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..9e5fc313657a8aa37e2e2aead49f45fa868f0a23 --- /dev/null +++ b/submissions_extracted/424/Q2.ipynb @@ -0,0 +1,430 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q2-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import os\n", + "import pandas as pd\n", + "import numpy as np\n", + "from PIL import Image\n", + "from sklearn.model_selection import train_test_split\n", + "\n", + "# Load Labels\n", + "labels_df = pd.read_csv(os.path.join(path, \"labels.csv\"))\n", + "img_dir = os.path.join(path, \"images\")\n", + "\n", + "images = []\n", + "ages = []\n", + "\n", + "# Load Images and Resize\n", + "print(\"Loading images...\")\n", + "for index, row in labels_df.iterrows():\n", + " img_name = row.iloc[0]\n", + " age = row.iloc[1]\n", + " img_path = os.path.join(img_dir, img_name)\n", + "\n", + " if os.path.exists(img_path):\n", + " img = Image.open(img_path).convert('RGB')\n", + " img_array = np.array(img) / 255.0 # Normalize pixel values to [0, 1]\n", + " images.append(img_array)\n", + " ages.append(age)\n", + "\n", + "X = np.array(images)\n", + "y = np.array(ages)\n", + "\n", + "# Transpose image dimensions to match PyTorch format (N, C, H, W)\n", + "X = np.transpose(X, (0, 3, 1, 2))\n", + "\n", + "# Split Data\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n", + "\n", + "print(f\"X_train shape: {X_train.shape}\")\n", + "print(f\"X_test shape: {X_test.shape}\")\n", + "print(f\"y_train shape: {y_train.shape}\")\n", + "print(f\"y_test shape: {y_test.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import torch\n", + "import torch.nn as nn\n", + "from torchvision.datasets import MNIST\n", + "from torch.utils.data import DataLoader\n", + "from torch.optim import Adam\n", + "from torchvision.transforms.functional import to_tensor\n", + "import torch.nn.functional as F\n", + "import matplotlib.pyplot as plt" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 1. Convert Numpy arrays to PyTorch Tensors\n", + "\n", + "# Training dataset\n", + "train_dataset = MNIST(\n", + " root='./datasets', # Dataset storage path\n", + " train=True, # Use training data\n", + " transform=to_tensor, # Convert images to tensors\n", + " download=True # Download if not available\n", + ")\n", + "\n", + "# Testing dataset\n", + "test_dataset = MNIST(\n", + " root='./datasets', # Dataset storage path\n", + " train=False, # Use test data\n", + " transform=to_tensor, # Convert images to tensors\n", + " download=True # Download if not available\n", + ")\n", + "\n", + "# print one sample from the dataset\n", + "# Each sample consists of an image tensor and its label\n", + "sample_image, sample_label = train_dataset[0]\n", + "\n", + "print(f\"\\n Image shape: {sample_image.shape}\") # (1, 28, 28)\n", + "print(f\"Label: {sample_label}\")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 2. Create TensorDataset objects\n", + "\n", + "import torch\n", + "\n", + "# Create tensors\n", + "x = torch.tensor([1.0, 2.0, 3.0])\n", + "y = torch.randn(3)\n", + "print(\"x:\", x)\n", + "print(\"y:\", y)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 3. Create DataLoaders\n", + "\n", + "from torch.utils.data import DataLoader\n", + "\n", + "# DataLoader for training data\n", + "train_loader = DataLoader(\n", + " train_dataset,\n", + " batch_size=32,\n", + " shuffle=True,\n", + " num_workers=2\n", + ")\n", + "# DataLoader for test/validation data\n", + "test_loader = DataLoader(\n", + " test_dataset,\n", + " batch_size=32,\n", + " shuffle=False,\n", + " num_workers=2\n", + ")\n", + "# Get the first batch from the training DataLoader\n", + "X_batch, y_batch = next(iter(train_loader))\n", + "print(f\"Training batch input shape: {X_batch.shape}\")\n", + "print(f\"Training batch labels shape: {y_batch.shape}\")\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 4. Print shape of one batch\n", + "\n", + "first_sample, _ = train_dataset[0]\n", + "print(f\"Shape of one sample: {first_sample.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 5. Display sample images\n", + "sample_image, sample_label = train_dataset[0]\n", + "\n", + "print(f\"\\n Image shape: {sample_image.shape}\") # (1, 28, 28)\n", + "print(f\"Label: {sample_label}\")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your model class here:\n", + "class NN4Layer(nn.Module):\n", + "\n", + " def __init__(self, input_dim, hidden_dim, output_dim):\n", + " super(NN4Layer, self).__init__()\n", + "\n", + " # First linear layer: input features -> hidden layer\n", + " self.layer1 = nn.Linear(input_dim, hidden_dim)\n", + "\n", + " # Second linear layer: hidden layer -> hidden layer\n", + " self.layer2 = nn.Linear(hidden_dim, hidden_dim)\n", + "\n", + " # Third linear layer: hidden layer -> hidden layer\n", + " self.layer3 = nn.Linear(hidden_dim, hidden_dim)\n", + "\n", + " # Output layer: hidden layer -> number of classes (logits)\n", + " self.layer4 = nn.Linear(hidden_dim, output_dim)\n", + "\n", + " # ReLU activation for non-linearity\n", + " self.relu = nn.ReLU()\n", + "\n", + " # Defines how input data flows through the network\n", + " def forward(self, x):\n", + " # First hidden layer\n", + " a1 = self.relu(self.layer1(x))\n", + "\n", + " # Second hidden layer\n", + " a2 = self.relu(self.layer2(a1))\n", + "\n", + " # Third hidden layer\n", + " a3 = self.relu(self.layer3(a2))\n", + "\n", + " # Output layer (raw scores / logits)\n", + " output = self.layer4(a3) # we said we'll use softmax, where is it? ¯\\(ツ)/¯\n", + "\n", + " return output\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your training loop here:\n", + "def train_one_epoch(model, optimizer, criterion, train_loader, device):\n", + " # Set the model to training mode\n", + " model.train()\n", + "\n", + " running_loss = 0.0\n", + "\n", + " for X_batch, y_batch in train_loader:\n", + " # Move batch to the selected device\n", + " X_batch = X_batch.to(device) # shape: (batch_size, num_features)\n", + " y_batch = y_batch.to(device) # shape: (batch_size,)\n", + "\n", + " # Forward pass (outputs are logits)\n", + " outputs = model(X_batch) # shape: (batch_size, num_classes)\n", + " loss = criterion(outputs, y_batch)\n", + "\n", + " # Backward pass & optimization\n", + " optimizer.zero_grad() # Clear previous gradients\n", + " loss.backward() # Compute gradients\n", + " optimizer.step() # Update model parameters\n", + "\n", + " running_loss += loss.item()\n", + "\n", + " # Average loss over all batches\n", + " avg_loss = running_loss / len(train_loader)\n", + "\n", + " return avg_loss\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your validation loop here:\n", + "def validate(model, criterion, test_loader, device):\n", + " # Set the model to evaluation mode\n", + " model.eval()\n", + "\n", + " running_loss = 0.0\n", + " correct = 0\n", + " total = 0\n", + "\n", + " with torch.no_grad():\n", + " for X_batch, y_batch in test_loader:\n", + " # Move data to device\n", + " X_batch = X_batch.to(device) # shape: (batch_size, num_features)\n", + " y_batch = y_batch.to(device) # shape: (batch_size,)\n", + "\n", + " # Forward pass\n", + " outputs = model(X_batch) # shape: (batch_size, num_classes)\n", + " loss = criterion(outputs, y_batch)\n", + " running_loss += loss.item()\n", + "\n", + " # Apply Softmax to get probabilities\n", + " probabilities = F.softmax(outputs, dim=1)\n", + "\n", + " # Pick the classes with highest probabilities\n", + " predicted = torch.argmax(probabilities, dim=1)\n", + "\n", + " # Accuracy calculation\n", + " correct += (predicted == y_batch).sum().item()\n", + " total += y_batch.size(0)\n", + "\n", + " avg_loss = running_loss / len(test_loader)\n", + " accuracy = correct / total\n", + "\n", + " return avg_loss, accuracy" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Define device, model, loss, optimizer:\n", + "# Device setup\n", + "device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n", + "\n", + "# Model parameters\n", + "input_dim = X_train.shape[1] # Number of tabular features\n", + "hidden_dim = 14 # Design choice\n", + "output_dim = 4 # Weather classes: Rainy, Sunny, Cloudy, Snowy\n", + "\n", + "# Instantiate model\n", + "model = NN4Layer(input_dim, hidden_dim, output_dim).to(device)\n", + "\n", + "# Print the model architecture\n", + "print(\"Model Architecture:\\n\")\n", + "print(model)\n", + "\n", + "# Calculate the total number of trainable parameters\n", + "total_params = sum(p.numel() for p in model.parameters() if p.requires_grad)\n", + "print(f\"\\nTotal trainable parameters: {total_params}\")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "from torch.optim import AdamW\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Start training for 20 epochs:\n", + "\n", + "\n", + "num_epochs = 10\n", + "learning_rate = 0.001\n", + "\n", + "# Define criterion (loss function) - using CrossEntropyLoss as model now outputs logits\n", + "criterion = nn.CrossEntropyLoss()\n", + "# Define optimizer\n", + "optimizer = AdamW(model.parameters(), learning_rate)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Run Training\n", + "train_losses = []\n", + "val_losses = []\n", + "val_accuracies = []\n", + "\n", + "print('Starting Training...')\n", + "for epoch in range(num_epochs):\n", + " # Train one epoch\n", + " train_loss = train_one_epoch(model, optimizer, criterion, train_loader, device)\n", + "\n", + " # Validate\n", + " val_loss, val_accuracy = validate(model, criterion, test_loader, device)\n", + "\n", + " train_losses.append(train_loss)\n", + " val_losses.append(val_loss)\n", + " val_accuracies.append(val_accuracy)\n", + "\n", + " print(f'Epoch [{epoch+1}/{num_epochs}], Train Loss: {train_loss:.4f}, Val Loss: {val_loss:.4f}, Val Accuracy: {val_accuracy:.4f}')\n", + "\n", + "print('Training Complete!')" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "# Plotting results\n", + "plt.figure(figsize=(7, 5))\n", + "\n", + "plt.plot(train_losses, label='Train Loss')\n", + "plt.plot(val_losses, label='Validation Loss')\n", + "plt.title('Loss over Epochs')\n", + "plt.xlabel('Epoch')\n", + "plt.ylabel('Loss')\n", + "plt.legend()\n", + "\n", + "plt.tight_layout()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2 (Bonus): Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/424/Q3.ipynb b/submissions_extracted/424/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..430169a6a8612ec77877e2d09aebc6083e1e6231 --- /dev/null +++ b/submissions_extracted/424/Q3.ipynb @@ -0,0 +1,362 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "\n", + "\n", + "# Download latest version\n", + "\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q3-exam-data\")\n", + "\n", + "\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "from IPython.display import clear_output\n", + "\n", + "%pip install kagglehub catboost xgboost tqdm -q\n", + "\n", + "clear_output()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import pandas as pd\n", + "import numpy as np\n", + "import matplotlib.pyplot as plt\n", + "import seaborn as sns\n", + "import kagglehub\n", + "import os\n", + "from tqdm import tqdm\n", + "\n", + "%matplotlib inline" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "# Task 1: Write your code here:\n", + "df_path = os.path.join(path, 'Q3_data.csv')\n", + "df = pd.read_csv(df_path)\n", + "\n", + "print(f\"Dataset shape: {df.shape}\")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "df.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "df.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "def check_missing_values(df):\n", + " missing_values = df.isnull().sum()\n", + " print(\"Missing Values per Column:\")\n", + " print(missing_values[missing_values > 0])\n", + " if missing_values.any():\n", + " print(\"\\nHandle Missing Values as needed.\")\n", + " else:\n", + " print(\"\\nNo Missing Values Found.\")\n", + "\n", + "check_missing_values(df)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "def check_duplicates(df):\n", + " duplicates = df.duplicated().sum()\n", + " print(f\"Number of Duplicate Samples: {duplicates}\")\n", + " if duplicates > 0:\n", + " print(\"Dropping Duplicates...\")\n", + " df.drop_duplicates(inplace=True)\n", + " print(\"Duplicates Dropped.\")\n", + " else:\n", + " print(\"No Duplicate Samples Found.\")\n", + "\n", + "check_duplicates(df)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "categorical_cols = df.select_dtypes(include=[\"object\"]).columns\n", + "\n", + "print(\"Categorical Columns:\", list(categorical_cols))" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "from sklearn.preprocessing import StandardScaler #import StandardScaler\n", + "\n", + "print('data before scaling:\\n', df) #show before scaling\n", + "standard_scaler = StandardScaler() # Instantiate StandardScaler\n", + "data_standard_scaled = standard_scaler.fit_transform(df) # Apply fit_transform\n", + "\n", + "print('\\nData after scaling:\\n', data_standard_scaled) #show after scaling" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "def check_target_imbalance(df, target_column):\n", + " print(\"Target Distribution:\")\n", + "\n", + " df[target_column].hist() # Yeah you can just do this :)\n", + " plt.show()\n", + "\n", + "check_target_imbalance(df, \"Target\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "X = df.drop(\"Target\", axis=1).astype(float)\n", + "y = df['Target'].astype(float)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "!pip install catboost" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:\n", + "# Import models\n", + "from sklearn.neighbors import KNeighborsClassifier\n", + "from sklearn.svm import SVC\n", + "from sklearn.tree import DecisionTreeClassifier\n", + "from sklearn.ensemble import RandomForestClassifier\n", + "from xgboost import XGBClassifier\n", + "from catboost import CatBoostClassifier" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "from sklearn.model_selection import StratifiedKFold\n", + "from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "sklearn_models = {\n", + " \"CatBoost\": CatBoostClassifier(\n", + " verbose=0,\n", + " n_estimators=320,\n", + " max_depth=4\n", + " )\n", + "}\n", + "all_results = {}\n", + "\n", + "for name in sklearn_models:\n", + " all_results[name] = {'accuracy': [],'f1': []}" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "n_splits = 5 # K\n", + "\n", + "# Stratified 5-Fold Cross-Validation, shuffled\n", + "skf = StratifiedKFold(n_splits=n_splits, shuffle=True, random_state=42)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "for fold_idx, (train_index, test_index) in enumerate(skf.split(X, y)):\n", + " print(f\"\\nFold {fold_idx + 1}/{n_splits}\")\n", + "\n", + " # 1. Split data\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", + " # 2. Train & Validate sklearn models\n", + " for model_name, model in sklearn_models.items():\n", + " print(f\"Training {model_name}...\")\n", + " model.fit(X_train, y_train) # train\n", + " y_pred = model.predict(X_test) # validate\n", + "\n", + " # 3. Save metrics for that model in this fold\n", + " accuracy = accuracy_score(y_test, y_pred)\n", + " f1 = f1_score(y_test, y_pred, zero_division=0)\n", + "\n", + " all_results[model_name]['accuracy'].append(accuracy)\n", + " all_results[model_name]['f1'].append(f1)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "for model_name in all_results:\n", + " print(f\"\\n{model_name}:\")\n", + " print(f\" Accuracy: {np.mean(all_results[model_name]['accuracy']):.4f}\")\n", + " print(f\" F1-Score: {np.mean(all_results[model_name]['f1']):.4f}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "# Gather importances from the models (from the last fold)\n", + "importances = {}\n", + "\n", + "importances['CatBoost'] = sklearn_models['CatBoost'].feature_importances_\n", + "\n", + "# Create a 1x3 plot\n", + "fig, axes = plt.subplots(1, 3, figsize=(18, 6))\n", + "axes = axes.flatten()\n", + "features = X.columns\n", + "\n", + "for i, (model_name, imp) in enumerate(importances.items()):\n", + " # Sort features by importance for a cleaner plot\n", + " sorted_idx = np.argsort(imp)\n", + "\n", + " ax = axes[i]\n", + " ax.barh(features[sorted_idx], imp[sorted_idx])\n", + " ax.set_title(f\"{model_name} Feature Importance\")\n", + " ax.set_xlabel(\"Importance Score\")\n", + "\n", + "plt.tight_layout()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "# P_2 D_39 B_1 B_2" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/425/Q1.ipynb b/submissions_extracted/425/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..13ab6f73895881c22d35951f25cda016e30cb926 --- /dev/null +++ b/submissions_extracted/425/Q1.ipynb @@ -0,0 +1,342 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "import os\n", + "import pandas as pd\n", + "import matplotlib.pyplot as plt\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q1-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "# Load the dataset\n", + "df_path = os.path.join(path, 'Q1_data.csv')\n", + "df = pd.read_csv(df_path)\n", + "\n", + "print(f\"Dataset shape: {df.shape}\")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "df.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "df.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "plt.figure(figsize=(10, 5))\n", + "plt.hist(df['Delivery_Time'].dropna(), bins=50, edgecolor='black')\n", + "plt.title('Delivery Distribution')\n", + "plt.xlabel('Time')\n", + "plt.ylabel('Frequency')\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "df.drop(columns=['Order_ID'])" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "def check_missing_values(df):\n", + " missing_values = df.isnull().sum()\n", + " print(\"Missing Values per Column:\")\n", + " print(missing_values[missing_values > 0])\n", + " if missing_values.any():\n", + " print(\"\\nHandle Missing Values as needed.\")\n", + " else:\n", + " print(\"\\nNo Missing Values Found.\")\n", + "\n", + "check_missing_values(df)\n", + "cols = ['Weather', 'Traffic_Level', 'Time_of_Day', 'Courier_Experience_yrs', 'Delivery_Time']\n", + "df_clean = df.copy()\n", + "\n", + "\n", + "\n", + "# for Weather\n", + "for col in [\"Weather\"]:\n", + " df_clean[col] = df_clean[col].fillna('unknown')\n", + "\n", + "\n", + "#for some reason traffic-level and Time_of_Day Courier_Experience_yrs will be filled with Modes by defult :)\n", + "df_clean['Traffic_Level'] = df_clean['Traffic_Level'].fillna(df_clean['Traffic_Level'].mode()[0])\n", + "df_clean['Time_of_Day'] = df_clean['Time_of_Day'].fillna(df_clean['Time_of_Day'].mode()[0])\n", + "df_clean['Courier_Experience_yrs'] = df_clean['Courier_Experience_yrs'].fillna(df_clean['Courier_Experience_yrs'].mode()[0])\n", + "\n", + "\n", + "#used mean for it\n", + "df_clean['Delivery_Time'] = df_clean['Delivery_Time'].fillna(df_clean['Delivery_Time'].mean())\n", + "\n", + "\n", + "print(\"Missing values remaining:\", df_clean.isnull().sum().sum())" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "def check_duplicates(df):\n", + " duplicates = df.duplicated().sum()\n", + " print(f\"Number of Duplicate Samples: {duplicates}\")\n", + " if duplicates > 0:\n", + " print(\"Dropping Duplicates...\")\n", + " df.drop_duplicates(inplace=True)\n", + " print(\"Duplicates Dropped.\")\n", + " else:\n", + " print(\"No Duplicate Samples Found.\")\n", + "\n", + "check_duplicates(df_clean)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "from sklearn.preprocessing import StandardScaler, LabelEncoder,OneHotEncoder\n", + "#check it first\n", + "categorical_cols = df.select_dtypes(include=[\"object\"]).columns\n", + "print(\"Categorical Columns:\", list(categorical_cols))\n", + "\n", + "df_clean.head()\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "df_clean.head()\n", + "\n", + "for col in ['Weather', 'Traffic_Level', 'Time_of_Day','Vehicle_Type']:\n", + " le = LabelEncoder()\n", + " df_clean[col] = le.fit_transform(df_clean[col].astype(str))\n", + "\n", + "df_clean.head()\n", + "\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "from sklearn.model_selection import train_test_split, KFold\n", + "\n", + "# Define features (X) and target (y)\n", + "df_clean.head()\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "scaler = StandardScaler()\n", + "X_train_scaled = scaler.fit_transform(X_train)\n", + "X_test_scaled = scaler.transform(X_test)\n", + "\n", + "print(f\"\\nScaled ranges - Min: {X_train_scaled.min():.2f}, Max: {X_train_scaled.max():.2f}\")\n", + "pd.DataFrame(X_train_scaled, columns=X_train.columns).head(3)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 6: Write your code here:\n", + "df_clean['Delivery_Time'].hist()\n", + "\n", + "#it seems alrghit fingers crossed :)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "feature_cols = ['Order_ID',\t'Distance_km',\t'Weather',\t'Traffic_Level',\t'Time_of_Day',\t'Vehicle_Type',\t'Preparation_Time_min',\t'Courier_Experience_yrs']\n", + "X = df_clean[feature_cols]\n", + "y = df_clean['Delivery_Time']\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "# Print shapes\n", + "print(\"X_train shape:\", X_train.shape)\n", + "print(\"X_test shape:\", X_test.shape)\n", + "print(\"y_train shape:\", y_train.shape)\n", + "print(\"y_test shape:\", y_test.shape)\n", + "\n", + "\n", + "\n", + "#print(f\"\\nFeature ranges - Min: {X_train.min().min():.2f}, Max: {X_train.max().max():.2f}\")\n", + "#X_train.head(3)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:\n", + "from sklearn.model_selection import train_test_split, KFold,StratifiedKFold\n", + "from sklearn.ensemble import RandomForestRegressor\n", + "from sklearn.metrics import mean_absolute_error,mean_squared_error\n", + "\n", + "\n", + "kfold = KFold(n_splits=5, shuffle=True, random_state=42)\n", + "\n", + "mae_scores = []\n", + "rmse_scores = []\n", + "\n", + "for train_idx, val_idx in kfold.split(X_train_scaled):\n", + " X_fold_train, X_fold_val = X_train_scaled[train_idx], X_train_scaled[val_idx]\n", + " y_fold_train, y_fold_val = y_train.iloc[train_idx], y_train.iloc[val_idx]\n", + "print(f\"5-Fold CV Results:\")\n", + "\n", + "\n", + "\n", + "\n", + "# Train Random Forest Regressor\n", + "model = RandomForestRegressor(n_estimators=100, max_depth=20, random_state=42, n_jobs=-1)\n", + "model.fit(X_train_scaled, y_train)\n", + "print(\"Model trained!\")\n", + "\n", + "\n", + "# Predict and evaluate\n", + "mse = mean_squared_error(y_test, y_pred)\n", + "rmse = np.sqrt(mse)\n", + "\n", + "print(\"MSE :\", mse)\n", + "print(\"RMSE:\", rmse)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "# Feature importance\n", + "feature_importance = pd.DataFrame({\n", + " 'feature': feature_cols,\n", + " 'importance': model.feature_importances_\n", + "}).sort_values('importance', ascending=False)\n", + "\n", + "plt.figure(figsize=(10, 6))\n", + "plt.barh(feature_importance['feature'], feature_importance['importance'])\n", + "plt.xlabel('Importance')\n", + "plt.title('Feature Importance')\n", + "plt.gca().invert_yaxis()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "\n", + "plt.figure(figsize=(10, 5))\n", + "plt.hist(df_clean['price'].dropna(), bins=50, edgecolor='black')\n", + "plt.title('Price Distribution')\n", + "plt.xlabel('Price')\n", + "plt.ylabel('Frequency')\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/425/Q2.ipynb b/submissions_extracted/425/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..2b585d1264c00f480802b7605e6a2573e0b3d383 --- /dev/null +++ b/submissions_extracted/425/Q2.ipynb @@ -0,0 +1,430 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q2-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import os\n", + "import pandas as pd\n", + "import numpy as np\n", + "from PIL import Image\n", + "from sklearn.model_selection import train_test_split\n", + "\n", + "# Load Labels\n", + "labels_df = pd.read_csv(os.path.join(path, \"labels.csv\"))\n", + "img_dir = os.path.join(path, \"images\")\n", + "\n", + "images = []\n", + "ages = []\n", + "\n", + "# Load Images and Resize\n", + "print(\"Loading images...\")\n", + "for index, row in labels_df.iterrows():\n", + " img_name = row.iloc[0]\n", + " age = row.iloc[1]\n", + " img_path = os.path.join(img_dir, img_name)\n", + "\n", + " if os.path.exists(img_path):\n", + " img = Image.open(img_path).convert('RGB')\n", + " img_array = np.array(img) / 255.0 # Normalize pixel values to [0, 1]\n", + " images.append(img_array)\n", + " ages.append(age)\n", + "\n", + "X = np.array(images)\n", + "y = np.array(ages)\n", + "\n", + "# Transpose image dimensions to match PyTorch format (N, C, H, W)\n", + "X = np.transpose(X, (0, 3, 1, 2))\n", + "\n", + "# Split Data\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n", + "\n", + "print(f\"X_train shape: {X_train.shape}\")\n", + "print(f\"X_test shape: {X_test.shape}\")\n", + "print(f\"y_train shape: {y_train.shape}\")\n", + "print(f\"y_test shape: {y_test.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 1. Convert Numpy arrays to PyTorch Tensors\n", + "import torch\n", + "\n", + "x_train = torch.tensor(X_train, dtype=torch.float32)\n", + "print(x.dtype)\n", + "\n", + "x_test = torch.tensor(X_test, dtype=torch.float32)\n", + "print(x.dtype)\n", + "\n", + "y_train = torch.tensor(y_train, dtype=torch.float32)\n", + "print(x.dtype)\n", + "\n", + "y_test = torch.tensor(y_test, dtype=torch.float32)\n", + "print(x.dtype)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 2. Create TensorDataset objects\n", + "\n", + "\n", + "\n", + "from torchvision.datasets import MNIST\n", + "from torchvision.transforms.functional import to_tensor\n", + "\n", + "# Training dataset\n", + "train_dataset = MNIST(\n", + " root='./datasets', # Dataset storage path\n", + " train=True, # Use training data\n", + " transform=to_tensor, # Convert images to tensors\n", + " download=True # Download if not available\n", + ")\n", + "\n", + "# Testing dataset\n", + "test_dataset = MNIST(\n", + " root='./datasets', # Dataset storage path\n", + " train=False, # Use test data\n", + " transform=to_tensor, # Convert images to tensors\n", + " download=True # Download if not available\n", + ")\n", + "\n", + "# print one sample from the dataset\n", + "# Each sample consists of an image tensor and its label\n", + "sample_image, sample_label = train_dataset[0]\n", + "\n", + "print(f\"\\n Image shape: {sample_image.shape}\") # (1, 28, 28)\n", + "print(f\"Label: {sample_label}\")\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 3. Create DataLoaders\n", + "from torch.utils.data import DataLoader\n", + "\n", + "# DataLoader for training data\n", + "train_loader = DataLoader(\n", + " train_dataset,\n", + " batch_size=32,\n", + " shuffle=True,\n", + " num_workers=2\n", + ")\n", + "# DataLoader for test/validation data\n", + "test_loader = DataLoader(\n", + " test_dataset,\n", + " batch_size=32,\n", + " shuffle=False,\n", + " num_workers=2\n", + ")\n", + "\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 4. Print shape of one batch\n", + "\n", + "# Get the first batch from the training DataLoader\n", + "X_batch, y_batch = next(iter(train_loader))\n", + "print(f\"Training batch input shape: {X_batch.shape}\")\n", + "print(f\"Training batch labels shape: {y_batch.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 5. Display sample images\n", + "import matplotlib.pyplot as plt\n", + "images, labels = next(iter(train_loader))\n", + "\n", + "# Display the first 6 images in the batch\n", + "plt.figure(figsize=(8, 4))\n", + "\n", + "for i in range(6):\n", + " plt.subplot(2, 3, i + 1)\n", + " plt.imshow(images[i].squeeze(), cmap='gray')\n", + " plt.title(f\"Label: {labels[i].item()}\")\n", + " plt.axis('off')\n", + "\n", + "plt.tight_layout()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your model class here:\n", + "import torch.nn as nn\n", + "\n", + "\n", + "class NN4Layer(nn.Module):\n", + "\n", + " def __init__(self, input_dim, hidden_dim, output_dim):\n", + " super(NN4Layer, self).__init__()\n", + "\n", + " # First linear layer: input features -> hidden layer\n", + " self.layer1 = nn.Linear(input_dim, hidden_dim)\n", + "\n", + " # Second linear layer: hidden layer -> hidden layer\n", + " self.layer2 = nn.Linear(hidden_dim, hidden_dim)\n", + "\n", + " # Output layer: hidden layer -> number of classes (logits)\n", + " self.layer3 = nn.Linear(hidden_dim, hidden_dim)\n", + "\n", + " self.layer4 = nn.Linear(hidden_dim, output_dim)\n", + "\n", + "\n", + " # ReLU activation for non-linearity\n", + " self.relu = nn.ReLU()\n", + "\n", + " # Defines how input data flows through the network\n", + " def forward(self, x):\n", + " # First hidden layer\n", + " z1 = self.layer1(x)\n", + " a1 = self.relu(z1)\n", + "\n", + " # Second hidden layer\n", + " z2 = self.layer2(a1)\n", + " a2 = self.relu(z2)\n", + "\n", + "\n", + " z3 = self.layer2(a2)\n", + " a3 = self.relu(z3)\n", + "\n", + " # Output layer (raw scores / logits)\n", + " output = self.layer3(a3) # there is something missing here, remember? :)\n", + "\n", + " return output\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your training loop here:\n", + "\n", + "def train_one_epoch(model, optimizer, criterion, train_loader, device):\n", + " # Set the model to training mode\n", + " model.train()\n", + "\n", + " running_loss = 0.0\n", + "\n", + " for X_batch, y_batch in train_loader:\n", + " # Move batch to the selected device\n", + " X_batch = X_batch.view(X_batch.size(0), -1).to(device)\n", + " y_batch = y_batch.to(device)\n", + "\n", + " # Forward pass\n", + " outputs = model(X_batch) # shape: (batch_size, 10)\n", + " loss = criterion(outputs, y_batch)\n", + "\n", + " # Backward pass & optimization\n", + " optimizer.zero_grad() # Clear previous gradients\n", + " loss.backward() # Compute gradients\n", + " optimizer.step() # Update model parameters\n", + "\n", + " running_loss += loss.item()\n", + "\n", + " # Average loss over all batches\n", + " avg_loss = running_loss / len(train_loader)\n", + "\n", + " return avg_loss" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your validation loop here:\n", + "\n", + "def validate(model, criterion, test_loader, device):\n", + " # Set the model to evaluation mode\n", + " model.eval()\n", + "\n", + " running_loss = 0.0\n", + " correct = 0\n", + " total = 0\n", + "\n", + " with torch.no_grad():\n", + " for X_batch, y_batch in test_loader:\n", + " # Move data to device\n", + " X_batch = X_batch.view(X_batch.size(0), -1).to(device)\n", + " y_batch = y_batch.to(device)\n", + "\n", + " # Forward pass\n", + " outputs = model(X_batch) # shape: (batch_size, 10)\n", + " loss = criterion(outputs, y_batch)\n", + " running_loss += loss.item()\n", + "\n", + " # Apply Softmax to get probabilities\n", + " probabilities = F.softmax(outputs, dim=1)\n", + "\n", + " # Multiclass predictions\n", + " predicted = torch.argmax(probabilities, dim=1)\n", + "\n", + " # Accuracy calculation\n", + " correct += (predicted == y_batch).sum().item()\n", + " total += y_batch.size(0)\n", + "\n", + " avg_loss = running_loss / len(test_loader)\n", + " accuracy = correct / total\n", + "\n", + " return avg_loss, accuracy\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Define device, model, loss, optimizer:\n", + "from torch.optim import Adam\n", + "import torch.nn.functional as F\n", + "\n", + "\n", + "# Device setup\n", + "device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n", + "\n", + "# Model parameters\n", + "input_dim = 28 * 28 # MNIST images flattened\n", + "hidden_dim = 14 # Design choice\n", + "output_dim = 10 # Digits 0–9\n", + "\n", + "# Instantiate model\n", + "model = NN4Layer(input_dim, hidden_dim, output_dim).to(device)\n", + "\n", + "# Print the model architecture\n", + "print(\"Model Architecture:\\n\")\n", + "print(model)\n", + "\n", + "# Calculate the total number of trainable parameters\n", + "total_params = sum(p.numel() for p in model.parameters() if p.requires_grad)\n", + "print(f\"\\nTotal trainable parameters: {total_params}\")\n", + "\n", + "\n", + "num_epochs = 20\n", + "learning_rate = 0.001\n", + "\n", + "# Define criterion (loss function) - using CrossEntropyLoss as model now outputs logits\n", + "criterion = nn.CrossEntropyLoss()\n", + "# Define optimizer\n", + "optimizer = Adam(model.parameters(), learning_rate)\n", + "\n", + "\n", + "train_losses = []\n", + "val_losses = []\n", + "val_accuracies = []\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Start training for 20 epochs:\n", + "\n", + "print('Starting Training...')\n", + "for epoch in range(num_epochs):\n", + " # Train one epoch\n", + " train_loss = train_one_epoch(model, optimizer, criterion, train_loader, device)\n", + "\n", + " # Validate\n", + " val_loss, val_accuracy = validate(model, criterion, test_loader, device)\n", + "\n", + " train_losses.append(train_loss)\n", + " val_losses.append(val_loss)\n", + " val_accuracies.append(val_accuracy)\n", + "\n", + " print(f'Epoch [{epoch+1}/{num_epochs}], Train Loss: {train_loss:.4f}, Val Loss: {val_loss:.4f}, Val Accuracy: {val_accuracy:.4f}')\n", + "\n", + "print('Training Complete!')" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "# Plotting results\n", + "plt.figure(figsize=(7, 5))\n", + "\n", + "plt.plot(train_losses, label='Train Loss')\n", + "plt.plot(val_losses, label='Validation Loss')\n", + "plt.title('Loss over Epochs')\n", + "plt.xlabel('Epoch')\n", + "plt.ylabel('Loss')\n", + "plt.legend()\n", + "\n", + "plt.tight_layout()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2 (Bonus): Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/425/Q3.ipynb b/submissions_extracted/425/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..d8c8b9c0ec688044ccdf86a00e597783734514b8 --- /dev/null +++ b/submissions_extracted/425/Q3.ipynb @@ -0,0 +1,385 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "import kagglehub\n", + "import os\n", + "import pandas as pd\n", + "import matplotlib.pyplot as plt\n", + "\n", + "\n", + "\n", + "# Download latest version\n", + "\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q3-exam-data\")\n", + "\n", + "\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "\n", + "df_path = os.path.join(path, 'Q3_data.csv')\n", + "df = pd.read_csv(df_path)\n", + "\n", + "print(f\"Dataset shape: {df.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "df.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "df.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "missing_percentage = (df.isnull().sum() / len(df)) * 100\n", + "missing_data = pd.DataFrame({\n", + " 'Column': missing_percentage.index,\n", + " 'Missing_Percentage': missing_percentage.values\n", + "})\n", + "missing_data = missing_data[missing_data['Missing_Percentage'] > 0].sort_values('Missing_Percentage', ascending=False)\n", + "\n", + "print(\"Missing Data Analysis:\")\n", + "missing_data.head(10)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "missing_percentage = (df.isnull().sum() / len(df)) * 100\n", + "missing_data = pd.DataFrame({\n", + " 'Column': missing_percentage.index,\n", + " 'Missing_Percentage': missing_percentage.values\n", + "})\n", + "missing_data = missing_data[missing_data['Missing_Percentage'] > 0].sort_values('Missing_Percentage', ascending=False)\n", + "\n", + "print(\"Missing Data Analysis:\")\n", + "missing_data.head(10)\n", + "\n", + "def check_missing_values(df):\n", + "\n", + " # Get missing values using pandas\n", + " missing_values = df.isnull().sum()\n", + "\n", + " print(\"Missing Values per Column:\")\n", + " print(missing_values[missing_values > 0])\n", + "\n", + " if missing_values.any() or NaN:\n", + " print(\"\\nHandle Missing Values as needed.\")\n", + " else:\n", + " print(\"\\nNo Missing Values Found.\")\n", + "\n", + "check_missing_values(df)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "\n", + "\n", + "def check_duplicates(df):\n", + " duplicates = df.duplicated().sum()\n", + " print(f\"Number of Duplicate Samples: {duplicates}\")\n", + " if duplicates > 0:\n", + " print(\"Dropping Duplicates...\")\n", + " df.drop_duplicates(inplace=True)\n", + " print(\"Duplicates Dropped.\")\n", + " else:\n", + " print(\"No Duplicate Samples Found.\")\n", + "\n", + "check_duplicates(df_clean)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "\n", + "from sklearn.preprocessing import StandardScaler, LabelEncoder,OneHotEncoder\n", + "#check it first\n", + "categorical_cols = df.select_dtypes(include=[\"object\"]).columns\n", + "print(\"Categorical Columns:\", list(categorical_cols))\n", + "\n", + "df_clean.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "from sklearn.preprocessing import StandardScaler\n", + "\n", + "numerical_cols = df.select_dtypes(include=[\"number\"]).columns.drop(\"P_2\")\n", + "\n", + "scaler = StandardScaler()\n", + "df[numerical_cols] = scaler.fit_transform(df[numerical_cols])\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "\n", + "df_clean['P_2'].hist()\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "\n", + "X = df.drop(\"P_2\", axis=1).astype(float)\n", + "y = df[\"P_2\"].astype(float)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:\n", + "from sklearn.model_selection import train_test_split, KFold,StratifiedKFold\n", + "n_splits = 3 # K=3 Folds\n", + "\n", + "skf = StratifiedKFold(n_splits=n_splits, shuffle=True, random_state=42)\n", + "sr_results = {'loss': [], 'acc': [], 'f1': []}\n", + "\n", + "for fold_idx, (train_index, test_index) in enumerate(skf.split(X, y)):\n", + "\n", + " print(f\"\\nFold {fold_idx + 1}/{n_splits}\")\n", + "\n", + " # Get the train & test split for this fold\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", + " # Train using gradient descent with learning rate = 0.5\n", + " theta, losses = gradient_descent(X_train, y_train, lr=0.5, num_classes=4)\n", + "\n", + " # Calculate z & class probabilities for X_test\n", + " z = np.dot(X_test, theta)\n", + " y_pred_proba = softmax(z)\n", + "\n", + " # Pick the predicted classes with the highest probability\n", + " y_pred = np.argmax(y_pred_proba, axis=1)\n", + "\n", + " # Calculate evaluation metrics\n", + " accuracy = accuracy_score(y_test, y_pred)\n", + " f1 = f1_score(y_test, y_pred, average='macro') # for multiclass f1 score, you should set the average hyperparameter (\"macro\", \"micro\", \"weighted\")\n", + "\n", + " # Store results\n", + " sr_results['loss'].append(losses)\n", + " sr_results['acc'].append(accuracy)\n", + " sr_results['f1'].append(f1)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "# Gather importances from the models (from the last fold)\n", + "from sklearn.neighbors import KNeighborsClassifier\n", + "from sklearn.svm import SVC\n", + "from sklearn.tree import DecisionTreeClassifier\n", + "from sklearn.ensemble import RandomForestClassifier\n", + "from xgboost import XGBClassifier\n", + "\n", + "\n", + "sklearn_models = {\n", + " \"K-Nearest Neighbors\": KNeighborsClassifier(\n", + " n_neighbors=3, # Number of neighbors to consider\n", + " ),\n", + " \"Support Vector Machine\": SVC(\n", + " kernel='rbf', # 'linear', 'poly', 'rbf', 'sigmoid'\n", + " C=0.75 # Regularization parameter\n", + " ),\n", + " \"Decision Tree\": DecisionTreeClassifier(\n", + " max_depth=3 # Maximum depth of tree (prevents overfitting)\n", + " ),\n", + " \"Random Forest\": RandomForestClassifier(\n", + " n_estimators=320, # Number of trees\n", + " max_depth=4\n", + " ),\n", + " \"XGBoost\": XGBClassifier(\n", + " verbosity=0,\n", + " n_estimators=300, # Number of boosting rounds\n", + " max_depth=5,\n", + " learning_rate=0.05 # Step size shrinkage\n", + " ),\n", + "\n", + "}\n", + "\n", + "\n", + "\n", + "\n", + "all_results = {}\n", + "\n", + "for name in sklearn_models:\n", + " all_results[name] = {'accuracy': [], 'precision': [], 'recall': [], 'f1': []}\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "all_results = {}\n", + "\n", + "for name in sklearn_models:\n", + " all_results[name] = {'accuracy': [], 'precision': [], 'recall': [], 'f1': []}\n", + "# Calculate the majority class baseline\n", + "n_splits = 5 # K\n", + "\n", + "# Stratified 5-Fold Cross-Validation, shuffled\n", + "skf = StratifiedKFold(n_splits=n_splits, shuffle=True, random_state=42)\n", + "\n", + "majority_class = y.value_counts().idxmax()\n", + "baseline_pred = [majority_class] * len(y)\n", + "for fold_idx, (train_index, test_index) in enumerate(skf.split(X, y)):\n", + " print(f\"\\nFold {fold_idx + 1}/{n_splits}\")\n", + "\n", + " # 1. Split data\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", + " # 2. Train & Validate sklearn models\n", + " for model_name, model in sklearn_models.items():\n", + " print(f\"Training {model_name}...\")\n", + " model.fit(X_train, y_train) # train\n", + " y_pred = model.predict(X_test) # validate\n", + "\n", + " # 3. Save metrics for that model in this fold\n", + " accuracy = accuracy_score(y_test, y_pred)\n", + " precision = precision_score(y_test, y_pred, zero_division=0)\n", + " recall = recall_score(y_test, y_pred, zero_division=0)\n", + " f1 = f1_score(y_test, y_pred, zero_division=0)\n", + "\n", + " all_results[model_name]['accuracy'].append(accuracy)\n", + " all_results[model_name]['precision'].append(precision)\n", + " all_results[model_name]['recall'].append(recall)\n", + " all_results[model_name]['f1'].append(f1)\n", + "\n", + "# Evaluate the baseline\n", + "baseline_accuracy = accuracy_score(y, baseline_pred)\n", + "baseline_precision = precision_score(y, baseline_pred, average='weighted', zero_division=0)\n", + "baseline_recall = recall_score(y, baseline_pred, average='weighted', zero_division=0)\n", + "baseline_f1 = f1_score(y, baseline_pred, average='weighted', zero_division=0)\n", + "\n", + "print(f\"Baseline Accuracy (majority class): {baseline_accuracy:.4f}\")\n", + "print(f\"Baseline Precision: {baseline_precision:.4f}\")\n", + "print(f\"Baseline Recall: {baseline_recall:.4f}\")\n", + "print(f\"Baseline F1-Score: {baseline_f1:.4f}\")\n", + "\n", + "# Gather importances from the models (from the last fold)\n", + "importances = {}\n", + "\n", + "importances['Random Forest'] = sklearn_models['Random Forest'].feature_importances_\n", + "importances['XGBoost'] = sklearn_models['XGBoost'].feature_importances_\n", + "importances['CatBoost'] = sklearn_models['CatBoost'].feature_importances_\n", + "\n", + "# Create a 1x3 plot\n", + "fig, axes = plt.subplots(1, 3, figsize=(18, 6))\n", + "axes = axes.flatten()\n", + "features = X.columns\n", + "\n", + "for i, (model_name, imp) in enumerate(importances.items()):\n", + " # Sort features by importance for a cleaner plot\n", + " sorted_idx = np.argsort(imp)\n", + "\n", + " ax = axes[i]\n", + " ax.barh(features[sorted_idx], imp[sorted_idx])\n", + " ax.set_title(f\"{model_name} Feature Importance\")\n", + " ax.set_xlabel(\"Importance Score\")\n", + "\n", + "plt.tight_layout()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/426/Q1.ipynb b/submissions_extracted/426/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..a041a3a925dda8093bb5d663a3dfb8a33ae20a66 --- /dev/null +++ b/submissions_extracted/426/Q1.ipynb @@ -0,0 +1,324 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q1-exam-data\")\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "import pandas as pd\n", + "import os\n", + "csv_path = os.path.join(path, \"Q1_data.csv\")\n", + "df = pd.read_csv(csv_path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "df.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "df.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "#What does our target variable look like?\n", + "import matplotlib.pyplot as plt\n", + "target_column = \"delivery_time\"\n", + "def check_target_distribution(df, target_column):\n", + " df[target_column].hist(bins=30, edgecolor='black') ## his=histogram\n", + "\n", + " plt.title(f\"Target Distribution ({target_column})\")\n", + " plt.xlabel(target_column)\n", + " plt.ylabel(\"Frequency\")\n", + " plt.grid(False)\n", + "\n", + " plt.show()\n", + "\n", + "##check_target_distribution(df, \"delivery_time\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "df.drop(columns=['Order_ID'])" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "# Analyze missing values\n", + "missing_percentage = (df.isnull().sum() / len(df)) * 100\n", + "missing_data = pd.DataFrame({\n", + " 'Column': missing_percentage.index,\n", + " 'Missing_Percentage': missing_percentage.values\n", + "})\n", + "missing_data = missing_data[missing_data['Missing_Percentage'] > 0].sort_values('Missing_Percentage', ascending=False)\n", + "print(\"Missing Data Analysis:\")\n", + "missing_data.head(10)\n", + "# Select relevant columns, we do not select 'model' (too many unique values, too sparse and will hurt the model performance)\n", + "col = ['Weather','Traffic_Level', 'Time_of_Day', 'Courier_Experience_yrs', 'Delivery_Time']\n", + "df_clen = df[cols].copy()\n", + "\n", + "# ## Numerical: Delivery_Time\t, Courier_Experience_yrs num\n", + "for col in ['Traffic_Level','Courier_Experience_yrs','Time_of_Day','Delivery_Time']:\n", + " df_clean[col] = df_clean[col].fillna(df_clean['col'].mean())\n", + "\n", + "print(\"Missing values remaining:\", df_clean.isnull().sum().sum())" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "print(\"Checking for duplicate rows...\")\n", + "duplicate_rows = df.duplicated().sum()\n", + "if duplicate_rows > 0:\n", + " print(f\"Found {duplicate_rows} duplicate rows. Removing them...\")\n", + " df.drop_duplicates(inplace=True)\n", + " print(\"Duplicate rows removed.\")\n", + "else:\n", + " print(\"No duplicate rows found.\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "from sklearn.preprocessing import LabelEncoder, OneHotEncoder\n", + "print(\"Separating target variable and features...\")\n", + "X = df.drop('Delivery_Time', axis=1)\n", + "y = df['Delivery_Time']\n", + "\n", + "print(\"Applying Label Encoding to target variable 'y'...\")\n", + "label_encoder = LabelEncoder()\n", + "y_encoded = label_encoder.fit_transform(y)\n", + "\n", + "print(\"Applying One-Hot Encoding to feature DataFrame 'X'...\")\n", + "onehot_encoder = OneHotEncoder(handle_unknown='ignore', sparse_output=False)\n", + "X_encoded = pd.DataFrame(onehot_encoder.fit_transform(X), columns=onehot_encoder.get_feature_names_out(X.columns))\n", + "\n", + "print(\"Verification of encoded data shapes:\")\n", + "print(f\"Shape of X_encoded: {X_encoded.shape}\")\n", + "print(f\"Shape of y_encoded: {y_encoded.shape}\")\n", + "\n", + "print(\"First 5 rows of X_encoded:\")\n", + "display(X_encoded.head())\n", + "print(\"First 5 elements of y_encoded:\")\n", + "print(y_encoded[:5])\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "\n", + "from sklearn.model_selection import train_test_split, StratifiedKFold\n", + "X = df.drop('Delivery_Time', axis=1)\n", + "y = df['Delivery_Time']\n", + "X_train, X_test, y_train, y_test = train_test_split(X,y, test_size=0.2, random_state=42, stratify=y)\n", + "print(f\"Train: {X_train.shape}, Test: {X_test.shape}\")\n", + "print(f\"Legendary in train: {y_train.sum()}, in test: {y_test.sum()}\")\n", + "# Scale features\n", + "scaler = StandardScaler()\n", + "X_train_scaled = scaler.fit_transform(X_train)\n", + "X_test_scaled = scaler.transform(X_test)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 6: Write your code here: Check for target imbalance and state if it is imbalanced or not (keep this cell empty if not needed)\n", + "# 1. Is the target imbalanced?\n", + "import seaborn as sns\n", + "import matplotlib.pyplot as plt\n", + "def check_target_imbalance(df, target_column):\n", + " print(\"Target Distribution:\")\n", + " print(df[target_column].value_counts(normalize=True))\n", + " sns.countplot(x=df[target_column])\n", + " plt.title(\"Target Distribution\")\n", + " plt.show()\n", + "\n", + "check_target_imbalance(df,\"Delivery_Time\") ## imbalanced will use stratified k fold" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "X = df.drop('Delivery_Time', axis=1)\n", + "y = df['Delivery_Time']" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:\n", + "from sklearn.model_selection import KFold\n", + "# Define K-Fold Cross Validation\n", + "kf = KFold(n_splits=5, shuffle=True, random_state=42)\n", + "\n", + "# Iterate through folds\n", + "for fold, (train_idx, test_idx) in enumerate(kf.split(X), start=1):\n", + " # indexing for each fold\n", + " X_train, X_test = X.iloc[train_idx], X.iloc[test_idx]\n", + " y_train, y_test = y.iloc[train_idx], y.iloc[test_idx]\n", + " # print shapes\n", + " print(f\"Fold {fold}\")\n", + " print(\" X_train shape:\", X_train.shape)\n", + " print(\" X_test shape :\", X_test.shape)\n", + " print(\" y_train shape:\", y_train.shape)\n", + " print(\" y_test shape :\", y_test.shape)\n", + " print(\"-\" * 30)\n", + "\n", + " ##3\n", + "from sklearn.ensemble import RandomForestClassifier\n", + "model = RandomForestClassifier(n_estimators=100, max_depth=15,\n", + " class_weight='balanced', random_state=42)\n", + "model.fit(X_train, y_train)\n", + "print(\"Model trained!\")\n", + "\n", + "# 4- Evaluate using MAE (Mean Absolute Error) ONLY\n", + "from sklearn.metrics import mean_absolute_error\n", + "# Predict and evaluate\n", + "y_pred = model.predict(X_test)\n", + "mae = mean_absolute_error(y_test, y_pred)\n", + "\n", + "## 5-Print the\n", + "print(f\"5-Fold CV Results:\")\n", + "print(f\"MAE: ${mae.mean():,.2f}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "# Feature importance\n", + "import pandas as pd\n", + "import matplotlib.pyplot as plt\n", + "\n", + "importance = pd.DataFrame({\n", + " 'feature': feature_cols,\n", + " 'importance': model.feature_importances_\n", + "}).sort_values('importance', ascending=False)\n", + "\n", + "plt.figure(figsize=(10, 6))\n", + "plt.barh(importance['feature'], importance['importance'], color='purple')\n", + "plt.xlabel('Importance')\n", + "plt.title('Feature Importance')\n", + "plt.gca().invert_yaxis()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "def check_target_distribution(df, target_column):\n", + " df[target_column].hist(bins=30, edgecolor='black') ## his=histogram\n", + "\n", + " plt.title(f\"Target Distribution ({target_column})\")\n", + " plt.xlabel(target_column)\n", + " plt.ylabel(\"Frequency\")\n", + " plt.grid(False)\n", + "\n", + " plt.show()\n", + "\n", + "check_target_distribution(df, \"y_pred\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/426/Q2.ipynb b/submissions_extracted/426/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..80d3d3b03b2392213350d102e4279a831073186b --- /dev/null +++ b/submissions_extracted/426/Q2.ipynb @@ -0,0 +1,372 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "##import required libraries\n", + "import kagglehub # for importing the dataset\n", + "import pandas as pd # dataframe stuff\n", + "import numpy as np # in general, it's a mathematical library\n", + "import torch # admin this lab\n", + "import torch.nn as nn # for building the model\n", + "from torch.optim import AdamW # optimizer\n", + "import matplotlib.pyplot as plt # visualizing\n", + "from torch.utils.data import TensorDataset,DataLoader # it's obvious\n", + "from sklearn.model_selection import train_test_split # literally obvious\n", + "from sklearn.preprocessing import StandardScaler, LabelEncoder # 🧐🧐🧐🧐\n", + "from sklearn.metrics import mean_absolute_error, mean_squared_error, r2_score\n", + "from torchvision.datasets import CIFAR10\n", + "from torchvision.transforms.functional import to_tensor\n", + "from torch.utils.data import DataLoader\n", + "import matplotlib.pyplot as plt\n", + "import torch.nn as nn\n", + "import torch.nn.functional as F\n", + "import torch\n", + "from torch.optim import AdamW" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q2-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import os\n", + "import pandas as pd\n", + "import numpy as np\n", + "from PIL import Image\n", + "from sklearn.model_selection import train_test_split\n", + "\n", + "# Load Labels\n", + "labels_df = pd.read_csv(os.path.join(path, \"labels.csv\"))\n", + "img_dir = os.path.join(path, \"images\")\n", + "\n", + "images = []\n", + "ages = []\n", + "\n", + "# Load Images and Resize\n", + "print(\"Loading images...\")\n", + "for index, row in labels_df.iterrows():\n", + " img_name = row.iloc[0]\n", + " age = row.iloc[1]\n", + " img_path = os.path.join(img_dir, img_name)\n", + "\n", + " if os.path.exists(img_path):\n", + " img = Image.open(img_path).convert('RGB')\n", + " img_array = np.array(img) / 255.0 # Normalize pixel values to [0, 1]\n", + " images.append(img_array)\n", + " ages.append(age)\n", + "\n", + "X = np.array(images)\n", + "y = np.array(ages)\n", + "\n", + "# Transpose image dimensions to match PyTorch format (N, C, H, W)\n", + "X = np.transpose(X, (0, 3, 1, 2))\n", + "\n", + "# Split Data\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n", + "\n", + "print(f\"X_train shape: {X_train.shape}\")\n", + "print(f\"X_test shape: {X_test.shape}\")\n", + "print(f\"y_train shape: {y_train.shape}\")\n", + "print(f\"y_test shape: {y_test.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 1. Convert Numpy arrays to PyTorch Tensors\n", + "import torch\n", + "X_train = torch.tensor(X_train, dtype=torch.float32)\n", + "X_test = torch.tensor(X_test, dtype=torch.float32)\n", + "y_train = torch.tensor(y_train, dtype=torch.float32)\n", + "y_test = torch.tensor(y_test, dtype=torch.float32)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 2. Create TensorDataset objects\n", + "from torch.utils.data import TensorDataset,DataLoader\n", + "# TensorDataset pairs input features (X) with their corresponding labels (y)\n", + "# Each item in the dataset is returned as (X[i], y[i])\n", + "train_dataset = TensorDataset(X_train, y_train)\n", + "test_dataset = TensorDataset(X_test, y_test)\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 3. Create DataLoaders\n", + "# Create Dataloaders to train and test data in batches\n", + "train_loader = DataLoader(train_dataset, batch_size=32, shuffle=True)\n", + "test_loader = DataLoader(test_dataset, batch_size=32, shuffle=False)\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 4. Print shape of one batch\n", + "# Get the first batch from the training DataLoader\n", + "X_batch, y_batch = next(iter(train_loader))\n", + "print(f\"Training batch input shape: {X_batch.shape}\")\n", + "print(f\"Training batch labels shape: {y_batch.shape}\")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 5. Display sample images\n", + "# Get one batch of images and labels\n", + "import matplotlib.pyplot as plt\n", + "images, labels = next(iter(train_loader))\n", + "\n", + "# Display the first 6 images in the batch\n", + "plt.figure(figsize=(8, 4))\n", + "\n", + "for i in range(6):\n", + " plt.subplot(2, 3, i + 1)\n", + "\n", + " # Convert from (C, H, W) to (H, W, C) for matplotlib\n", + " img = images[i].permute(1, 2, 0)\n", + "\n", + " plt.imshow(img)\n", + " plt.title(f\"Label: {labels[i].item()}\")\n", + " plt.axis('off')\n", + "\n", + "plt.tight_layout()\n", + "plt.show()\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your model class here:\n", + "import torch.nn\n", + "class NN4Layer(nn.Module):\n", + " def __init__(self, input_dim, hidden_dim, output_dim):\n", + " super(NN3Layer, self).__init__()\n", + "\n", + " # First linear layer: input features -> hidden layer\n", + " self.layer1 = nn.Linear(input_dim, hidden_dim)\n", + "\n", + " # Second linear layer: hidden layer -> hidden layer\n", + " self.layer2 = nn.Linear(hidden_dim, hidden_dim)\n", + "\n", + " # Third linear layer: hidden layer -> hidden layer\n", + " self.layer3 = nn.Linear(hidden_dim, hidden_dim)\n", + "\n", + " # Output layer: hidden layer -> number of classes (logits)\n", + " self.layer4 = nn.Linear(hidden_dim, output_dim) ## output حسب عدد الكلاسات\n", + "\n", + " # ReLU activation for non-linearity\n", + " self.relu = nn.ReLU()\n", + "\n", + " # Defines how input data flows through the network\n", + "def forward(self, x):\n", + " # First hidden layer\n", + " z1 = self.layer1(x)\n", + " a1 = self.relu(z1)\n", + "\n", + " # Second hidden layer\n", + " z2 = self.layer2(a1)\n", + " a2 = self.relu(z2)\n", + "\n", + " # Third hidden layer\n", + " z3 = self.layer3(a2)\n", + " a3 = self.relu(z3)\n", + "\n", + " # Output layer (raw scores / logits)\n", + " output = self.layer4(a3) # there is something missing here, remember? :)\n", + "\n", + " ## بستخدم كروس انتروبي لوس داخلها السوفت ماكس الردي عشان كذا ماعرفت السوفت ماكس\n", + "## وباينري كروس انتروبي لازم ادخلها قبل في سقمويد\n", + "\n", + " return z4" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your training loop here:\n", + "def train_one_epoch(model, optimizer, criterion, train_loader, device):\n", + " # Set the model to training mode\n", + " model.train()\n", + "\n", + " running_loss = 0.0\n", + "\n", + " for X_batch, y_batch in train_loader:\n", + " # Move batch to the selected device\n", + " X_batch = X_batch.view(X_batch.size(0), -1).to(device)\n", + " y_batch = y_batch.to(device)\n", + "\n", + " # Forward pass\n", + " # TODO: make predictions\n", + " outputs = model(X_batch) # shape: (batch_size, 10)\n", + " # TODO: compute loss\n", + " loss = criterion(outputs, y_batch)\n", + "\n", + " # Backward pass & optimization\n", + " optimizer.zero_grad() # Clear previous gradients\n", + " loss.backward() # Compute gradients\n", + " optimizer.step() # Update model parameters\n", + "\n", + " running_loss += loss.item()\n", + "\n", + " # Average loss over all batches\n", + " avg_loss = running_loss / len(train_loader)\n", + "\n", + " return avg_loss" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your validation loop here:\n", + "def validate(model, criterion, test_loader, device):\n", + " # Set the model to evaluation mode\n", + " model.eval()\n", + "\n", + " running_loss = 0.0\n", + " correct = 0\n", + " total = 0" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Define device, model, loss, optimizer:\n", + " ##Model, Criterion, Optimizer\n", + " output = []\n", + "input_dim = X_train.shape[1]\n", + "hidden_dim = 10\n", + "model =NN4Layer(input_dim=input_dim, hidden_dim=hidden_dim, output_dim=output).to(device)\n", + "criterion = nn.BCELoss()\n", + "optimizer = Adam(model.parameters(), lr=learning_rate)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Start training for 20 epochs:\n", + "def train_one_epoch(model, optimizer, criterion, train_loader, device):\n", + " # Set the model to training mode\n", + " model.train()\n", + "\n", + " running_loss = 0.0\n", + "\n", + " for X_batch, y_batch in train_loader:\n", + " # Move batch to the selected device\n", + " X_batch = X_batch.to(device)\n", + " y_batch = y_batch.view(-1, 1).to(device) ## .view كان [30] والاوتبوت فيه عمود ١ فعشان يزيده\n", + "\n", + " # Forward pass\n", + " outputs = model(X_batch)\n", + " loss = criterion(outputs, y_batch)\n", + "\n", + " # Backward pass & optimization\n", + " optimizer.zero_grad() # Clear previous gradients\n", + " loss.backward() # Compute gradients\n", + " optimizer.step() # Update model parameters\n", + "\n", + " running_loss += loss.item() ## لاني ادرب باتش فابغى اخذ افيرج للوس\n", + "\n", + " # Average loss over all batches\n", + " avg_loss = running_loss / len(train_loader)\n", + "\n", + " return avg_loss" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "# Plotting results\n", + "import matplotlib.pyplot as plt\n", + "plt.figure(figsize=(7, 5))\n", + "\n", + "plt.plot(train_losses, label='Train Loss')\n", + "plt.plot(val_losses, label='Validation Loss')\n", + "plt.title('Loss over Epochs')\n", + "plt.xlabel('Epoch')\n", + "plt.ylabel('Loss')\n", + "plt.legend()\n", + "\n", + "plt.tight_layout()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2 (Bonus): Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/426/Q3.ipynb b/submissions_extracted/426/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..a44609f19bb98bb44f00c169788d2aa66e4c5da0 --- /dev/null +++ b/submissions_extracted/426/Q3.ipynb @@ -0,0 +1,270 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "\n", + "# Download latest version\n", + "\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q3-exam-data\")\n", + "\n", + "\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "import pandas as pd\n", + "import os\n", + "csv_path = os.path.join(path, \"Q3_data.csv\")\n", + "df = pd.read_csv(csv_path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "df.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "df.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "# Analyze missing values\n", + "missing_percentage = (df.isnull().sum() / len(dfcadfrs)) * 100\n", + "missing_data = pd.DataFrame({\n", + " 'Column': missing_percentage.index,\n", + " 'Missing_Percentage': missing_percentage.values\n", + "})\n", + "missing_data = missing_data[missing_data['Missing_Percentage'] > 0].sort_values('Missing_Percentage', ascending=False)\n", + "\n", + "print(\"Missing Data Analysis:\")\n", + "missing_data.head(10)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "print(\"Checking for duplicate rows...\")\n", + "duplicate_rows = df.duplicated().sum()\n", + "if duplicate_rows > 0:\n", + " print(f\"Found {duplicate_rows} duplicate rows. Removing them...\")\n", + " df.drop_duplicates(inplace=True)\n", + " print(\"Duplicate rows removed.\")\n", + "else:\n", + " print(\"No duplicate rows found.\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here: NO NEED" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "# Feature Scaling\n", + "from sklearn.preprocessing import StandardScaler\n", + "scaler = StandardScaler()\n", + "X_scaled = scaler.fit_transform(X)\n", + "X = df.drop(Target, axis=1)\n", + "y = df[Target]" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:Is the target imbalanced?\n", + "import seaborn as sns\n", + "import matplotlib.pyplot as plt\n", + "import\n", + "def check_target_imbalance(df, target_column):\n", + " print(\"Target Distribution:\")\n", + " print(df[target_column].value_counts(normalize=True))\n", + " sns.countplot(x=df[target_column])\n", + " plt.title(\"Target Distribution\")\n", + " plt.show()\n", + "\n", + "check_target_imbalance(df,\"Delivery_Time\") ## imbalanced will use stratified k fold" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "X = df.drop('Target', axis=1)\n", + "y = df['Target']" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:\n", + "from sklearn.model_selection import KFold\n", + "# Define K-Fold Cross Validation\n", + "kf = KFold(n_splits=5, shuffle=True, random_state=42)\n", + "\n", + "# Iterate through folds\n", + "for fold, (train_idx, test_idx) in enumerate(kf.split(X), start=1):\n", + " # indexing for each fold\n", + " X_train, X_test = X.iloc[train_idx], X.iloc[test_idx]\n", + " y_train, y_test = y.iloc[train_idx], y.iloc[test_idx]\n", + " # print shapes\n", + " print(f\"Fold {fold}\")\n", + " print(\" X_train shape:\", X_train.shape)\n", + " print(\" X_test shape :\", X_test.shape)\n", + " print(\" y_train shape:\", y_train.shape)\n", + " print(\" y_test shape :\", y_test.shape)\n", + " print(\"-\" * 30)\n", + " from catboost import CatBoostClassifier\n", + " \"CatBoost\": CatBoostClassifier(\n", + " verbose=0,\n", + " n_estimators=320,\n", + " max_depth=4\n", + " )\n", + "all_results = {}\n", + "\n", + "for name in sklearn_models:\n", + " all_results[name] = {'accuracy': [], 'precision': [], 'recall': [], 'f1': []}" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:# Task 1: Write your code here:\n", + "# Gather importances from the models (from the last fold)\n", + "importances = {}\n", + "\n", + "importances['CatBoost'] = sklearn_models['CatBoost'].feature_importances_\n", + "\n", + "# Create a 1x3 plot\n", + "fig, axes = plt.subplots(1, 3, figsize=(18, 6))\n", + "axes = axes.flatten()\n", + "features = X.columns\n", + "\n", + "for i, (model_name, imp) in enumerate(importances.items()):\n", + " # Sort features by importance for a cleaner plot\n", + " sorted_idx = np.argsort(imp)\n", + "\n", + " ax = axes[i]\n", + " ax.barh(features[sorted_idx], imp[sorted_idx])\n", + " ax.set_title(f\"{model_name} Feature Importance\")\n", + " ax.set_xlabel(\"Importance Score\")\n", + "\n", + "plt.tight_layout()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "coeffs = {}\n", + "\n", + "coeffs['Lasso'] = models['LASSO Regression'].coef_\n", + "coeffs['Ridge'] = models['Ridge Regression'].coef_\n", + "\n", + "fig, axes = plt.subplots(1, 2, figsize=(15, 6))\n", + "axes = axes.flatten()\n", + "features = X.columns\n", + "\n", + "for i, (model_name, coef) in enumerate(coeffs.items()):\n", + " # Sort features by absolute coefficient value\n", + " absolute_coef = np.abs(coef)\n", + " sorted_idx = np.argsort(absolute_coef)\n", + "\n", + " ax = axes[i]\n", + " ax.barh(features[sorted_idx], coef[sorted_idx])\n", + " ax.set_title(f\"{model_name} Coefficients\")\n", + " ax.set_xlabel(\"Coefficient Value (Impact)\")\n", + "\n", + "plt.tight_layout()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/427/Q1.ipynb b/submissions_extracted/427/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..c9a1247ac6e079fd331b49a4aeadd39bbd293b33 --- /dev/null +++ b/submissions_extracted/427/Q1.ipynb @@ -0,0 +1,194 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q1-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "import pandas as pd\n", + "df = pd.read_csv('/kaggle/input/q1-exam-data/Q1_data.csv')\n", + "\n", + "df" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "cols = ['price', 'year', 'manufacturer', 'condition', 'cylinders', 'fuel', 'odometer', 'transmission', 'type']\n", + "df_clean = df[cols].copy()\n", + "\n", + "# Drop rows where target (price) or key features are missing - can't predict without them\n", + "print(f\"Before: {df_clean.shape}\")\n", + "df_clean = df_clean.dropna(subset=['price', 'year', 'odometer'])\n", + "print(f\"After dropping missing price/year/odometer: {df_clean.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 6: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "class SimpleNN(nn.Module):\n", + " def __init__(self, input_dim, output_dim):\n", + " super(SimpleNN, self).__init__()\n", + " self.layer1 = nn.Linear(input_dim, 64)\n", + " self.output = nn.Linear(64, output_dim)\n", + " self.relu = nn.ReLU()\n", + "\n", + " def forward(self, x):\n", + " x = self.relu(self.layer1(x))\n", + " x = self.output(x)\n", + " return x\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:\n", + "KFold (shuffle=True)\n", + "\n", + "skf = KFold(n_splits=5)\n", + " for train_index, test_index in skf.split(X, y):\n", + " # Split data into training and testing sets\n", + " X_Train, X_Test = X.loc[train_index, :], X.loc[test_index, :]\n", + " y_Train, y_Test = y.iloc[train_index], y.iloc[test_index]\n", + " # Train the model\n", + " model.fit(X_Train, y_Train)\n", + " # Predict on the test set\n", + " y_pred = model.predict(X_Test)\n", + "\n", + " # Calculate metrics\n", + " scores_f1.append(f1_score(y_Test, y_pred, average='weighted'))\n", + "\n", + " # Print the results\n", + " print(f\"{model_name} F1-Score: {np.mean(scores_f1):.4f}\")\n", + " print(\"\\n\")\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "plt.figure(figsize=(18, 14))\n", + "plt.barh(features, importances, color='orange')\n", + "plt.xlabel('Importance Score')\n", + "plt.ylabel('Features')\n", + "plt.title('CatBoost Feature Importance')\n", + "plt.gca().invert_yaxis() # Invert y-axis to show the most important features at the top\n", + "plt.show()\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/427/Q2.ipynb b/submissions_extracted/427/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..1dec67d62b6ac461c57179c2bab67ee5e1ef5f47 --- /dev/null +++ b/submissions_extracted/427/Q2.ipynb @@ -0,0 +1,411 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q2-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import os\n", + "import pandas as pd\n", + "import numpy as np\n", + "from PIL import Image\n", + "from sklearn.model_selection import train_test_split\n", + "from torchvision.transforms.functional import to_tensor\n", + "# Load Labels\n", + "labels_df = pd.read_csv(os.path.join(path, \"labels.csv\"))\n", + "img_dir = os.path.join(path, \"images\")\n", + "\n", + "images = []\n", + "ages = []\n", + "\n", + "# Load Images and Resize\n", + "print(\"Loading images...\")\n", + "for index, row in labels_df.iterrows():\n", + " img_name = row.iloc[0]\n", + " age = row.iloc[1]\n", + " img_path = os.path.join(img_dir, img_name)\n", + "\n", + " if os.path.exists(img_path):\n", + " img = Image.open(img_path).convert('RGB')\n", + " img_array = np.array(img) / 255.0 # Normalize pixel values to [0, 1]\n", + " images.append(img_array)\n", + " ages.append(age)\n", + "\n", + "X = np.array(images)\n", + "y = np.array(ages)\n", + "\n", + "# Transpose image dimensions to match PyTorch format (N, C, H, W)\n", + "X = np.transpose(X, (0, 3, 1, 2))\n", + "\n", + "# Split Data\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n", + "\n", + "print(f\"X_train shape: {X_train.shape}\")\n", + "print(f\"X_test shape: {X_test.shape}\")\n", + "print(f\"y_train shape: {y_train.shape}\")\n", + "print(f\"y_test shape: {y_test.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "train_dataset = images(\n", + " root='./datasets', # Dataset storage path\n", + " train=True, # Use training data\n", + " transform=to_tensor, # Convert images to tensors\n", + " download=True # Download if not available\n", + ")\n", + "\n", + "# Testing dataset\n", + "test_dataset =images(\n", + " root='./datasets', # Dataset storage path\n", + " train=False, # Use test data\n", + " transform=to_tensor, # Convert images to tensors\n", + " download=True # Download if not available\n", + ")\n", + "\n", + "# print one sample from the dataset\n", + "# Each sample consists of an image tensor and its label\n", + "sample_image, sample_label = train_dataset[0]\n", + "\n", + "print(f\"\\n Image shape: {sample_image.shape}\") # (1, 28, 28)\n", + "print(f\"Label: {sample_label}\")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 2. Create TensorDataset objects\n", + "\n", + "train_loader = DataLoader(\n", + " train_dataset,\n", + " batch_size=32,\n", + " shuffle=True,\n", + " num_workers=2\n", + ")\n", + "# DataLoader for test/validation data\n", + "test_loader = DataLoader(\n", + " test_dataset,\n", + " batch_size=32,\n", + " shuffle=False,\n", + " num_workers=2\n", + ")\n", + "# Get the first batch from the training DataLoader\n", + "X_batch, y_batch = next(iter(train_loader))\n", + "print(f\"Training batch input shape: {X_batch.shape}\")\n", + "print(f\"Training batch labels shape: {y_batch.shape}\")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 3. Create DataLoaders\n", + "\n", + "images, labels = next(iter(train_loader))\n", + "\n", + "# Display the first 6 images in the batch\n", + "plt.figure(figsize=(8, 4))\n", + "\n", + "for i in range(6):\n", + " plt.subplot(2, 3, i + 1)\n", + " plt.imshow(images[i].squeeze(), cmap='gray')\n", + " plt.title(f\"Label: {labels[i].item()}\")\n", + " plt.axis('off')\n", + "\n", + "plt.tight_layout()\n", + "plt.show()\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 4. Print shape of one batch\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 5. Display sample images\n", + "\n", + "images, labels = next(iter(train_loader))\n", + "\n", + "# Display the first 6 images in the batch\n", + "plt.figure(figsize=(8, 4))\n", + "\n", + "for i in range(6):\n", + " plt.subplot(2, 3, i + 1)\n", + "\n", + " # Convert from (C, H, W) to (H, W, C) for matplotlib\n", + " img = images[i].permute(1, 2, 0)\n", + "\n", + " plt.imshow(img)\n", + " plt.title(f\"Label: {labels[i].item()}\")\n", + " plt.axis('off')\n", + "\n", + "plt.tight_layout()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your model class here:\n", + " def __init__(self, input_dim, hidden_dim, output_dim):\n", + " super(NN4Layer, self).__init__()\n", + "\n", + " # First linear layer: input features -> hidden layer\n", + " self.layer1 = nn.Linear(input_dim, hidden_dim)\n", + "\n", + " # Second linear layer: hidden layer -> hidden layer\n", + " self.layer2 = nn.Linear(hidden_dim, hidden_dim)\n", + "\n", + " # Output layer: hidden layer -> number of classes (logits)\n", + " self.layer3 = nn.Linear(hidden_dim, hidden_dim)\n", + "\n", + " self.layer4 = nn.Linear(hidden_dim, output_dim)\n", + " # ReLU activation for non-linearity\n", + " self.relu = nn.ReLU()\n", + "\n", + " # Defines how input data flows through the network\n", + " def forward(self, x):\n", + " # First hidden layer\n", + " z1 = self.layer1(x)\n", + " a1 = self.relu(z1)\n", + "\n", + " # Second hidden layer\n", + " z2 = self.layer2(a1)\n", + " a2 = self.relu(z2)\n", + "\n", + " z3 = self.layer2(a2)\n", + " a3 = self.relu(z3)\n", + "\n", + " # Output layer (raw scores / logits)\n", + " output = self.layer4(a3) # there is something missing here, remember? :)\n", + "\n", + " return output" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your training loop here:\n", + "def train_one_epoch(model, optimizer, criterion, train_loader, device):\n", + " # Set the model to training mode\n", + " model.train()\n", + "\n", + " running_loss = 0.0\n", + "\n", + " for X_batch, y_batch in train_loader:\n", + " # Move batch to the selected device\n", + " X_batch = X_batch.view(X_batch.size(0), -1).to(device)\n", + " y_batch = y_batch.to(device)\n", + "\n", + " # Forward pass\n", + " outputs = model(X_batch) # shape: (batch_size, 10)\n", + " loss = criterion(outputs, y_batch)\n", + "\n", + " # Backward pass & optimization\n", + " optimizer.zero_grad() # Clear previous gradients\n", + " loss.backward() # Compute gradients\n", + " optimizer.step() # Update model parameters\n", + "\n", + " running_loss += loss.item()\n", + "\n", + " # Average loss over all batches\n", + " avg_loss = running_loss / len(train_loader)\n", + "\n", + " return avg_loss" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your validation loop here:\n", + "def validate(model, criterion, test_loader, device):\n", + " # Set the model to evaluation mode\n", + " model.eval()\n", + "\n", + " running_loss = 0.0\n", + " correct = 0\n", + " total = 0\n", + "\n", + " with torch.no_grad():\n", + " for X_batch, y_batch in test_loader:\n", + " # Move data to device\n", + " X_batch = X_batch.view(X_batch.size(0), -1).to(device)\n", + " y_batch = y_batch.to(device)\n", + "\n", + " # Forward pass\n", + " outputs = model(X_batch) # shape: (batch_size, 10)\n", + " loss = criterion(outputs, y_batch)\n", + " running_loss += loss.item()\n", + "\n", + " # Apply Softmax to get probabilities\n", + " probabilities = F.softmax(outputs, dim=1)\n", + "\n", + " # Multiclass predictions\n", + " predicted = torch.argmax(probabilities, dim=1)\n", + "\n", + " # Accuracy calculation\n", + " correct += (predicted == y_batch).sum().item()\n", + " total += y_batch.size(0)\n", + "\n", + " avg_loss = running_loss / len(test_loader)\n", + " accuracy = correct / total\n", + "\n", + " return avg_loss, accuracy\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Define device, model, loss, optimizer:\n", + "num_epochs = 20\n", + "# TODO: choose a learning rate (try different values and evaluate results)\n", + "learning_rate = 0.001\n", + "\n", + "# TODO: Define criterion (loss function) (hint: what loss do we use for multiclass ?)\n", + "criterion = nn.CrossEntropyLoss()\n", + "# TODO: Define optimizer(what is updated during training?)\n", + "optimizer = AdamW(model.parameters(), learning_rate)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Start training for 20 epochs:\n", + "dtrain_losses = []\n", + "val_losses = []\n", + "val_accuracies = []\n", + "\n", + "print('Starting Training...')\n", + "for epoch in range(num_epochs):\n", + " # Train one epoch\n", + " train_loss = train_one_epoch(model, optimizer, criterion, train_loader, device)\n", + "\n", + " # Validate\n", + " val_loss, val_accuracy = validate(model, criterion, test_loader, device)\n", + "\n", + " train_losses.append(train_loss)\n", + " val_losses.append(val_loss)\n", + " val_accuracies.append(val_accuracy)\n", + "\n", + " print(f'Epoch [{epoch+1}/{num_epochs}], Train Loss: {train_loss:.4f}, Val Loss: {val_loss:.4f}, Val Accuracy: {val_accuracy:.4f}')\n", + "\n", + "print('Training Complete!')" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "plt.figure(figsize=(7, 5))\n", + "\n", + "plt.plot(train_losses, label='Train Loss')\n", + "plt.plot(val_losses, label='Validation Loss')\n", + "plt.title('Loss over Epochs')\n", + "plt.xlabel('Epoch')\n", + "plt.ylabel('Loss')\n", + "plt.legend()\n", + "\n", + "plt.tight_layout()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2 (Bonus): Write your code here:\n", + "odel.eval()\n", + "# Get one batch from the test DataLoader\n", + "images, labels = next(iter(test_loader))\n", + "# Move images to device\n", + "images = images.to(device)\n", + "labels = labels.to(device)\n", + "\n", + "with torch.no_grad():\n", + " # Flatten images before passing to the model\n", + " outputs = model(images.view(images.size(0), -1))\n", + " predictions = torch.argmax(outputs, dim=1)\n", + "\n", + "# Move tensors back to CPU for plotting\n", + "images = images.cpu()\n", + "labels = labels.cpu()\n", + "predictions = predictions.cpu()\n", + "\n", + "# Plot first 6 predictions\n", + "plt.figure(figsize=(8, 4))\n", + "for i in range(6):\n", + " plt.subplot(2, 3, i + 1)\n", + " plt.imshow(images[i].squeeze(), cmap='gray')\n", + " plt.title(f\"True: {labels[i]} | Pred: {predictions[i]}\")\n", + " plt.axis('off')\n", + "\n", + "plt.tight_layout()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/427/Q3.ipynb b/submissions_extracted/427/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..b34e28eca3757dec0b807e209da37ea98b292dfe --- /dev/null +++ b/submissions_extracted/427/Q3.ipynb @@ -0,0 +1,232 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "\n", + "\n", + "# Download latest version\n", + "\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q3-exam-data\")\n", + "\n", + "\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "import pandas as pd\n", + "df = pd.read_csv('/kaggle/input/q3-exam-data/Q3_data.csv')\n", + "df" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "df.info()\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "df.describe()\n", + "\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "categorical_cols = ['manufacturer', 'condition', 'cylinders', 'fuel', 'transmission', 'type']\n", + "for col in categorical_cols:\n", + " le = LabelEncoder()\n", + " df_clean[col] = le.fit_transform(df_clean[col].astype(str))\n", + "\n", + "df_clean.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "class SimpleNN(nn.Module):\n", + " def __init__(self, input_dim, output_dim):\n", + " super(SimpleNN, self).__init__()\n", + " self.layer1 = nn.Linear(input_dim, 64)\n", + " self.output = nn.Linear(64, output_dim)\n", + " self.relu = nn.ReLU()\n", + "\n", + " def forward(self, x):\n", + " x = self.relu(self.layer1(x))\n", + " x = self.output(x)\n", + " return x\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:\n", + "\n", + "from sklearn.model_selection import StratifiedKFold\n", + "\n", + "# Use previously generated random classification data\n", + "X, y = X_clf.copy(), y_clf.copy()\n", + "\n", + "# Show full dataset class distribution\n", + "full_ratio = (y.value_counts(normalize=True) * 100).sort_index()\n", + "print(\"Full Dataset Class Distribution\")\n", + "print(\" y class percentages:\", {k: f\"{v:.2f}%\" for k, v in full_ratio.items()})\n", + "print(\"-\" * 40)\n", + "\n", + "# Define Stratified K-Fold\n", + "skf = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)\n", + "\n", + "print(\"Stratified K-Fold Cross Validation\\n\" + \"-\"*40)\n", + "\n", + "for fold, (train_idx, test_idx) in enumerate(skf.split(X, y), start=1):\n", + " # indexing for each fold\n", + " X_train, X_test = X.iloc[train_idx], X.iloc[test_idx]\n", + " y_train, y_test = y.iloc[train_idx], y.iloc[test_idx]\n", + "\n", + " print(f\"Fold {fold}\")\n", + " print(\" X_train shape:\", X_train.shape)\n", + " print(\" X_test shape :\", X_test.shape)\n", + " print(\" y_train shape:\", y_train.shape)\n", + " print(\" y_test shape :\", y_test.shape)\n", + "\n", + " # showing class distribution\n", + " train_ratio = (y_train.value_counts(normalize=True) * 100).sort_index()\n", + " test_ratio = (y_test.value_counts(normalize=True) * 100).sort_index()\n", + "\n", + " print(\" y_train class percentages:\", {k: f\"{v:.2f}%\" for k, v in train_ratio.items()})\n", + " print(\" y_test class percentages :\", {k: f\"{v:.2f}%\" for k, v in test_ratio.items()})\n", + "\n", + " print(\"-\" * 40)\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "for model_name in results:\n", + " print(f\"\\n{model_name}:\")\n", + " # Print the average of each evaluation metric across folds\n", + " print(f\" Accuracy: {np.mean(results[model_name]['accuracy']):.4f}\")\n", + " print(f\" F1-Score: {np.mean(results[model_name]['f1']):.4f}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/428/Q1.ipynb b/submissions_extracted/428/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..ca6196950c7c6f915bfb6cd0ec7f0e6bcef99003 --- /dev/null +++ b/submissions_extracted/428/Q1.ipynb @@ -0,0 +1,236 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q1-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import numpy as np\n", + "import pandas as pd\n", + "import matplotlib.pyplot as plt\n", + "import os\n", + "import kagglehub\n", + "\n", + "from sklearn.model_selection import train_test_split, KFold\n", + "from sklearn.preprocessing import StandardScaler, LabelEncoder\n", + "from sklearn.ensemble import RandomForestRegressor\n", + "from sklearn.metrics import mean_absolute_error, mean_squared_error\n", + "\n", + "import warnings\n", + "warnings.filterwarnings('ignore')\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Load the dataset\n", + "cars_path =os.path.join(path, 'Q1_data.csv')\n", + "df_cars = pd.read_csv(cars_path)\n", + "df_cars.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Check data types and structure\n", + "df_cars.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Descriptive statistics for numerical columns\n", + "df_cars.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "df = df.drop(columns='Order_ID')" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 6: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Define features (X) and target (y)\n", + "feature_cols = ['year', 'odometer', 'age', 'miles_per_year',\n", + " 'manufacturer', 'condition', 'cylinders', 'fuel', 'transmission', 'type',\n", + " 'age_x_miles_per_year']\n", + "X = df_clean[feature_cols]\n", + "y = df_clean['price']\n", + "\n", + "# Train-test split (80% train, 20% test)\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n", + "print(f\"Train: {X_train.shape}, Test: {X_test.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/428/Q2.ipynb b/submissions_extracted/428/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..e9a5814dac129f60265fd85b0e196de5bf455481 --- /dev/null +++ b/submissions_extracted/428/Q2.ipynb @@ -0,0 +1,302 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q2-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "from sklearn.datasets import load_breast_cancer\n", + "from sklearn.model_selection import train_test_split\n", + "from sklearn.preprocessing import StandardScaler\n", + "from torch.utils.data import TensorDataset\n", + "from torch.utils.data import DataLoader\n", + "import torch\n", + "\n", + "# load data\n", + "data = load_breast_cancer()\n", + "X = data.data\n", + "y = data.target\n", + "\n", + "# Split the dataset into training and testing sets\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42, stratify=y)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 2. Create TensorDataset objects\n", + "\n", + "print(X_train, X_test, y_train, y_test)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import os\n", + "import pandas as pd\n", + "import numpy as np\n", + "from PIL import Image\n", + "from sklearn.model_selection import train_test_split\n", + "\n", + "# Load Labels\n", + "labels_df = pd.read_csv(os.path.join(path, \"labels.csv\"))\n", + "img_dir = os.path.join(path, \"images\")\n", + "\n", + "images = []\n", + "ages = []\n", + "\n", + "# Load Images and Resize\n", + "print(\"Loading images...\")\n", + "for index, row in labels_df.iterrows():\n", + " img_name = row.iloc[0]\n", + " age = row.iloc[1]\n", + " img_path = os.path.join(img_dir, img_name)\n", + "\n", + " if os.path.exists(img_path):\n", + " img = Image.open(img_path).convert('RGB')\n", + " img_array = np.array(img) / 255.0 # Normalize pixel values to [0, 1]\n", + " images.append(img_array)\n", + " ages.append(age)\n", + "\n", + "X = np.array(images)\n", + "y = np.array(ages)\n", + "\n", + "# Transpose image dimensions to match PyTorch format (N, C, H, W)\n", + "X = np.transpose(X, (0, 3, 1, 2))\n", + "\n", + "# Split Data\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n", + "\n", + "print(f\"X_train shape: {X_train.shape}\")\n", + "print(f\"X_test shape: {X_test.shape}\")\n", + "print(f\"y_train shape: {y_train.shape}\")\n", + "print(f\"y_test shape: {y_test.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 3. Create DataLoaders\n", + "import torch\n", + "\n", + "# Create tensors\n", + "x = torch.tensor([1.0, 2.0, 3.0])\n", + "y = torch.randn(3)\n", + "print(\"x:\", x)\n", + "print(\"y:\", y)\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 4. Print shape of one batch\n", + " # Move batch to the selected device\n", + " X_batch = X_batch.to(device)\n", + " y_batch = y_batch.view(-1, 1).to(device)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 5. Display sample images\n", + "\n", + "import torch\n", + "\n", + "# 1️⃣ Flatten - Convert any shape to (batch_size, features)\n", + "x = torch.randn(32, 3, 28, 28)\n", + "x_flat = x.flatten(start_dim=1)\n", + "print(\"Flatten:\", x_flat.shape) # (32, 2352)\n", + "\n", + "# 2️⃣ Squeeze - Remove dimensions with size 1\n", + "x = torch.randn(1, 3, 28, 28)\n", + "x_sq = x.squeeze()\n", + "print(\"Squeeze:\", x_sq.shape) # (3, 28, 28)\n", + "\n", + "# 3️⃣ Unsqueeze - Add a new dimension of size 1\n", + "x = torch.randn(3, 28, 28)\n", + "x_unsq = x.unsqueeze(0)\n", + "print(\"Unsqueeze:\", x_unsq.shape) # (1, 3, 28, 28)\n", + "\n", + "# 4️⃣ View - Reshape freely while keeping same number of elements\n", + "x = torch.randn(32, 28, 28, 3)\n", + "x_view = x.view(32, -1) # Flatten all except batch\n", + "print(\"View:\", x_view.shape) # (32, 28*28*3)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "data = load_breast_cancer()\n", + "\n", + "X = data.data\n", + "y = data.target\n", + "\n", + "# Split the dataset into training and testing sets\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42, stratify=y)\n", + "\n", + "# Standardize the data\n", + "scaler = StandardScaler()\n", + "X_train = scaler.fit_transform(X_train)\n", + "X_test = scaler.transform(X_test)\n", + "\n", + "# transform to tensors\n", + "X_train = torch.tensor(X_train, dtype=torch.float32)\n", + "X_test = torch.tensor(X_test, dtype=torch.float32)\n", + "y_train = torch.tensor(y_train, dtype=torch.float32)\n", + "y_test = torch.tensor(y_test, dtype=torch.float32)\n", + "\n", + "# Create TensorDatasets for training and testing\n", + "train_dataset = TensorDataset(X_train, y_train)\n", + "test_dataset = TensorDataset(X_test, y_test)\n", + "\n", + "# Create Dataloaders to train and test data in batches\n", + "train_loader = DataLoader(train_dataset, batch_size=32, shuffle=True)\n", + "test_loader = DataLoader(test_dataset, batch_size=32, shuffle=False)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "\n", + " # Defines how input data flows through the network\n", + " def forward(self, x):\n", + " # First hidden layer\n", + " a1 = self.relu(self.layer1(x))\n", + "\n", + " # Second hidden layer\n", + " a2 = self.relu(self.layer2(a1))\n", + "\n", + " # Third hidden layer\n", + " a3 = self.relu(self.layer3(a2))\n", + "\n", + " # Output layer (raw scores / logits)\n", + " output = self.layer4(a3) # we said we'll use softmax, where is it? ¯\\(ツ)/¯\n", + "\n", + " return output\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your training loop here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your validation loop here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Define device, model, loss, optimizer:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Start training for 20 epochs:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import matplotlib.pyplot as plt" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "# Plotting results\n", + "plt.figure(figsize=(7, 5))\n", + "\n", + "plt.plot(train_losses, label='Train Loss')\n", + "plt.plot(val_losses, label='Validation Loss')\n", + "plt.title('Loss over Epochs')\n", + "plt.xlabel('Epoch')\n", + "plt.ylabel('Loss')\n", + "plt.legend()\n", + "\n", + "plt.tight_layout()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2 (Bonus): Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/429/Q1.ipynb b/submissions_extracted/429/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..ed8ae8ad9a56e2f9043a03e2bbcc3eba6bd1730b --- /dev/null +++ b/submissions_extracted/429/Q1.ipynb @@ -0,0 +1,456 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "from IPython.display import clear_output\n", + "\n", + "%pip install kagglehub catboost lightgbm tqdm -q\n", + "\n", + "clear_output()\n", + "\n", + "import pandas as pd\n", + "import numpy as np\n", + "import matplotlib.pyplot as plt\n", + "import seaborn as sns\n", + "import kagglehub\n", + "import os\n", + "from tqdm import tqdm\n", + "\n", + "%matplotlib inline\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q1-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "csv_path = os.path.join(path, \"Q1_data.csv\")\n", + "\n", + "df = pd.read_csv(csv_path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "df.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "df.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "def check_target_distribution(df, target_column):\n", + " df[target_column].hist(bins=30, edgecolor='black')\n", + "\n", + " plt.title(f\"Target Distribution ({target_column})\")\n", + " plt.xlabel(target_column)\n", + " plt.ylabel(\"Frequency\")\n", + " plt.grid(False)\n", + "\n", + " plt.show()\n", + "\n", + "check_target_distribution(df,\"Delivery_Time\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "# Define stat columns\n", + "stat_cols = ['Order_ID']\n", + "\n", + "# Drop rows with missing stat values\n", + "df = df.dropna(subset=stat_cols)\n", + "print(f\"Shape after cleaning: {df.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "# 2. Do we have missing values?\n", + "def check_missing_values(df):\n", + " missing_values = df.isnull().sum()\n", + " print(\"Missing Values per Column:\")\n", + " print(missing_values[missing_values > 0])\n", + " if missing_values.any():\n", + " print(\"\\nHandle Missing Values as needed.\")\n", + " else:\n", + " print(\"\\nNo Missing Values Found.\")\n", + "\n", + "# 3. Do we have categorical columns?\n", + "def encode_categorical_columns(df):\n", + " categorical_cols = df.select_dtypes(include=[\"object\"]).columns\n", + " print(\"Categorical Columns:\", list(categorical_cols))\n", + "\n", + "# Fill categorical columns with 'unknown' - missing likely means \"not specified\"\n", + "for col in ['Weather', 'Traffic_Level', 'Time_of_Day']:\n", + " df[col] = df[col].fillna('unknown')\n", + "\n", + "# Fill Delivery_Time with mean\n", + "df['Delivery_Time'] = df['Delivery_Time'].fillna(df['Delivery_Time'].mean())\n", + "\n", + "# Fill Delivery_Time with mean\n", + "df['Courier_Experience_yrs'] = df['Courier_Experience_yrs'].fillna(df['Courier_Experience_yrs'].mean())\n", + "\n", + "check_missing_values(df)\n", + "\n", + "print(\"Missing values remaining:\", df.isnull().sum().sum())" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "def check_duplicates(df):\n", + " duplicates = df.duplicated().sum()\n", + " print(f\"Number of Duplicate Samples: {duplicates}\")\n", + " if duplicates > 0:\n", + " print(\"Dropping Duplicates...\")\n", + " df.drop_duplicates(inplace=True)\n", + " print(\"Duplicates Dropped.\")\n", + " else:\n", + " print(\"No Duplicate Samples Found.\")\n", + "\n", + "check_duplicates(df)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "\n", + "from sklearn.preprocessing import OneHotEncoder\n", + "\n", + "categorical_data = [['Weather'], ['Traffic_Level'], ['Time_of_Day'],['Vehicle_Type']]\n", + "\n", + "print(f\"Original Data:\\n{categorical_data}\\n\")\n", + "\n", + "# 2. Initialize the encoder (Ensure output is dense/numpy array)\n", + "my_encoder = OneHotEncoder(sparse_output = False)\n", + "\n", + "# 3. Fit and Transform the data\n", + "encoded_data = my_encoder.fit_transform(categorical_data)\n", + "\n", + "# 4. Print the result\n", + "print(encoded_data)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "from sklearn.preprocessing import StandardScaler\n", + "\n", + "# TODO: Initialize StandardScaler\n", + "standard_scaler = StandardScaler()\n", + "\n", + "# TODO: Apply fit_transform to df_exercise\n", + "df_exercise_scaled = standard_scaler.fit_transform(encoded_data)\n", + "\n", + "\n", + "print(f\"data after scaling {encoded_data}\")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 6: Write your code here:\n", + "\n", + "# 1. Is the target imbalanced?\n", + "def check_target_imbalance(df, target_column):\n", + " print(\"Target Distribution:\")\n", + "\n", + " df[target_column].hist() # Yeah you can just do this :)\n", + " plt.show()\n", + "\n", + "check_target_imbalance(df, \"Delivery_Time\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "from sklearn.model_selection import KFold\n", + "from sklearn.metrics import mean_absolute_error as sklearn_mae\n", + "from sklearn.model_selection import StratifiedKFold\n", + "from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score\n", + "from sklearn.ensemble import RandomForestRegressor\n", + "from sklearn.model_selection import StratifiedKFold\n", + "from sklearn.metrics import accuracy_score, f1_score" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "X = df.drop(\"Delivery_Time\", axis=1)\n", + "y = df['Delivery_Time']" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "\n", + "n_splits = 5 # K=5 Folds\n", + "\n", + "skf = StratifiedKFold(n_splits=n_splits, shuffle=True, random_state=42)\n", + "\n", + "from sklearn.model_selection import train_test_split\n", + "\n", + "# CORRECTED: Use capital 'X' to match the previous definition\n", + "X, y = X.copy(), y.copy()\n", + "\n", + "# split ratio (80% train, 20% test)\n", + "X_train, X_test, y_train, y_test = train_test_split(\n", + " X, y,\n", + " test_size=0.2, # 20% for test, remaining 80% for train\n", + " random_state=42, # reproducible output\n", + " shuffle=True, # representative splits\n", + " stratify=y # preserve class distribution\n", + ")\n", + "\n", + "# Print shapes\n", + "print(\"X_train shape:\", X_train.shape)\n", + "print(\"X_test shape:\", X_test.shape)\n", + "print(\"y_train shape:\", y_train.shape)\n", + "print(\"y_test shape:\", y_test.shape)\n", + "\n", + "\n", + "\n", + "from sklearn.model_selection import KFold\n", + "\n", + "X, y = X_reg.copy(), y_reg.copy()\n", + "\n", + "kf = KFold(n_splits = 5, shuffle = True, random_state = 42)\n", + "\n", + "for fold , (train_idx, test_idx) in enumerate(kf.split(X), start = 1):\n", + " X_train, X_test = X.iloc[train_idx], X.iloc[test_idx]\n", + " y_train, y_test = y.iloc[train_idx], y.iloc[test_idx]\n", + "\n", + " print(f\"Fold {fold}\")\n", + " print(\" X_train shape:\", X_train.shape)\n", + " print(\" X_test shape :\", X_test.shape)\n", + " print(\" y_train shape:\", y_train.shape)\n", + " print(\" y_test shape :\", y_test.shape)\n", + " print(\"-\" * 30)\n", + "\n", + " # Train\n", + " model.fit(X_train, y_train)\n", + "\n", + " # Predict\n", + " y_pred = model.predict(X_test)\n", + "\n", + " # Calculate metrics\n", + " mse = sklearn_mse(y_test, y_pred)\n", + " rmse = np.sqrt(mse)\n", + " r2 = r2_score(y_test, y_pred)\n", + "\n", + " # Store results\n", + " all_results[model_name][\"mse\"].append(mse)\n", + " all_results[model_name][\"rmse\"].append(rmse)\n", + " all_results[model_name][\"r2\"].append(r2)\n", + "\n", + "# Make predictions and calculate MAE\n", + "valid_pred = model.predict(X_valid)\n", + "model_mae = mean_absolute_error(y_valid, valid_pred)\n", + "print(f\"Model MAE: {model_mae:.4f}\")\n", + "\n", + "# Calculate average loss across folds\n", + "avg_loss = np.mean(lr_losses, axis=0)\n", + "\n", + "plt.figure(figsize=(10, 6))\n", + "plt.plot(avg_loss, label='Logistic Regression Loss', color='purple')\n", + "plt.title('Average Logistic Regression Loss Curve (Across 5 Folds)')\n", + "plt.xlabel('Iteration')\n", + "plt.ylabel('Binary Cross-Entropy Loss')\n", + "plt.legend()\n", + "plt.grid(True, alpha=0.3)\n", + "plt.show()\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "# Gather importances from the models (from the last fold)\n", + "importances = {}\n", + "\n", + "importances['Random Forest'] = sklearn_models['Random Forest'].feature_importances_\n", + "\n", + "# Create a 1x3 plot\n", + "fig, axes = plt.subplots(1, 3, figsize=(18, 6))\n", + "axes = axes.flatten()\n", + "features = X.columns\n", + "\n", + "for i, (model_name, imp) in enumerate(importances.items()):\n", + " # Sort features by importance for a cleaner plot\n", + " sorted_idx = np.argsort(imp)\n", + "\n", + " ax = axes[i]\n", + " ax.barh(features[sorted_idx], imp[sorted_idx])\n", + " ax.set_title(f\"{model_name} Feature Importance\")\n", + " ax.set_xlabel(\"Importance Score\")\n", + "\n", + "plt.tight_layout()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "plt.figure(figsize=(10, 6))\n", + "plt.hist(valid_pred, bins=30, edgecolor='black')\n", + "plt.title('Distribution of Predictions')\n", + "plt.xlabel('Predicted Emission')\n", + "plt.ylabel('Count')\n", + "plt.show()\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# TODO: Define models with hyperparameters of your choice\n", + "models = {\n", + " \"Random Forest\": RandomForestRegressor (\n", + " n_estimators=200,\n", + " max_depth=10\n", + " ),\n", + " \"CatBoost\": CatBoostRegressor(\n", + " verbose=0,\n", + " n_estimators=200,\n", + " max_depth=4\n", + " )\n", + "}\n", + "\n", + "average_losses = np.mean(lr_losses, axis=0)\n", + "\n", + "plt.figure(figsize=(10, 6))\n", + "plt.plot(average_losses, label='Average Loss')\n", + "plt.xlabel('Iteration')\n", + "plt.ylabel('MSE Loss')\n", + "plt.title('Linear Regression Training Loss (Averaged Across Folds)')\n", + "plt.legend()\n", + "plt.grid(True, alpha=0.3)\n", + "plt.show()\n", + "\n", + "results = {}\n", + "\n", + "for model_name in models:\n", + " results[model_name] = {'accuracy': [], 'precision': [], 'recall': [], 'f1': []}\n", + "\n", + " for fold_idx, (train_index, test_index) in enumerate(skf.split(X, y)):\n", + " print(f\"\\nFold {fold_idx + 1}/{n_splits}\")\n", + "\n", + " # Get the train & test split for this fold\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", + " # Train & Validate Models\n", + " for model_name, model in models.items():\n", + "\n", + " print(f\"Training {model_name}...\")\n", + "\n", + " # Fit the model on train data\n", + " model.fit(X_train, y_train)\n", + "\n", + " # Use the model to predict the test data\n", + " y_pred = model.predict(X_test)\n", + "\n", + " # Calculate evaluation metrics\n", + " accuracy = accuracy_score(y_test, y_pred)\n", + " f1 = f1_score(y_test, y_pred, average='macro') # for multiclass f1 score, you should set the average hyperparameter (\"macro\", \"micro\", \"weighted\")\n", + "\n", + " results[model_name]['accuracy'].append(accuracy)\n", + " results[model_name]['f1'].append(f1)" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/429/Q2.ipynb b/submissions_extracted/429/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..c772f3a9191a1f4f3bd10c1d97b4091a79fa707e --- /dev/null +++ b/submissions_extracted/429/Q2.ipynb @@ -0,0 +1,406 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q2-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import os\n", + "import pandas as pd\n", + "import numpy as np\n", + "from PIL import Image\n", + "from sklearn.model_selection import train_test_split\n", + "\n", + "# Load Labels\n", + "labels_df = pd.read_csv(os.path.join(path, \"labels.csv\"))\n", + "img_dir = os.path.join(path, \"images\")\n", + "\n", + "images = []\n", + "ages = []\n", + "\n", + "# Load Images and Resize\n", + "print(\"Loading images...\")\n", + "for index, row in labels_df.iterrows():\n", + " img_name = row.iloc[0]\n", + " age = row.iloc[1]\n", + " img_path = os.path.join(img_dir, img_name)\n", + "\n", + " if os.path.exists(img_path):\n", + " img = Image.open(img_path).convert('RGB')\n", + " img_array = np.array(img) / 255.0 # Normalize pixel values to [0, 1]\n", + " images.append(img_array)\n", + " ages.append(age)\n", + "\n", + "X = np.array(images)\n", + "y = np.array(ages)\n", + "\n", + "# Transpose image dimensions to match PyTorch format (N, C, H, W)\n", + "X = np.transpose(X, (0, 3, 1, 2))\n", + "\n", + "# Split Data\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n", + "\n", + "print(f\"X_train shape: {X_train.shape}\")\n", + "print(f\"X_test shape: {X_test.shape}\")\n", + "print(f\"y_train shape: {y_train.shape}\")\n", + "print(f\"y_test shape: {y_test.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 1. Convert Numpy arrays to PyTorch Tensors\n", + "\n", + "\n", + "# split features from targets\n", + "X = df.drop(\"Weather Type\",axis=1)\n", + "y = df['Weather Type']\n", + "\n", + "# Split the dataset into training and testing sets\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42, stratify=y)\n", + "\n", + "# transform to tensors\n", + "X_train = torch.tensor(X_train.values, dtype=torch.float32)\n", + "X_test = torch.tensor(X_test.values, dtype=torch.float32)\n", + "y_train = torch.tensor(y_train.values, dtype=torch.long)\n", + "y_test = torch.tensor(y_test.values, dtype=torch.long)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 2. Create TensorDataset objects\n", + "\n", + "from sklearn.datasets import load_breast_cancer\n", + "from sklearn.model_selection import train_test_split\n", + "from sklearn.preprocessing import StandardScaler\n", + "from torch.utils.data import TensorDataset\n", + "from torch.utils.data import DataLoader\n", + "import torch\n", + "\n", + "# load data\n", + "data = load_breast_cancer()\n", + "X = data.data\n", + "y = data.target\n", + "\n", + "# Split the dataset into training and testing sets\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42, stratify=y)\n", + "\n", + "# Standardize the data\n", + "scaler = StandardScaler()\n", + "X_train = scaler.fit_transform(X_train)\n", + "X_test = scaler.transform(X_test)\n", + "\n", + "# transform to tensors\n", + "X_train = torch.tensor(X_train, dtype=torch.float32)\n", + "X_test = torch.tensor(X_test, dtype=torch.float32)\n", + "y_train = torch.tensor(y_train, dtype=torch.float32)\n", + "y_test = torch.tensor(y_test, dtype=torch.float32)\n", + "\n", + "# TensorDataset pairs input features (X) with their corresponding labels (y)\n", + "# Each item in the dataset is returned as (X[i], y[i])\n", + "train_dataset = TensorDataset(X_train, y_train)\n", + "test_dataset = TensorDataset(X_test, y_test)\n", + "\n", + "# Access a single sample from the dataset\n", + "# This helps verify the shape of one data sample\n", + "first_sample, _ = train_dataset[0]\n", + "print(f\"Shape of one sample: {first_sample.shape}\")\n", + "\n", + "from torchvision.datasets import MNIST\n", + "from torchvision.transforms.functional import to_tensor\n", + "\n", + "# Training dataset\n", + "train_dataset = MNIST(\n", + " root='./datasets', # Dataset storage path\n", + " train=True, # Use training data\n", + " transform=to_tensor, # Convert images to tensors\n", + " download=True # Download if not available\n", + ")\n", + "\n", + "# Testing dataset\n", + "test_dataset = MNIST(\n", + " root='./datasets', # Dataset storage path\n", + " train=False, # Use test data\n", + " transform=to_tensor, # Convert images to tensors\n", + " download=True # Download if not available\n", + ")\n", + "\n", + "# print one sample from the dataset\n", + "# Each sample consists of an image tensor and its label\n", + "sample_image, sample_label = train_dataset[0]\n", + "\n", + "print(f\"\\n Image shape: {sample_image.shape}\") # (1, 28, 28)\n", + "print(f\"Label: {sample_label}\")\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 3. Create DataLoaders\n", + "from torch.utils.data import DataLoader\n", + "\n", + "# DataLoader for training data\n", + "train_loader = DataLoader(\n", + " train_dataset,\n", + " batch_size=32,\n", + " shuffle=True,\n", + " num_workers=2\n", + ")\n", + "# DataLoader for test/validation data\n", + "test_loader = DataLoader(\n", + " test_dataset,\n", + " batch_size=32,\n", + " shuffle=False,\n", + " num_workers=2\n", + ")\n", + "# Get the first batch from the training DataLoader\n", + "X_batch, y_batch = next(iter(train_loader))\n", + "print(f\"Training batch input shape: {X_batch.shape}\")\n", + "print(f\"Training batch labels shape: {y_batch.shape}\")\n", + "\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 4. Print shape of one batch\n", + "# Create TensorDatasets for training and testing\n", + "train_dataset = TensorDataset(X_train, y_train)\n", + "test_dataset = TensorDataset(X_test, y_test)\n", + "\n", + "# Create Dataloaders to train and test data in batches\n", + "train_loader = DataLoader(?, batch_size=?, shuffle=?)\n", + "test_loader = DataLoader(?, batch_size=?, shuffle=?)\n", + "\n", + "# Print dataset sizes\n", + "print(\"Train dataset:\", len(train_dataset))\n", + "print(\"Test dataset:\", len(test_dataset))\n", + "\n", + "# Get the first batch from the training DataLoader\n", + "X_batch, y_batch = next(iter(train_loader))\n", + "print(f\"Training batch input shape: {X_batch.shape}\")\n", + "print(f\"Training batch labels shape: {y_batch.shape}\")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 5. Display sample images\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your model class here:\n", + "import torch.nn as nn\n", + "import torch.optim as optim\n", + "from torch.utils.data import DataLoader, TensorDataset\n", + "\n", + "# Create a simple neural network (maximum 5 layers)\n", + "class SimpleNN(nn.Module):\n", + " def __init__(self, input_size, num_classes):\n", + " super(SimpleNN, self).__init__()\n", + " self.model = nn.Sequential(\n", + " nn.Flatten(),\n", + " nn.Linear(input_size, 128),\n", + " nn.ReLU(),\n", + " nn.Linear(128, 64),\n", + " nn.ReLU(),\n", + " nn.Linear(64, num_classes)\n", + " )\n", + "\n", + " def forward(self, x):\n", + " return self.model(x)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "def train_one_epoch(model, optimizer, criterion, train_loader, device):\n", + " # Set the model to training mode\n", + " model.train()\n", + "\n", + " running_loss = 0.0\n", + "\n", + " for X_batch, y_batch in train_loader:\n", + " # Move batch to the selected device\n", + " X_batch = X_batch.to(device) # shape: (batch_size, num_features)\n", + " y_batch = y_batch.to(device) # shape: (batch_size,)\n", + "\n", + " # Forward pass (outputs are logits)\n", + " outputs = ? # shape: (batch_size, num_classes)\n", + " loss = criterion(outputs, y_batch)\n", + "\n", + " # Backward pass & optimization\n", + " ? # Clear previous gradients\n", + " ? # Compute gradients\n", + " ? # Update model parameters\n", + "\n", + " running_loss += loss.item()\n", + "\n", + " # Average loss over all batches\n", + " avg_loss = running_loss / len(train_loader)\n", + "\n", + " return avg_loss\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "def validate(model, criterion, test_loader, device):\n", + " # Set the model to evaluation mode\n", + " model.eval()\n", + "\n", + " running_loss = 0.0\n", + " correct = 0\n", + " total = 0\n", + "\n", + " with torch.no_grad():\n", + " for X_batch, y_batch in test_loader:\n", + " # Move data to device\n", + " X_batch = X_batch.to(device) # shape: (batch_size, num_features)\n", + " y_batch = y_batch.to(device) # shape: (batch_size,)\n", + "\n", + " # Forward pass\n", + " ?\n", + " running_loss += loss.item()\n", + "\n", + " # Apply Softmax to get probabilities\n", + " probabilities = F.softmax(outputs, dim=1)\n", + "\n", + " # Pick the classes with highest probabilities\n", + " predicted = torch.argmax(probabilities, dim=1)\n", + "\n", + " # Accuracy calculation\n", + " correct += (predicted == y_batch).sum().item()\n", + " total += y_batch.size(0)\n", + "\n", + " avg_loss = running_loss / len(test_loader)\n", + " accuracy = correct / total\n", + "\n", + " return avg_loss, accuracy" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Define device, model, loss, optimizer:\n", + "# Initialize the model\n", + "input_size = X_train.shape[1]\n", + "num_classes = number_of_labels\n", + "model = SimpleNN(input_size, num_classes)\n", + "\n", + "# Define loss function and optimizer\n", + "criterion = nn.CrossEntropyLoss()\n", + "optimizer = optim.Adam(model.parameters(), lr=0.001)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Start training for 20 epochs:\n", + "\n", + "# Train the model\n", + "epochs = 20\n", + "for epoch in range(epochs):\n", + " for inputs, labels in train_loader:\n", + " optimizer.zero_grad()\n", + " outputs = model(inputs)\n", + " loss = criterion(outputs, labels)\n", + " loss.backward()\n", + " optimizer.step()\n", + " print(f\"Epoch {epoch+1}/{epochs}, Loss: {loss.item():.4f}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "# Plotting results\n", + "plt.figure(figsize=(7, 5))\n", + "\n", + "plt.plot(train_losses, label='Train Loss')\n", + "plt.plot(val_losses, label='Validation Loss')\n", + "plt.title('Loss over Epochs')\n", + "plt.xlabel('Epoch')\n", + "plt.ylabel('Loss')\n", + "plt.legend()\n", + "\n", + "plt.tight_layout()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2 (Bonus): Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/429/Q3.ipynb b/submissions_extracted/429/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..225bd6321682e9db7aeb03cc3ba4e53175ee05f1 --- /dev/null +++ b/submissions_extracted/429/Q3.ipynb @@ -0,0 +1,319 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "\n", + "import kagglehub\n", + "from IPython.display import clear_output\n", + "\n", + "%pip install kagglehub catboost lightgbm tqdm -q\n", + "\n", + "clear_output()\n", + "\n", + "import pandas as pd\n", + "import numpy as np\n", + "import matplotlib.pyplot as plt\n", + "import seaborn as sns\n", + "import kagglehub\n", + "import os\n", + "from tqdm import tqdm\n", + "\n", + "%matplotlib inline" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q3-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)\n", + "csv_path = os.path.join(path, \"Q3_data.csv\")\n", + "\n", + "df = pd.read_csv(csv_path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "df.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "df.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "def check_missing_values(df):\n", + " missing_values = df.isnull().sum()\n", + " print(\"Missing Values per Column:\")\n", + " print(missing_values[missing_values > 0])\n", + " if missing_values.any():\n", + " print(\"\\nHandle Missing Values as needed.\")\n", + " else:\n", + " print(\"\\nNo Missing Values Found.\")\n", + "\n", + "check_missing_values(df)\n", + "\n", + "print(\"Missing values remaining:\", df.isnull().sum().sum())" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "def check_duplicates(df):\n", + " duplicates = df.duplicated().sum()\n", + " print(f\"Number of Duplicate Samples: {duplicates}\")\n", + " if duplicates > 0:\n", + " print(\"Dropping Duplicates...\")\n", + " df.drop_duplicates(inplace=True)\n", + " print(\"Duplicates Dropped.\")\n", + " else:\n", + " print(\"No Duplicate Samples Found.\")\n", + "\n", + "check_duplicates(df)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "\n", + "from sklearn.preprocessing import OneHotEncoder\n", + "\n", + "# 3. Do we have categorical columns?\n", + "def encode_categorical_columns(df):\n", + " categorical_cols = df.select_dtypes(include=[\"object\"]).columns\n", + " print(\"Categorical Columns:\", list(categorical_cols))\n", + "\n", + "encode_categorical_columns(df)\n", + "\n", + "from sklearn.preprocessing import OneHotEncoder\n", + "\n", + "categorical_data = [['Weather'], ['Traffic_Level'], ['Time_of_Day'],['Vehicle_Type']]\n", + "\n", + "print(f\"Original Data:\\n{categorical_data}\\n\")\n", + "\n", + "# 2. Initialize the encoder (Ensure output is dense/numpy array)\n", + "my_encoder = OneHotEncoder(sparse_output = False)\n", + "\n", + "# 3. Fit and Transform the data\n", + "encoded_data = my_encoder.fit_transform(categorical_data)\n", + "\n", + "# 4. Print the result\n", + "print(encoded_data)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "from sklearn.preprocessing import StandardScaler\n", + "\n", + "# TODO: Initialize StandardScaler\n", + "standard_scaler = StandardScaler()\n", + "\n", + "# TODO: Apply fit_transform to df_exercise\n", + "df_scaled = standard_scaler.fit_transform(encoded_data)\n", + "\n", + "\n", + "print(f\"data after scaling {encoded_data}\")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "\n", + "# 1. Is the target imbalanced?\n", + "def check_target_imbalance(df, target_column):\n", + " print(\"Target Distribution:\")\n", + "\n", + " df[target_column].hist() # Yeah you can just do this :)\n", + " plt.show()\n", + "\n", + "check_target_imbalance(df, \"Target\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "X = df.drop(\"Target\", axis=1)\n", + "y = df['Target']" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:\n", + "n_splits = 5 # K=5 Folds\n", + "\n", + "# 5-Fold Cross-Validation, shuffled\n", + "kf = KFold(n_splits=n_splits, shuffle=True, random_state=42)\n", + "\n", + "lr_losses = []\n", + "lr_mse = []\n", + "lr_rmse = []\n", + "lr_r2 = []\n", + "for fold_idx, (train_index, test_index) in enumerate(kf.split(X)):\n", + " print(f\"\\nFold {fold_idx + 1}/{n_splits}\")\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", + " # Train\n", + " theta, losses = gradient_descent(X_train.values, y_train.values, learning_rate=0.1, n_iters=500)\n", + "\n", + " # Validate\n", + " y_pred = np.dot(X_test.values, theta)\n", + "\n", + " # Calculate evaluation metrics\n", + " mse = sklearn_mse(y_test, y_pred)\n", + " rmse = np.sqrt(mse)\n", + " r2 = r2_score(y_test, y_pred)\n", + "\n", + " # Store results\n", + " lr_losses.append(losses)\n", + " lr_mse.append(mse)\n", + " lr_rmse.append(rmse)\n", + " lr_r2.append(r2)\n", + "\n", + "results = {}\n", + "\n", + "for model_name in models:\n", + " results[model_name] = {'accuracy': [], 'precision': [], 'recall': [], 'f1': []}\n", + "\n", + " for fold_idx, (train_index, test_index) in enumerate(skf.split(X, y)):\n", + " print(f\"\\nFold {fold_idx + 1}/{n_splits}\")\n", + "\n", + " # Get the train & test split for this fold\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", + " # Train & Validate Models\n", + " for model_name, model in models.items():\n", + "\n", + " print(f\"Training {model_name}...\")\n", + "\n", + " # Fit the model on train data\n", + " model.fit(X_train, y_train)\n", + "\n", + " # Use the model to predict the test data\n", + " y_pred = model.predict(X_test)\n", + "\n", + " # Calculate evaluation metrics\n", + " accuracy = accuracy_score(y_test, y_pred)\n", + " f1 = f1_score(y_test, y_pred, average='macro') # for multiclass f1 score, you should set the average hyperparameter (\"macro\", \"micro\", \"weighted\")\n", + "\n", + " results[model_name]['accuracy'].append(accuracy)\n", + " results[model_name]['f1'].append(f1)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "importance = pd.DataFrame({\n", + " 'feature': feature_cols,\n", + " 'importance': model.feature_importances_\n", + "}).sort_values('importance', ascending=False)\n", + "\n", + "plt.figure(figsize=(10, 6))\n", + "plt.barh(importance['feature'], importance['importance'], color='purple')\n", + "plt.xlabel('Importance')\n", + "plt.title('Feature Importance')\n", + "plt.gca().invert_yaxis()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "\n", + "# It is the 'Target' feature" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/43/Q1.ipynb b/submissions_extracted/43/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..07828148e22d4361cd479dd174a04be66f62d618 --- /dev/null +++ b/submissions_extracted/43/Q1.ipynb @@ -0,0 +1,205 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import numpy as np\n", + "import pandas as pd\n", + "import matplotlib.pyplot as plt\n", + "import os\n", + "import kagglehub\n", + "\n", + "from sklearn.model_selection import train_test_split, StratifiedKFold, cross_val_score\n", + "from sklearn.preprocessing import StandardScaler, LabelEncoder\n", + "from sklearn.ensemble import RandomForestClassifier\n", + "from sklearn.metrics import classification_report, confusion_matrix, accuracy_score\n", + "\n", + "import warnings\n", + "warnings.filterwarnings('ignore')\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "import pandas as pd\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q1-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Download latest version\n", + "\n", + "df = pd.read_csv(f\"{path}/Q1_data.csv\")\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "df_Q1_data.csv.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 6: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/43/Q2.ipynb b/submissions_extracted/43/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..471c243795912c16b8bee6a600f6fa752618365c --- /dev/null +++ b/submissions_extracted/43/Q2.ipynb @@ -0,0 +1,192 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q2-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import os\n", + "import pandas as pd\n", + "import numpy as np\n", + "from PIL import Image\n", + "from sklearn.model_selection import train_test_split\n", + "\n", + "# Load Labels\n", + "labels_df = pd.read_csv(os.path.join(path, \"labels.csv\"))\n", + "img_dir = os.path.join(path, \"images\")\n", + "\n", + "images = []\n", + "ages = []\n", + "\n", + "# Load Images and Resize\n", + "print(\"Loading images...\")\n", + "for index, row in labels_df.iterrows():\n", + " img_name = row.iloc[0]\n", + " age = row.iloc[1]\n", + " img_path = os.path.join(img_dir, img_name)\n", + "\n", + " if os.path.exists(img_path):\n", + " img = Image.open(img_path).convert('RGB')\n", + " img_array = np.array(img) / 255.0 # Normalize pixel values to [0, 1]\n", + " images.append(img_array)\n", + " ages.append(age)\n", + "\n", + "X = np.array(images)\n", + "y = np.array(ages)\n", + "\n", + "# Transpose image dimensions to match PyTorch format (N, C, H, W)\n", + "X = np.transpose(X, (0, 3, 1, 2))\n", + "\n", + "# Split Data\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n", + "\n", + "print(f\"X_train shape: {X_train.shape}\")\n", + "print(f\"X_test shape: {X_test.shape}\")\n", + "print(f\"y_train shape: {y_train.shape}\")\n", + "print(f\"y_test shape: {y_test.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 1. Convert Numpy arrays to PyTorch Tensors\n", + "import torch\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 2. Create TensorDataset objects\n", + "\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 3. Create DataLoaders\n", + "\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 4. Print shape of one batch\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 5. Display sample images\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your model class here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your training loop here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your validation loop here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Define device, model, loss, optimizer:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Start training for 20 epochs:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2 (Bonus): Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/43/Q3.ipynb b/submissions_extracted/43/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..c97832709061629f03a86d1f40306ca8a3e2a744 --- /dev/null +++ b/submissions_extracted/43/Q3.ipynb @@ -0,0 +1,160 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "\n", + "\n", + "# Download latest version\n", + "\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q3-exam-data\")\n", + "\n", + "\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/430/Q1.ipynb b/submissions_extracted/430/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..69cd87ebf26d7e0f05895349da2f849e67438385 --- /dev/null +++ b/submissions_extracted/430/Q1.ipynb @@ -0,0 +1,305 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "from IPython.display import clear_output\n", + "\n", + "%pip install kagglehub catboost lightgbm tqdm -q\n", + "\n", + "clear_output()\n", + "import pandas as pd\n", + "import numpy as np\n", + "import matplotlib.pyplot as plt\n", + "import seaborn as sns\n", + "import kagglehub\n", + "import os\n", + "from tqdm import tqdm\n", + "\n", + "%matplotlib inline\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q1-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "import os\n", + "import pandas as pd\n", + "food_path = os.path.join(path, \"Q1_data.csv\")\n", + "df = pd.read_csv(food_path)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "print(f\"Shape: {df.shape}\")\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "\n", + "df.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "df.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "food_df = pd.read_csv(\"/kaggle/input/q1-exam-data/Q1_data.csv\")\n", + "def check_target_imbalance(df, target_column):\n", + " print(\"Target Distribution:\")\n", + " print(food_df[target_column].value_counts(normalize=True))\n", + " sns.countplot(x=food_df[target_column])\n", + " plt.title(\"Target Distribution\")\n", + " plt.show()\n", + "\n", + "check_target_imbalance(food_df,\"delivery_time\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "food_df = food_df.drop('Order_ID', axis=1)\n", + "food_df" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + " #Check missing values\n", + "def check_missing_values(df):\n", + " missing_values = df.isnull().sum()\n", + " print(\"Missing Values per Column:\")\n", + " print(missing_values[missing_values > 0])\n", + " if missing_values.any():\n", + " print(\"\\nHandle Missing Values as needed.\")\n", + " else:\n", + " print(\"\\nNo Missing Values Found.\")\n", + "\n", + "check_missing_values(food_df)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "def check_duplicates(df):\n", + " duplicates = df.duplicated().sum()\n", + " print(f\"Number of Duplicate Samples: {duplicates}\")\n", + " if duplicates > 0:\n", + " print(\"Dropping Duplicates...\")\n", + " df.drop_duplicates(inplace=True)\n", + " print(\"Duplicates Dropped.\")\n", + " else:\n", + " print(\"No Duplicate Samples Found.\")\n", + "\n", + "check_duplicates(df)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "labels = ['Distance_km' ,\t'Weather',\t'Traffic_Level'\t, 'Time_of_Day',\t'Vehicle_Type',\t'Preparation_Time_min' , \t'Courier_Experience_yrs'\t , 'Delivery_Time' ]\n", + "encoder = LabelEncoder()\n", + "encoded = encoder.fit_transform(labels)\n", + "print(\"Labels:\", labels)\n", + "print(\"Encoded:\", encoded)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "categorical_cols = df.select_dtypes(include=[\"object\"]).columns\n", + "\n", + "for col in categorical_cols:\n", + " print(f\"Encoding column: {col}\")\n", + " le = LabelEncoder()\n", + " # TODO: Apply fit_transform to encode the column\n", + " df[col] = le.fit_transform(df[col])\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "from sklearn.preprocessing import LabelEncoder\n", + "\n", + "label_encoders = {}\n", + "for col in categorical_cols:\n", + " le = LabelEncoder()\n", + " df[col] = le.fit_transform(df[col])\n", + " label_encoders[col] = le\n", + "\n", + "df" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 6: Write your code here:\n", + "def check_target_imbalance(df, target_column):\n", + " print(\"Target Distribution:\")\n", + " print(df[target_column].value_counts(normalize=True))\n", + " sns.countplot(x=df[target_column])\n", + " plt.title(\"Target Distribution\")\n", + " plt.show()\n", + "\n", + "check_target_imbalance(food_df, \"delivery_time\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "from sklearn.model_selection import train_test_split\n", + "import numpy as np\n", + "\n", + "# Sample data\n", + "X = np.array([[1, 2], [3, 4], [5, 6], [7, 8], [9, 10]])\n", + "y = np.array([0, 1, 0, 1, 0])\n", + "\n", + "# 80-20 split\n", + "X_train, X_test, y_train, y_test = train_test_split(\n", + " X, y, test_size=0.2, random_state=42\n", + ")\n", + "\n", + "print(f\"Training set: {len(X_train)} samples\")\n", + "print(f\"Test set: {len(X_test)} samples\")\n", + "print(f\"\\nX_train:\\n{X_train}\")\n", + "print(f\"\\nX_test:\\n{X_test}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:\n", + "from sklearn.model_selection import KFold, StratifiedKFold, cross_val_score\n", + "from sklearn.linear_model import LogisticRegression\n", + "import numpy as np\n", + "\n", + "# Sample data\n", + "X = np.random.rand(100, 5)\n", + "y = np.random.randint(0, 2, 100)\n", + "\n", + "# KFold Cross-Validation\n", + "kfold = KFold(n_splits=5, shuffle=True, random_state=42)\n", + "model = LogisticRegression()\n", + "\n", + "# Get scores for each fold\n", + "scores = cross_val_score(model, X, y, cv=kfold, scoring='accuracy')\n", + "print(\"KFold scores:\", scores)\n", + "print(f\"Mean accuracy: {scores.mean():.3f} (+/- {scores.std():.3f})\")\n", + "\n", + "# StratifiedKFold (for imbalanced data)\n", + "skfold = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)\n", + "scores_strat = cross_val_score(model, X, y, cv=skfold, scoring='accuracy')\n", + "print(\"\\nStratifiedKFold scores:\", scores_strat)\n", + "print(f\"Mean accuracy: {scores_strat.mean():.3f}\")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "for name, importance in zip(iris.feature_names, model.feature_importances_):\n", + " print(f\" {name}: {importance:.3f}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/430/Q2.ipynb b/submissions_extracted/430/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..24475ace56ec98958199dd545bb0d03df173b3b7 --- /dev/null +++ b/submissions_extracted/430/Q2.ipynb @@ -0,0 +1,332 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q2-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import os\n", + "import pandas as pd\n", + "import numpy as np\n", + "from PIL import Image\n", + "from sklearn.model_selection import train_test_split\n", + "\n", + "# Load Labels\n", + "labels_df = pd.read_csv(os.path.join(path, \"labels.csv\"))\n", + "img_dir = os.path.join(path, \"images\")\n", + "\n", + "images = []\n", + "ages = []\n", + "\n", + "# Load Images and Resize\n", + "print(\"Loading images...\")\n", + "for index, row in labels_df.iterrows():\n", + " img_name = row.iloc[0]\n", + " age = row.iloc[1]\n", + " img_path = os.path.join(img_dir, img_name)\n", + "\n", + " if os.path.exists(img_path):\n", + " img = Image.open(img_path).convert('RGB')\n", + " img_array = np.array(img) / 255.0 # Normalize pixel values to [0, 1]\n", + " images.append(img_array)\n", + " ages.append(age)\n", + "\n", + "X = np.array(images)\n", + "y = np.array(ages)\n", + "\n", + "# Transpose image dimensions to match PyTorch format (N, C, H, W)\n", + "X = np.transpose(X, (0, 3, 1, 2))\n", + "\n", + "# Split Data\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n", + "\n", + "print(f\"X_train shape: {X_train.shape}\")\n", + "print(f\"X_test shape: {X_test.shape}\")\n", + "print(f\"y_train shape: {y_train.shape}\")\n", + "print(f\"y_test shape: {y_test.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 1. Convert Numpy arrays to PyTorch Tensors\n", + "import torch\n", + "import torch.nn as nn\n", + "\n", + "# Sample input\n", + "x = torch.tensor([-2.0, -1.0, 0.0, 1.0, 2.0])\n", + "\n", + "# ReLU: Most common for hidden layers\n", + "relu = nn.ReLU()\n", + "print(\"Input:\", x)\n", + "print(\"ReLU:\", relu(x)) # [0, 0, 0, 1, 2]\n", + "\n", + "# Sigmoid: Binary classification\n", + "sigmoid = nn.Sigmoid()\n", + "print(\"\\nSigmoid:\", sigmoid(x)) # (0, 1) range\n", + "\n", + "# Tanh: Alternative to ReLU\n", + "tanh = nn.Tanh()\n", + "print(\"Tanh:\", tanh(x)) # (-1, 1) range\n", + "\n", + "# Softmax: Multi-class classification\n", + "softmax = nn.Softmax(dim=0)\n", + "logits = torch.tensor([2.0, 1.0, 0.1])\n", + "print(\"\\nLogits:\", logits)\n", + "print(\"Softmax:\", softmax(logits)) # Probabilities sum to 1\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 2. Create TensorDataset objects\n", + "# Create TensorDatasets for training and testing\n", + "train_dataset = TensorDataset(X_train, y_train)\n", + "test_dataset = TensorDataset(X_test, y_test)\n", + "\n", + "# Create Dataloaders to train and test data in batches\n", + "train_loader = DataLoader(train_dataset, batch_size=32, shuffle=True)\n", + "test_loader = DataLoader(test_dataset, batch_size=32, shuffle=False)\n", + "\n", + "# Print dataset sizes\n", + "print(\"Train dataset:\", len(train_dataset))\n", + "print(\"Test dataset:\", len(test_dataset))\n", + "\n", + "# Get the first batch from the training DataLoader\n", + "X_batch, y_batch = next(iter(train_loader))\n", + "print(f\"Training batch input shape: {X_batch.shape}\")\n", + "print(f\"Training batch labels shape: {y_batch.shape}\")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 3. Create DataLoaders\n", + "\n", + "train_loader = DataLoader( train_dataset, batch_size=32, shuffle=True, num_workers=2)\n", + "# DataLoader for test data\n", + "test_loader = DataLoader( test_dataset, batch_size=32, shuffle=False, num_workers=2)\n", + "\n", + "# Get the first batch from the training DataLoader\n", + "X_batch, y_batch = next(iter(train_loader))\n", + "print(f\"Training batch input shape: {X_batch.shape}\")\n", + "print(f\"Training batch labels shape: {y_batch.shape}\")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 4. Print shape of one batch\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 5. Display sample images\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your model class here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your training loop here:\n", + "def train_one_epoch(model, optimizer, criterion, train_loader, device):\n", + " # Set the model to training mode\n", + " model.train()\n", + "\n", + " running_loss = 0.0\n", + "\n", + " for X_batch, y_batch in train_loader:\n", + " # Move batch to the selected device\n", + " X_batch = X_batch.view(X_batch.size(0), -1).to(device)\n", + " y_batch = y_batch.to(device)\n", + "\n", + " # Forward pass\n", + " # TODO: make predictions\n", + " outputs = model(X_batch) # shape: (batch_size, 10)\n", + " # TODO: compute loss\n", + " loss = criterion(outputs, y_batch)\n", + "\n", + " # Backward pass & optimization\n", + " optimizer.zero_grad() # Clear previous gradients\n", + " loss.backward() # Compute gradients\n", + " optimizer.step() # Update model parameters\n", + "\n", + " running_loss += loss.item()\n", + "\n", + " # Average loss over all batches\n", + " avg_loss = running_loss / len(train_loader)\n", + "\n", + " return avg_loss" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your validation loop here:\n", + "def validate(model, criterion, test_loader, device):\n", + " # Set the model to evaluation mode\n", + " model.eval()\n", + "\n", + " running_loss = 0.0\n", + " correct = 0\n", + " total = 0\n", + "\n", + " with torch.no_grad():\n", + " for X_batch, y_batch in test_loader:\n", + " # Move data to device\n", + " X_batch = X_batch.view(X_batch.size(0), -1).to(device)\n", + " y_batch = y_batch.to(device)\n", + "\n", + " # Forward pass\n", + " # TODO: make predictions\n", + " outputs = model(X_batch) # shape: (batch_size, 10)\n", + " # TODO: compute loss\n", + " loss = criterion(outputs, y_batch)\n", + " running_loss += loss.item()\n", + "\n", + " # TODO: Apply Softmax to get probabilities\n", + " probabilities = F.softmax(outputs, dim=1)\n", + "\n", + " # TODO: Multiclass predictions\n", + " predicted = torch.argmax(probabilities, dim=1)\n", + "\n", + " # Accuracy calculation\n", + " correct += (predicted == y_batch).sum().item()\n", + " total += y_batch.size(0)\n", + "\n", + " avg_loss = running_loss / len(test_loader)\n", + " # TODO: how do we calculate accuracy?\n", + " accuracy = correct / total\n", + "\n", + " return avg_loss, accuracy\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Define device, model, loss, optimizer:\n", + "# Device setup\n", + "device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n", + "\n", + "# Model parameters\n", + "# TODO: What are input features ? (hint: flatten using channel, height, width)\n", + "input_dim = 3 * 32 * 32 # CIFAR-10 images flattened (RGB)\n", + "\n", + "# TODO: choose number of hidden neurons\n", + "hidden_dim = 64 # Design choice\n", + "\n", + "# TODO: what are the number of classes ?\n", + "output_dim = 10 # CIFAR-10 classes\n", + "\n", + "# TODO: Instantiate model (what are the model class inputs?)\n", + "model = NN5Layer(input_dim, hidden_dim, output_dim).to(device)\n", + "\n", + "# TODO: Print the model architecture\n", + "print(\"Model Architecture:\\n\")\n", + "print(model)\n", + "\n", + "# Calculate the total number of trainable parameters\n", + "total_params = sum(p.numel() for p in model.parameters() if p.requires_grad)\n", + "print(f\"\\nTotal trainable parameters: {total_params}\")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Start training for 20 epochs:\n", + "# TODO: choose number of epochs, increase it if you have gpus :)\n", + "num_epochs = 20\n", + "# TODO: choose a learning rate (try different values and evaluate results)\n", + "learning_rate = 0.001\n", + "\n", + "# TODO: Define criterion (loss function) (hint: what loss do we use for multiclass ?)\n", + "criterion = nn.CrossEntropyLoss()\n", + "# TODO: Define optimizer(what is updated during training?)\n", + "optimizer = AdamW(model.parameters(), learning_rate)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2 (Bonus): Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/430/Q3.ipynb b/submissions_extracted/430/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..1b5aad740d57610aa6ec62cebd4ff2609df0cfdd --- /dev/null +++ b/submissions_extracted/430/Q3.ipynb @@ -0,0 +1,243 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "from IPython.display import clear_output\n", + "\n", + "%pip install kagglehub catboost lightgbm tqdm -q\n", + "\n", + "clear_output()\n", + "import pandas as pd\n", + "import numpy as np\n", + "import matplotlib.pyplot as plt\n", + "import seaborn as sns\n", + "import kagglehub\n", + "import os\n", + "from tqdm import tqdm\n", + "\n", + "%matplotlib inline\n", + "\n", + "\n", + "\n", + "\n", + "# Download latest version\n", + "\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q3-exam-data\")\n", + "\n", + "\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "import os\n", + "import pandas as pd\n", + "data_path = os.path.join(path, \"Q3_data.csv\")\n", + "data_df = pd.read_csv(data_path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "data_df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "\n", + "data_df.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "data_df.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + " #Check missing values\n", + "def check_missing_values(df):\n", + " missing_values = df.isnull().sum()\n", + " print(\"Missing Values per Column:\")\n", + " print(missing_values[missing_values > 0])\n", + " if missing_values.any():\n", + " print(\"\\nHandle Missing Values as needed.\")\n", + " else:\n", + " print(\"\\nNo Missing Values Found.\")\n", + "\n", + "check_missing_values(data_df)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "def check_duplicates(df):\n", + " duplicates = df.duplicated().sum()\n", + " print(f\"Number of Duplicate Samples: {duplicates}\")\n", + " if duplicates > 0:\n", + " print(\"Dropping Duplicates...\")\n", + " df.drop_duplicates(inplace=True)\n", + " print(\"Duplicates Dropped.\")\n", + " else:\n", + " print(\"No Duplicate Samples Found.\")\n", + "\n", + "check_duplicates(data_df)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "from sklearn.model_selection import train_test_split\n", + "import numpy as np\n", + "\n", + "# Sample data\n", + "X = np.array([[1, 2], [3, 4], [5, 6], [7, 8], [9, 10]])\n", + "y = np.array([0, 1, 0, 1, 0])\n", + "\n", + "# 80-20 split\n", + "X_train, X_test, y_train, y_test = train_test_split(\n", + " X, y, test_size=0.2, random_state=42\n", + ")\n", + "\n", + "print(f\"Training set: {len(X_train)} samples\")\n", + "print(f\"Test set: {len(X_test)} samples\")\n", + "print(f\"\\nX_train:\\n{X_train}\")\n", + "print(f\"\\nX_test:\\n{X_test}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:\n", + "from sklearn.model_selection import KFold, StratifiedKFold, cross_val_score\n", + "from sklearn.linear_model import LogisticRegression\n", + "import numpy as np\n", + "\n", + "# Sample data\n", + "X = np.random.rand(100, 5)\n", + "y = np.random.randint(0, 2, 100)\n", + "\n", + "# KFold Cross-Validation\n", + "kfold = KFold(n_splits=5, shuffle=True, random_state=42)\n", + "model = LogisticRegression()\n", + "\n", + "# Get scores for each fold\n", + "scores = cross_val_score(model, X, y, cv=kfold, scoring='accuracy')\n", + "print(\"KFold scores:\", scores)\n", + "print(f\"Mean accuracy: {scores.mean():.3f} (+/- {scores.std():.3f})\")\n", + "\n", + "# StratifiedKFold (for imbalanced data)\n", + "skfold = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)\n", + "scores_strat = cross_val_score(model, X, y, cv=skfold, scoring='accuracy')\n", + "print(\"\\nStratifiedKFold scores:\", scores_strat)\n", + "print(f\"Mean accuracy: {scores_strat.mean():.3f}\")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/431/Q1.ipynb b/submissions_extracted/431/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..4f8f402b2dd262f74c8955a57f70e89fd781362c --- /dev/null +++ b/submissions_extracted/431/Q1.ipynb @@ -0,0 +1,258 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q1-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "import os\n", + "import pandas as pd\n", + "\n", + "full_path = os.path.join(path, 'Q1_data.csv')\n", + "df = pd.read_csv(full_path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "df.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "df.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "import matplotlib.pyplot as plt\n", + "plt.hist(df['Delivery_Time'].dropna(), bins=50, edgecolor='black')" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "df_clean = df.drop('Order_ID', axis = 1)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "\n", + "display(df_clean.isna().sum())\n", + "display(df_clean.isnull().sum() / len(df_clean))\n", + "df_clean.dropna(subset=['Weather', 'Traffic_Level', 'Time_of_Day', 'Courier_Experience_yrs'])\n", + "df_clean['Delivery_Time'] = df_clean['Delivery_Time'].fillna(method='ffill')" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "print(df_clean.duplicated().sum())\n", + "df_clean.drop_duplicates(inplace=True)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "from sklearn.preprocessing import LabelEncoder\n", + "\n", + "categorical_cols = df_clean.select_dtypes(include=['object']).columns\n", + "for col in categorical_cols:\n", + " le = LabelEncoder()\n", + " df_clean[col] = le.fit_transform(df_clean[col].astype(str))" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "from sklearn.preprocessing import StandardScaler\n", + "# Have done splitting early\n", + "from sklearn.model_selection import train_test_split\n", + "X = df_clean.drop('Delivery_Time', axis=1)\n", + "y = df_clean['Delivery_Time']\n", + "\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n", + "\n", + "scaler = StandardScaler()\n", + "X_train_scaled = scaler.fit_transform(X_train)\n", + "X_test_scaled = scaler.transform(X_test)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 6: Write your code here:\n", + "# The plot is done above, there is no severe imbalance." + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "# Have done it before encoding above" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:\n", + "from sklearn.model_selection import KFold\n", + "from sklearn.ensemble import RandomForestRegressor\n", + "import numpy as np\n", + "from sklearn.metrics import mean_absolute_error, mean_squared_error\n", + "\n", + "kfold = KFold(n_splits=5, shuffle=True, random_state=42)\n", + "\n", + "model = RandomForestRegressor(n_estimators=100, max_depth=20, random_state=42, n_jobs=-1)\n", + "\n", + "mae_scores = []\n", + "rmse_scores = []\n", + "\n", + "for train_idx, val_idx in kfold.split(X_train_scaled):\n", + " X_fold_train, X_fold_val = X_train_scaled[train_idx], X_train_scaled[val_idx]\n", + " y_fold_train, y_fold_val = y_train.iloc[train_idx], y_train.iloc[val_idx]\n", + "\n", + " # Train and predict\n", + " model.fit(X_fold_train, y_fold_train)\n", + " y_fold_pred = model.predict(X_fold_val)\n", + "\n", + " # Calculate metrics\n", + " mae_scores.append(mean_absolute_error(y_fold_val, y_fold_pred))\n", + " rmse_scores.append(np.sqrt(mean_squared_error(y_fold_val, y_fold_pred)))\n", + "\n", + "mae_scores = np.array(mae_scores)\n", + "rmse_scores = np.array(rmse_scores)\n", + "\n", + "print(f\"5-Fold CV Results:\")\n", + "print(f\"MAE: {mae_scores.mean():,.2f}\")\n", + "print(f\"RMSE: {rmse_scores.mean():,.2f}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "feature_importance = pd.DataFrame({\n", + " 'feature': ['Distance_km', 'Weather', 'Traffic_Level', 'Time_of_Day', 'Vehicle_Type', 'Preparation_Time_min', 'Courier_Experience_yrs'],\n", + " 'importance': model.feature_importances_\n", + "}).sort_values('importance', ascending=False)\n", + "\n", + "plt.figure(figsize=(10, 6))\n", + "plt.barh(feature_importance['feature'], feature_importance['importance'])\n", + "plt.xlabel('Importance')\n", + "plt.title('Feature Importance')\n", + "plt.gca().invert_yaxis()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/431/Q2.ipynb b/submissions_extracted/431/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..58415bc8397d5a04f7908ff4b628d0fe480a40e6 --- /dev/null +++ b/submissions_extracted/431/Q2.ipynb @@ -0,0 +1,324 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q2-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import os\n", + "import pandas as pd\n", + "import numpy as np\n", + "from PIL import Image\n", + "from sklearn.model_selection import train_test_split\n", + "\n", + "# Load Labels\n", + "labels_df = pd.read_csv(os.path.join(path, \"labels.csv\"))\n", + "img_dir = os.path.join(path, \"images\")\n", + "\n", + "images = []\n", + "ages = []\n", + "\n", + "# Load Images and Resize\n", + "print(\"Loading images...\")\n", + "for index, row in labels_df.iterrows():\n", + " img_name = row.iloc[0]\n", + " age = row.iloc[1]\n", + " img_path = os.path.join(img_dir, img_name)\n", + "\n", + " if os.path.exists(img_path):\n", + " img = Image.open(img_path).convert('RGB')\n", + " img_array = np.array(img) / 255.0 # Normalize pixel values to [0, 1]\n", + " images.append(img_array)\n", + " ages.append(age)\n", + "\n", + "X = np.array(images)\n", + "y = np.array(ages)\n", + "\n", + "# Transpose image dimensions to match PyTorch format (N, C, H, W)\n", + "X = np.transpose(X, (0, 3, 1, 2))\n", + "\n", + "# Split Data\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n", + "\n", + "print(f\"X_train shape: {X_train.shape}\")\n", + "print(f\"X_test shape: {X_test.shape}\")\n", + "print(f\"y_train shape: {y_train.shape}\")\n", + "print(f\"y_test shape: {y_test.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 1. Convert Numpy arrays to PyTorch Tensors\n", + "import torch\n", + "X_train_tensor = torch.tensor(X_train, dtype=torch.float32)\n", + "X_test_tensor = torch.tensor(X_test, dtype=torch.float32)\n", + "y_train_tensor = torch.tensor(y_train, dtype=torch.float32)\n", + "y_test_tensor = torch.tensor(y_test, dtype=torch.float32)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 2. Create TensorDataset objects\n", + "from torch.utils.data import TensorDataset, DataLoader\n", + "\n", + "train_dataset = TensorDataset(X_train_tensor, y_train_tensor)\n", + "test_dataset = TensorDataset(X_test_tensor, y_test_tensor)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 3. Create DataLoaders\n", + "\n", + "train_loader = DataLoader(train_dataset, batch_size=32, shuffle=True)\n", + "test_loader = DataLoader(test_dataset, batch_size=32, shuffle=False)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 4. Print shape of one batch\n", + "\n", + "X_batch, y_batch = next(iter(train_loader))\n", + "print(f\"Batch shape: {X_batch.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 5. Display sample images\n", + "import matplotlib.pyplot as plt\n", + "plt.figure(figsize=(8, 4))\n", + "\n", + "for i in range(6):\n", + " plt.subplot(2, 3, i + 1)\n", + " plt.imshow(images[i].squeeze(), cmap='gray')\n", + " plt.title(f\"Label: {y_batch[i].item()}\")\n", + " plt.axis('off')\n", + "\n", + "plt.tight_layout()\n", + "plt.show()\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your model class here:\n", + "import torch.nn as nn\n", + "class NN4Layer(nn.Module):\n", + " def __init__(self, input_dim, hidden_dim):\n", + " super(NN4Layer, self).__init__()\n", + "\n", + " self.layer1 = nn.Linear(input_dim, hidden_dim)\n", + " self.layer2 = nn.Linear(hidden_dim, hidden_dim)\n", + " self.layer3 = nn.Linear(hidden_dim, hidden_dim)\n", + " self.layer4 = nn.Linear(hidden_dim, 1)\n", + " self.relu = nn.ReLU()\n", + "\n", + " def forward(self, x):\n", + " x = x.view(x.size(0), -1)\n", + " z1 = self.layer1(x)\n", + " a1 = self.relu(z1)\n", + "\n", + " z2 = self.layer2(a1)\n", + " a2 = self.relu(z2)\n", + "\n", + " z3 = self.layer3(a2)\n", + " a3 = self.relu(z3)\n", + "\n", + " z4 = self.layer4(a3)\n", + " output = self.relu(z4)\n", + "\n", + " return output\n", + "" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your training loop here:\n", + "def train_one_epoch(model, optimizer, criterion, train_loader, device):\n", + " model.train()\n", + "\n", + " running_loss = 0.0\n", + "\n", + " for X_batch, y_batch in train_loader:\n", + " X_batch = X_batch.view(X_batch.size(0), -1).to(device)\n", + " y_batch = y_batch.to(device)\n", + "\n", + " outputs = model(X_batch)\n", + " loss = criterion(outputs, y_batch)\n", + "\n", + " optimizer.zero_grad()\n", + " loss.backward()\n", + " optimizer.step()\n", + "\n", + " running_loss += loss.item()\n", + "\n", + " avg_loss = running_loss / len(train_loader)\n", + "\n", + " return avg_loss" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your validation loop here:\n", + "def validate(model, criterion, test_loader, device):\n", + " # Set the model to evaluation mode\n", + " model.eval()\n", + "\n", + " running_loss = 0.0\n", + "\n", + " with torch.no_grad():\n", + " for X_batch, y_batch in test_loader:\n", + " X_batch = X_batch.view(X_batch.size(0), -1).to(device)\n", + " y_batch = y_batch.to(device)\n", + "\n", + " outputs = model(X_batch)\n", + " loss = criterion(outputs, y_batch)\n", + " running_loss += loss.item()\n", + "\n", + "\n", + " avg_loss = running_loss / len(test_loader)\n", + " return avg_loss\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Define device, model, loss, optimizer:\n", + "from torch.optim import Adam\n", + "device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n", + "\n", + "input_dim = 36 * 36 * 3\n", + "hidden_dim = 14\n", + "\n", + "model = NN4Layer(input_dim, hidden_dim).to(device)\n", + "\n", + "print(\"Model Architecture:\\n\")\n", + "print(model)\n", + "\n", + "num_epochs = 10\n", + "learning_rate = 0.001\n", + "\n", + "criterion = nn.MSELoss()\n", + "# Define optimizer\n", + "optimizer = Adam(model.parameters(), learning_rate)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Start training for 20 epochs:\n", + "train_losses = []\n", + "val_losses = []\n", + "\n", + "print('Starting Training...')\n", + "for epoch in range(num_epochs):\n", + " train_loss = train_one_epoch(model, optimizer, criterion, train_loader, device)\n", + "\n", + " val_loss = validate(model, criterion, test_loader, device)\n", + "\n", + " train_losses.append(train_loss)\n", + " val_losses.append(val_loss)\n", + "\n", + " if (epoch + 1) % 5 == 0:\n", + " print(\n", + " f'Epoch [{epoch+1}/{num_epochs}], '\n", + " f'Train Loss: {train_loss:.4f}, '\n", + " f'Val Loss: {val_loss:.4f}'\n", + " )\n", + "\n", + "print('Training Complete!')" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "plt.figure(figsize=(7, 5))\n", + "\n", + "plt.plot(train_losses, label='Train Loss')\n", + "plt.plot(val_losses, label='Validation Loss')\n", + "plt.title('Loss over Epochs')\n", + "plt.xlabel('Epoch')\n", + "plt.ylabel('Loss')\n", + "plt.legend()\n", + "\n", + "plt.tight_layout()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2 (Bonus): Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/431/Q3.ipynb b/submissions_extracted/431/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..1ed3ddb63b1c474c5c03fbb08280355c9e646abd --- /dev/null +++ b/submissions_extracted/431/Q3.ipynb @@ -0,0 +1,235 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "\n", + "\n", + "# Download latest version\n", + "\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q3-exam-data\")\n", + "\n", + "\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "import os\n", + "import pandas as pd\n", + "\n", + "full_path = os.path.join(path, 'Q3_data.csv')\n", + "df = pd.read_csv(full_path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "df.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "df.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "for col in df.columns:\n", + " df[col] = df[col].fillna(df[col].median())" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "df.drop_duplicates(inplace=True)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "# There are no catagories" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "from sklearn.preprocessing import StandardScaler\n", + "# Have done splitting early\n", + "from sklearn.model_selection import train_test_split\n", + "X = df.drop('Target', axis=1)\n", + "y = df['Target']\n", + "\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42, stratify=y)\n", + "\n", + "scaler = StandardScaler()\n", + "X_train_scaled = scaler.fit_transform(X_train)\n", + "X_test_scaled = scaler.transform(X_test)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "import matplotlib.pyplot as plt\n", + "plt.hist(y.dropna(), bins=50, edgecolor='black')\n", + "# There is some imbalance, so stratified split is needed (done already above)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "#done above" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:\n", + "# %pip install catboost # Needed to run it once\n", + "from catboost import CatBoostClassifier\n", + "from sklearn.model_selection import KFold\n", + "import numpy as np\n", + "from sklearn.metrics import mean_absolute_error, mean_squared_error\n", + "\n", + "kfold = KFold(n_splits=5, shuffle=True, random_state=42) # I just noticed that I was using booth kfold and train_test_split in two labs D:<\n", + "\n", + "model = CatBoostClassifier(\n", + " verbose=0,\n", + " n_estimators=200,\n", + " max_depth=4\n", + " )\n", + "\n", + "mae_scores = []\n", + "rmse_scores = []\n", + "\n", + "for train_idx, val_idx in kfold.split(X_train_scaled):\n", + " X_fold_train, X_fold_val = X_train_scaled[train_idx], X_train_scaled[val_idx]\n", + " y_fold_train, y_fold_val = y_train.iloc[train_idx], y_train.iloc[val_idx]\n", + "\n", + " # Train and predict\n", + " model.fit(X_fold_train, y_fold_train)\n", + " y_fold_pred = model.predict(X_fold_val)\n", + "\n", + " # Calculate metrics\n", + " mae_scores.append(mean_absolute_error(y_fold_val, y_fold_pred))\n", + " rmse_scores.append(np.sqrt(mean_squared_error(y_fold_val, y_fold_pred)))\n", + "\n", + "mae_scores = np.array(mae_scores)\n", + "rmse_scores = np.array(rmse_scores)\n", + "\n", + "print(f\"5-Fold CV Results:\")\n", + "print(f\"MAE: {mae_scores.mean():,.2f}\")\n", + "print(f\"RMSE: {rmse_scores.mean():,.2f}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "feature_importance = pd.DataFrame({\n", + " 'feature': X.columns,\n", + " 'importance': model.feature_importances_\n", + "}).sort_values('importance', ascending=False)\n", + "\n", + "plt.figure(figsize=(10, 6))\n", + "plt.barh(feature_importance['feature'], feature_importance['importance'])\n", + "plt.xlabel('Importance')\n", + "plt.title('Feature Importance')\n", + "plt.gca().invert_yaxis()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "feature_importance.max()\n", + "# Feature S_9 is the most important!\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/432/Q1.ipynb b/submissions_extracted/432/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..e5f1e28223bfba67daaecb9981bbfa09e8d20ff4 --- /dev/null +++ b/submissions_extracted/432/Q1.ipynb @@ -0,0 +1,200 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import numpy as np\n", + "import pandas as pd\n", + "import matplotlib.pyplot as plt\n", + "import os\n", + "import kagglehub\n", + "\n", + "from sklearn.model_selection import train_test_split, KFold\n", + "from sklearn.preprocessing import StandardScaler, LabelEncoder\n", + "from sklearn.ensemble import RandomForestRegressor\n", + "from sklearn.metrics import mean_absolute_error, mean_squared_error\n", + "\n", + "import warnings\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q1-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "csv_path = os.path.join(path, \"Q1_data.csv\")\n", + "df_ = pd.read_csv(csv_path)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "df_.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "df_.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "df_.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "plt.figure(figsize=(8,4 ))\n", + "plt.hist(df_[\"Delivery_Time\" ].dropna(), bins=8, edgecolor='black')\n", + "plt.title('Delivery time')\n", + "plt.xlabel('time')\n", + "plt.ylabel('delivery')\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "df_cols = (\"Delivery_time\",\"Order_ID\" ,\"Weather\", \"Vehicle_Type\", )\n", + "df_clean = df_[df_cols].copy()\n", + "print(f\"Before: {df_.shape}\")\n", + "df_clean= df_clean.dropna(subset=['Order_ID'])\n", + "print(f\"After dropping missing Order_ID: {df_.shape}\")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 6: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/432/Q2.ipynb b/submissions_extracted/432/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..b969432cbb5fbf3df2d30a104e9605031158129e --- /dev/null +++ b/submissions_extracted/432/Q2.ipynb @@ -0,0 +1,193 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q2-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import os\n", + "import pandas as pd\n", + "import numpy as np\n", + "from PIL import Image\n", + "from sklearn.model_selection import train_test_split\n", + "\n", + "# Load Labels\n", + "labels_df = pd.read_csv(os.path.join(path, \"labels.csv\"))\n", + "img_dir = os.path.join(path, \"images\")\n", + "\n", + "images = []\n", + "ages = []\n", + "\n", + "# Load Images and Resize\n", + "print(\"Loading images...\")\n", + "for index, row in labels_df.iterrows():\n", + " img_name = row.iloc[0]\n", + " age = row.iloc[1]\n", + " img_path = os.path.join(img_dir, img_name)\n", + "\n", + " if os.path.exists(img_path):\n", + " img = Image.open(img_path).convert('RGB')\n", + " img_array = np.array(img) / 255.0 # Normalize pixel values to [0, 1]\n", + " images.append(img_array)\n", + " ages.append(age)\n", + "\n", + "X = np.array(images)\n", + "y = np.array(ages)\n", + "\n", + "# Transpose image dimensions to match PyTorch format (N, C, H, W)\n", + "X = np.transpose(X, (0, 3, 1, 2))\n", + "\n", + "# Split Data\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n", + "\n", + "print(f\"X_train shape: {X_train.shape}\")\n", + "print(f\"X_test shape: {X_test.shape}\")\n", + "print(f\"y_train shape: {y_train.shape}\")\n", + "print(f\"y_test shape: {y_test.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import torch\n", + "x = torch.tensor([400, 3, 36, 36])\n", + "y = torch.randn([400,])\n", + "print(\"x:\", x)\n", + "print(\"y\", y)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 2. Create TensorDataset objects\n", + "\n", + "train_dataset = Tensor_Dataset(X_train, y_train)\n", + "test_dataset = Tensor_Dataset(x_test, y_test)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 3. Create DataLoaders\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 4. Print shape of one batch\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 5. Display sample images\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your model class here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your training loop here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your validation loop here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Define device, model, loss, optimizer:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Start training for 20 epochs:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2 (Bonus): Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/432/Q3.ipynb b/submissions_extracted/432/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..f43272af0605fd8b183ba97cd5d6c039f00c2606 --- /dev/null +++ b/submissions_extracted/432/Q3.ipynb @@ -0,0 +1,177 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import numpy as np\n", + "import pandas as pd\n", + "import matplotlib.pyplot as plt\n", + "import os\n", + "import kagglehub\n", + "\n", + "from sklearn.model_selection import train_test_split, KFold\n", + "from sklearn.preprocessing import StandardScaler, LabelEncoder\n", + "from sklearn.ensemble import RandomForestRegressor\n", + "from sklearn.metrics import mean_absolute_error, mean_squared_error\n", + "\n", + "import warnings\n", + "\n", + "\n", + "\n", + "# Download latest version\n", + "\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q3-exam-data\")\n", + "\n", + "\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "# Task 1: Write your code here:\n", + "csv_path = os.path.join(path, \"Q3_data.csv\")\n", + "df = pd.read_csv(csv_path)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "df.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "df.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/433/Q1.ipynb b/submissions_extracted/433/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..ba83ce3f1ac44bdb65a12e41f11ea2b100bc4a6a --- /dev/null +++ b/submissions_extracted/433/Q1.ipynb @@ -0,0 +1,327 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q1-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import numpy as np\n", + "import pandas as pd\n", + "import matplotlib.pyplot as plt\n", + "import os\n", + "import kagglehub\n", + "\n", + "from sklearn.model_selection import train_test_split, KFold\n", + "from sklearn.preprocessing import StandardScaler, LabelEncoder\n", + "from sklearn.ensemble import RandomForestRegressor\n", + "from sklearn.metrics import mean_absolute_error, mean_squared_error\n", + "\n", + "import warnings\n", + "warnings.filterwarnings('ignore')" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "import pandas as pd\n", + "df = pd.read_csv('/kaggle/input/q1-exam-data/Q1_data.csv')\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "df.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "df.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "df['Delivery_Time'].hist()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "df.drop(columns=['Order_ID'])" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "print(\"Missing values:\")\n", + "print(df.isnull().sum())\n", + "categorical_cols = df.select_dtypes(include=[\"object\"]).columns\n", + "num_cols = df.select_dtypes(include=[\"number\"]).columns\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "for col in categorical_cols:\n", + " df[col]=df[col].fillna(\"none\")\n", + "for col in num_cols:\n", + " df[col]=df[col].fillna(0)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "print(\"Missing values:\")\n", + "print(df.isnull().sum())" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "def check_duplicates(df):\n", + " duplicates = df.duplicated().sum()\n", + " print(f\"Number of Duplicate Samples: {duplicates}\")\n", + " if duplicates > 0:\n", + " print(\"Dropping Duplicates...\")\n", + " df.drop_duplicates(inplace=True)\n", + " print(\"Duplicates Dropped.\")\n", + " else:\n", + " print(\"No Duplicate Samples Found.\")\n", + "\n", + "check_duplicates(df)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "from sklearn.preprocessing import StandardScaler, LabelEncoder\n", + "categorical_cols = df.select_dtypes(include=[\"object\"]).columns\n", + "for col in categorical_cols:\n", + " print(f\"Encoding column: {col}\")\n", + " le = LabelEncoder()\n", + " df[col] = le.fit_transform(df[col])\n", + "df" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "numerical_cols = df.select_dtypes(include=[\"int64\", \"float64\"]).columns.drop(\"Delivery_Time\") ### DON'T SCALE THE TARGET\n", + "scaler = StandardScaler()\n", + "df[numerical_cols] = scaler.fit_transform(df[numerical_cols])\n", + "df" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 6: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "X = df.drop(\"Delivery_Time\", axis=1).astype(float)\n", + "y = df[\"Delivery_Time\"].astype(float)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:\n", + "from sklearn.model_selection import StratifiedKFold, train_test_split\n", + "from sklearn.metrics import accuracy_score\n", + "\n", + "n_splits = 5\n", + "skf = StratifiedKFold(n_splits=n_splits, shuffle=True, random_state=42)\n", + "\n", + "for fold_idx, (train_index, test_index) in enumerate(skf.split(X, y)):\n", + " print(f\"\\nFold {fold_idx + 1}/{n_splits}\")\n", + "\n", + " # Get the train & test split for this fold\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]" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "from sklearn.ensemble import RandomForestClassifier\n", + "\n", + "model=RandomForestClassifier(n_estimators=200, max_depth=10)\n", + "# Fit the model on train data\n", + "model.fit(X_train, y_train)\n", + "\n", + "# Use the model to predict the test data\n", + "y_pred = model.predict(X_test)\n", + "\n", + "accuracy = accuracy_score(y_test, y_pred)\n", + "print(f\"Accuracy: {accuracy}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "y_pred = model.predict(X_test)\n", + "\n", + "mae = mean_absolute_error(y_test, y_pred)\n", + "print(f\"MAE: ${mae:,.2f}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "feature_importance = pd.DataFrame({\n", + " 'feature': feature_cols,\n", + " 'importance': model.feature_importances_\n", + "}).sort_values('importance', ascending=False)\n", + "\n", + "plt.figure(figsize=(10, 6))\n", + "plt.barh(feature_importance['feature'], feature_importance['importance'])\n", + "plt.xlabel('Importance')\n", + "plt.title('Feature Importance')\n", + "plt.gca().invert_yaxis()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "df['Delivery_Time'].hist()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/433/Q2.ipynb b/submissions_extracted/433/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..e684cec6bac471a7cb069300a512c150064b195e --- /dev/null +++ b/submissions_extracted/433/Q2.ipynb @@ -0,0 +1,433 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q2-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import os\n", + "import pandas as pd\n", + "import numpy as np\n", + "from PIL import Image\n", + "from sklearn.model_selection import train_test_split\n", + "import kagglehub\n", + "import pandas as pd\n", + "import numpy as np\n", + "import torch\n", + "import torch.nn as nn\n", + "from torch.optim import AdamW\n", + "import matplotlib.pyplot as plt\n", + "from torch.utils.data import DataLoader, TensorDataset\n", + "from sklearn.model_selection import train_test_split\n", + "from sklearn.preprocessing import StandardScaler, LabelEncoder\n", + "from sklearn.metrics import mean_absolute_error, mean_squared_error, r2_score\n", + "# Load Labels\n", + "labels_df = pd.read_csv(os.path.join(path, \"labels.csv\"))\n", + "img_dir = os.path.join(path, \"images\")\n", + "\n", + "images = []\n", + "ages = []\n", + "\n", + "# Load Images and Resize\n", + "print(\"Loading images...\")\n", + "for index, row in labels_df.iterrows():\n", + " img_name = row.iloc[0]\n", + " age = row.iloc[1]\n", + " img_path = os.path.join(img_dir, img_name)\n", + "\n", + " if os.path.exists(img_path):\n", + " img = Image.open(img_path).convert('RGB')\n", + " img_array = np.array(img) / 255.0 # Normalize pixel values to [0, 1]\n", + " images.append(img_array)\n", + " ages.append(age)\n", + "\n", + "X = np.array(images)\n", + "y = np.array(ages)\n", + "\n", + "# Transpose image dimensions to match PyTorch format (N, C, H, W)\n", + "X = np.transpose(X, (0, 3, 1, 2))\n", + "\n", + "# Split Data\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n", + "\n", + "print(f\"X_train shape: {X_train.shape}\")\n", + "print(f\"X_test shape: {X_test.shape}\")\n", + "print(f\"y_train shape: {y_train.shape}\")\n", + "print(f\"y_test shape: {y_test.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 1. Convert Numpy arrays to PyTorch Tensors\n", + "\n", + "X_train = torch.tensor(X_train, dtype=torch.float32)\n", + "X_test = torch.tensor(X_test, dtype=torch.float32)\n", + "y_train = torch.tensor(y_train, dtype=torch.float32)\n", + "y_test = torch.tensor(y_test, dtype=torch.float32)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 2. Create TensorDataset objects\n", + "\n", + "\n", + "# Create TensorDatasets for training and testing\n", + "train_dataset = TensorDataset(X_train, y_train)\n", + "test_dataset = TensorDataset(X_test, y_test)\n", + "\n", + "\n", + "\n", + "# Print dataset sizes\n", + "print(\"Train dataset:\", len(train_dataset))\n", + "print(\"Test dataset:\", len(test_dataset))\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 3. Create DataLoaders\n", + "\n", + "train_loader = DataLoader(train_dataset, batch_size=32, shuffle=True)\n", + "test_loader = DataLoader(test_dataset, batch_size=32, shuffle=False)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 4. Print shape of one batch\n", + "X_batch, y_batch = next(iter(train_loader))\n", + "print(f\"Training batch input shape: {X_batch.shape}\")\n", + "print(f\"Training batch labels shape: {y_batch.shape}\")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Get one batch of images and labels\n", + "images, labels = next(iter(train_loader))\n", + "\n", + "# Display the first 6 images in the batch\n", + "plt.figure(figsize=(8, 4))\n", + "\n", + "for i in range(6):\n", + " plt.subplot(2, 3, i + 1)\n", + "\n", + " # Convert from (C, H, W) to (H, W, C) for matplotlib\n", + " img = images[i].permute(1, 2, 0)\n", + "\n", + " plt.imshow(img)\n", + " plt.title(f\"Label: {labels[i].item()}\")\n", + " plt.axis('off')\n", + "\n", + "plt.tight_layout()\n", + "plt.show()\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your model class here:\n", + "class NN4Layer(nn.Module):\n", + "\n", + " def __init__(self, input_dim, hidden_dim):\n", + " super(NN4Layer, self).__init__()\n", + "\n", + " # TODO: What are the dimensions of the first layer? (hint: features? hidden neurons?)\n", + " self.layer1 = nn.Linear(input_dim, hidden_dim)\n", + "\n", + " # TODO: What are the dimensions from previous and next layer?\n", + " self.layer2 = nn.Linear(hidden_dim, hidden_dim)\n", + "\n", + " # TODO: What are the dimensions from previous and next layer?\n", + " self.layer3 = nn.Linear(hidden_dim, hidden_dim)\n", + "\n", + " # TODO: What are the dimensions from previous and next layer?\n", + " self.layer4 = nn.Linear(hidden_dim, 1)\n", + "\n", + "\n", + " # activation function for non-linearity\n", + " self.relu = nn.ReLU()\n", + "\n", + " # Defines how input data flows through the network\n", + " def forward(self, x):\n", + " # Layer 1: TODO\n", + " z1 = self.layer1(x)\n", + " a1 = self.relu(z1)\n", + "\n", + " # Layer 2 TODO\n", + " z2 = self.layer2(a1)\n", + " a2 = self.relu(z2)\n", + "\n", + " # Layer 3 TODO\n", + " z3 = self.layer3(a2)\n", + " a3 = self.relu(z3)\n", + "\n", + " # Layer 4 TODO\n", + " output = self.layer4(a3)\n", + "\n", + "\n", + "\n", + " return output" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your training loop here:\n", + "def train_one_epoch(model, optimizer, criterion, train_loader, device):\n", + " # Set the model to training mode\n", + " model.train()\n", + "\n", + " running_loss = 0.0\n", + "\n", + " for X_batch, y_batch in train_loader:\n", + " # Move batch to the selected device\n", + " X_batch = X_batch.to(device)\n", + " y_batch = y_batch.view(-1, 1).to(device)\n", + "\n", + " # Forward pass\n", + " # TODO: make predictions\n", + " outputs = model(X_batch) # shape: (batch_size, 10)\n", + " # TODO: compute loss\n", + " loss = criterion(outputs, y_batch)\n", + "\n", + " # Backward pass & optimization\n", + " optimizer.zero_grad() # Clear previous gradients\n", + " loss.backward() # Compute gradients\n", + " optimizer.step() # Update model parameters\n", + "\n", + " running_loss += loss.item()\n", + "\n", + " # Average loss over all batches\n", + " avg_loss = running_loss / len(train_loader)\n", + "\n", + " return avg_loss" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "print(X_batch.shape)\n", + "print(y_batch.shape)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "def validate(model, criterion, test_loader, device):\n", + " # Set the model to evaluation mode\n", + " model.eval()\n", + "\n", + " running_loss = 0.0\n", + "\n", + " with torch.no_grad():\n", + " for X_batch, y_batch in test_loader:\n", + " # Move data to device\n", + " X_batch = X_batch.to(device) # shape: (batch_size, num_features)\n", + " y_batch = y_batch.view(-1, 1).to(device) # shape: (batch_size, 1)\n", + "\n", + " # Forward pass (continuous output)\n", + " outputs = model(X_batch.view(32,-1)) # shape: (batch_size, 1)\n", + " loss = criterion(outputs, y_batch)\n", + "\n", + " running_loss += loss.item()\n", + "\n", + " # Average loss over all batches\n", + " avg_loss = running_loss / len(test_loader)\n", + "\n", + " return avg_loss" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "print(X_batch.shape)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Model parameters\n", + "input_dim = X_train.shape[1] # Number of tabular features\n", + "hidden_dim = 32 # Design choice\n", + "\n", + "# Instantiate regression model\n", + "model = NN4Layer(input_dim, hidden_dim).to(device)\n", + "\n", + "# Print the model architecture\n", + "print(\"Model Architecture:\\n\")\n", + "print(model)\n", + "\n", + "# Calculate the total number of trainable parameters\n", + "total_params = sum(p.numel() for p in model.parameters() if p.requires_grad)\n", + "print(f\"\\nTotal trainable parameters: {total_params}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "num_epochs = 20\n", + "learning_rate = 0.001" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Define criterion (loss function)\n", + "criterion = nn.MSELoss()\n", + "# Define optimizer\n", + "optimizer = AdamW(model.parameters(), learning_rate)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "train_losses = []\n", + "val_losses = []\n", + "\n", + "print('Starting Training...')\n", + "for epoch in range(20):\n", + " # Train one epoch\n", + " train_loss = train_one_epoch(model, optimizer, criterion, train_loader, device)\n", + "\n", + " # Validate\n", + " val_loss = validate(model, criterion, test_loader, device)\n", + "\n", + " train_losses.append(train_loss)\n", + " val_losses.append(val_loss)\n", + "\n", + " if (epoch + 1) % 5 == 0:\n", + " print(\n", + " f'Epoch [{epoch+1}/{num_epochs}], '\n", + " f'Train Loss: {train_loss:.4f}, '\n", + " f'Val Loss: {val_loss:.4f}'\n", + " )\n", + "\n", + "print('Training Complete!')" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "# Plotting results\n", + "plt.figure(figsize=(7, 5))\n", + "\n", + "plt.plot(train_losses, label='Train Loss')\n", + "plt.plot(val_losses, label='Validation Loss')\n", + "plt.title('Loss over Epochs')\n", + "plt.xlabel('Epoch')\n", + "plt.ylabel('Loss (MSE)')\n", + "plt.legend()\n", + "\n", + "plt.tight_layout()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2 (Bonus): Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/433/Q3.ipynb b/submissions_extracted/433/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..ebfd7be4ea3a76741e26b5232b6e1ca8116c9f13 --- /dev/null +++ b/submissions_extracted/433/Q3.ipynb @@ -0,0 +1,338 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "import pandas as pd\n", + "import numpy as np\n", + "import matplotlib.pyplot as plt\n", + "import seaborn as sns\n", + "import kagglehub\n", + "import os\n", + "from tqdm import tqdm\n", + "\n", + "%matplotlib inline\n", + "from sklearn.model_selection import StratifiedKFold\n", + "from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score\n", + "\n", + "# Download latest version\n", + "\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q3-exam-data\")\n", + "\n", + "\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "import pandas as pd\n", + "df = pd.read_csv('/kaggle/input/q3-exam-data/Q3_data.csv')\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "\n", + "# Task 3: Write your code here:\n", + "df.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "df.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "print(\"Missing values:\")\n", + "print(df.isnull().sum())\n", + "categorical_cols = df.select_dtypes(include=[\"object\"]).columns\n", + "num_cols = df.select_dtypes(include=[\"number\"]).columns" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "for col in categorical_cols:\n", + " df[col]=df[col].fillna(\"none\")\n", + "for col in num_cols:\n", + " df[col]=df[col].fillna(0)\n", + "print(\"Missing values:\")\n", + "print(df.isnull().sum())" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "def check_duplicates(df):\n", + " duplicates = df.duplicated().sum()\n", + " print(f\"Number of Duplicate Samples: {duplicates}\")\n", + " if duplicates > 0:\n", + " print(\"Dropping Duplicates...\")\n", + " df.drop_duplicates(inplace=True)\n", + " print(\"Duplicates Dropped.\")\n", + " else:\n", + " print(\"No Duplicate Samples Found.\")\n", + "\n", + "check_duplicates(df)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "from sklearn.preprocessing import StandardScaler, LabelEncoder\n", + "categorical_cols = df.select_dtypes(include=[\"object\"]).columns\n", + "for col in categorical_cols:\n", + " print(f\"Encoding column: {col}\")\n", + " le = LabelEncoder()\n", + " df[col] = le.fit_transform(df[col])\n", + "df" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "numerical_cols = df.select_dtypes(include=[\"int64\", \"float64\"]).columns.drop(\"Target\") ### DON'T SCALE THE TARGET\n", + "scaler = StandardScaler()\n", + "df[numerical_cols] = scaler.fit_transform(df[numerical_cols])\n", + "df" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "df['Target'].hist()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "X = df.drop(\"Target\", axis=1).astype(float)\n", + "y = df[\"Target\"].astype(float)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "%pip install kagglehub catboost xgboost tqdm -q\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:\n", + "from sklearn.neighbors import KNeighborsClassifier\n", + "from sklearn.svm import SVC\n", + "from sklearn.tree import DecisionTreeClassifier\n", + "from sklearn.ensemble import RandomForestClassifier\n", + "from xgboost import XGBClassifier\n", + "from catboost import CatBoostClassifier\n", + "sklearn_models = {\n", + "\n", + " \"CatBoost\": CatBoostClassifier(\n", + " verbose=0,\n", + " n_estimators=320,\n", + " max_depth=4\n", + " )\n", + "}" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "all_results = {}\n", + "\n", + "for name in sklearn_models:\n", + " all_results[name] = {'accuracy': [], 'precision': [], 'recall': [], 'f1': []}" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "n_splits = 5 # K\n", + "\n", + "# Stratified 5-Fold Cross-Validation, shuffled\n", + "skf = StratifiedKFold(n_splits=n_splits, shuffle=True, random_state=42)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "for fold_idx, (train_index, test_index) in enumerate(skf.split(X, y)):\n", + " print(f\"\\nFold {fold_idx + 1}/{n_splits}\")\n", + "\n", + " # 1. Split data\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", + " # 2. Train & Validate sklearn models\n", + " for model_name, model in sklearn_models.items():\n", + " print(f\"Training {model_name}...\")\n", + " model.fit(X_train, y_train) # train\n", + " y_pred = model.predict(X_test) # validate\n", + "\n", + " # 3. Save metrics for that model in this fold\n", + " accuracy = accuracy_score(y_test, y_pred)\n", + " precision = precision_score(y_test, y_pred, zero_division=0)\n", + " recall = recall_score(y_test, y_pred, zero_division=0)\n", + " f1 = f1_score(y_test, y_pred, zero_division=0)\n", + "\n", + " all_results[model_name]['accuracy'].append(accuracy)\n", + " all_results[model_name]['precision'].append(precision)\n", + " all_results[model_name]['recall'].append(recall)\n", + " all_results[model_name]['f1'].append(f1)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "for model_name in all_results:\n", + " print(f\"\\n{model_name}:\")\n", + " print(f\" Accuracy: {np.mean(all_results[model_name]['accuracy']):.4f}\")\n", + " print(f\" F1-Score: {np.mean(all_results[model_name]['f1']):.4f}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "importances = {}\n", + "\n", + "\n", + "importances['CatBoost'] = sklearn_models['CatBoost'].feature_importances_\n", + "\n", + "# Create a 1x3 plot\n", + "fig, axes = plt.subplots(1, 3, figsize=(18, 6))\n", + "axes = axes.flatten()\n", + "features = X.columns\n", + "\n", + "for i, (model_name, imp) in enumerate(importances.items()):\n", + " # Sort features by importance for a cleaner plot\n", + " sorted_idx = np.argsort(imp)\n", + "\n", + " ax = axes[i]\n", + " ax.barh(features[sorted_idx], imp[sorted_idx])\n", + " ax.set_title(f\"{model_name} Feature Importance\")\n", + " ax.set_xlabel(\"Importance Score\")\n", + "\n", + "plt.tight_layout()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "sklearn_models['CatBoost',].feature_importances_" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/434/Q1.ipynb b/submissions_extracted/434/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..da4c53f112d934de5675a5873194a9244b6733a7 --- /dev/null +++ b/submissions_extracted/434/Q1.ipynb @@ -0,0 +1,381 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "import pandas as pd\n", + "import numpy as np\n", + "import os\n", + "import matplotlib.pyplot as plt\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q1-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)\n", + "os.listdir(path)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "\n", + "import kagglehub\n", + "import pandas as pd\n", + "import numpy as np\n", + "import os\n", + "import matplotlib.pyplot as plt\n", + "\n", + "file_path = os.path.join(path, \"Q1_data.csv\")\n", + "\n", + "df = pd.read_csv(file_path)\n", + "\n", + "df.head()\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "print(\"First 5 rows of the dataset:\")\n", + "display(df.head())" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "print(\"\\nDataset info:\")\n", + "df.info()\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "print(\"\\nStatistical description:\")\n", + "display(df.describe())\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "\n", + "plt.figure(figsize=(6,4))\n", + "plt.hist(df[\"Delivery_Time\"], bins=30)\n", + "plt.title(\"Delivery Time Distribution\")\n", + "plt.xlabel(\"Delivery Time (minutes)\")\n", + "plt.ylabel(\"Frequency\")\n", + "plt.show()\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "if \"Order_ID\" in df.columns:\n", + " df = df.drop(columns=[\"Order_ID\"])\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "# Check missing values\n", + "def check_missing_values(df):\n", + " missing_values = df.isnull().sum()\n", + " print(\"Missing Values per Column:\")\n", + " print(missing_values[missing_values > 0])\n", + " if missing_values.any():\n", + " print(\"\\nHandle Missing Values as needed.\")\n", + " else:\n", + " print(\"\\nNo Missing Values Found.\")\n", + "\n", + "missing = df.isnull().sum()\n", + "print(\"Missing values per column:\")\n", + "print(missing[missing > 0])\n", + "\n", + "num_cols = df.select_dtypes(include=[\"number\"]).columns\n", + "cat_cols = df.select_dtypes(exclude=[\"number\"]).columns\n", + "\n", + "df[num_cols] = df[num_cols].fillna(df[num_cols].median())\n", + "\n", + "for col in cat_cols:\n", + " df[col] = df[col].fillna(df[col].mode()[0])\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "\n", + "dup_count = df.duplicated().sum()\n", + "print(\"Number of duplicate rows:\", dup_count)\n", + "\n", + "if dup_count > 0:\n", + " df = df.drop_duplicates()\n", + " print(\"Duplicates removed. New shape:\", df.shape)\n", + "else:\n", + " print(\"No duplicate samples found.\")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "df = pd.get_dummies(df, drop_first=True)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "\n", + "from sklearn.preprocessing import StandardScaler\n", + "import pandas as pd\n", + "\n", + "target_col = \"Delivery_Time\"\n", + "\n", + "X = df.drop(columns=[target_col])\n", + "y = df[target_col]\n", + "\n", + "scaler = StandardScaler()\n", + "X_scaled = scaler.fit_transform(X)\n", + "\n", + "X = pd.DataFrame(X_scaled, columns=X.columns)\n", + "\n", + "print(\"Feature matrix shape:\", X.shape)\n", + "print(\"Target shape:\", y.shape)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 6: Write your code here:\n", + "\n", + "target_counts = y.value_counts()\n", + "print(\"Target counts:\")\n", + "print(target_counts)\n", + "\n", + "print(\"\\nTarget proportions:\")\n", + "print((target_counts / target_counts.sum()).round(4))\n", + "\n", + "target_counts.plot(kind=\"bar\", title=\"Target Distribution\")\n", + "plt.show()\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "target_col = \"Delivery_Time\"\n", + "\n", + "X = df.drop(columns=[target_col])\n", + "y = df[target_col]\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:\n", + "from sklearn.model_selection import KFold, StratifiedKFold\n", + "from sklearn.ensemble import RandomForestRegressor\n", + "from sklearn.metrics import mean_absolute_error\n", + "import numpy as np\n", + "\n", + "# T2\n", + "\n", + "if y.nunique() <= 20:\n", + " cv = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)\n", + " splits = cv.split(X, y)\n", + "else:\n", + " cv = KFold(n_splits=5, shuffle=True, random_state=42)\n", + " splits = cv.split(X)\n", + "\n", + "mae_scores = []\n", + "\n", + "# T3,4\n", + "for train_idx, val_idx in splits:\n", + " X_train, X_val = X.iloc[train_idx], X.iloc[val_idx]\n", + " y_train, y_val = y.iloc[train_idx], y.iloc[val_idx]\n", + "\n", + " model = RandomForestRegressor(random_state=42)\n", + " model.fit(X_train, y_train)\n", + "\n", + " preds = model.predict(X_val)\n", + " fold_mae = mean_absolute_error(y_val, preds)\n", + " mae_scores.append(fold_mae)\n", + "\n", + "# T5\n", + "print(\"Fold MAEs:\", np.round(mae_scores, 4))\n", + "print(\"Average MAE:\", round(float(np.mean(mae_scores)), 4))\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "import pandas as pd\n", + "import matplotlib.pyplot as plt\n", + "from sklearn.ensemble import RandomForestRegressor\n", + "\n", + "final_model = RandomForestRegressor(random_state=42)\n", + "final_model.fit(X, y)\n", + "\n", + "fi = pd.DataFrame({\n", + " \"feature\": X.columns,\n", + " \"importance\": final_model.feature_importances_\n", + "}).sort_values(\"importance\", ascending=False)\n", + "\n", + "print(fi.head(10))\n", + "\n", + "fi.head(15).plot(kind=\"barh\", x=\"feature\", y=\"importance\", title=\"Top Feature Importances\")\n", + "plt.gca().invert_yaxis()\n", + "plt.show()\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "import matplotlib.pyplot as plt\n", + "\n", + "preds = final_model.predict(X)\n", + "\n", + "plt.hist(preds, bins=25)\n", + "plt.title(\"Predicted Delivery Time Histogram\")\n", + "plt.xlabel(\"Predicted delivery time\")\n", + "plt.ylabel(\"Frequency\")\n", + "plt.show()\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:\n", + "import numpy as np\n", + "from sklearn.model_selection import KFold\n", + "from sklearn.metrics import mean_absolute_error\n", + "from sklearn.ensemble import RandomForestRegressor\n", + "\n", + "try:\n", + " from catboost import CatBoostRegressor\n", + " catboost_ok = True\n", + "except:\n", + " catboost_ok = False\n", + " print(\"CatBoost not available - will run RandomForest only.\")\n", + "\n", + "target_col = \"Delivery_Time\"\n", + "X = df.drop(columns=[target_col])\n", + "y = df[target_col]\n", + "\n", + "# KFold\n", + "kf = KFold(n_splits=5, shuffle=True, random_state=42)\n", + "\n", + "mae_scores = []\n", + "\n", + "for fold, (train_idx, val_idx) in enumerate(kf.split(X), 1):\n", + " X_train, X_val = X.iloc[train_idx], X.iloc[val_idx]\n", + " y_train, y_val = y.iloc[train_idx], y.iloc[val_idx]\n", + "\n", + " # Model 1: RandomForest\n", + " rf = RandomForestRegressor(random_state=42, n_estimators=300)\n", + " rf.fit(X_train, y_train)\n", + " pred_rf = rf.predict(X_val)\n", + "\n", + " # Model 2: CatBoost (if available)\n", + " if catboost_ok:\n", + " cb = CatBoostRegressor(random_state=42, verbose=0)\n", + " cb.fit(X_train, y_train)\n", + " pred_cb = cb.predict(X_val)\n", + "\n", + " # Avp\n", + " pred_avg = (pred_rf + pred_cb) / 2\n", + " else:\n", + " pred_avg = pred_rf\n", + "\n", + " mae = mean_absolute_error(y_val, pred_avg)\n", + " mae_scores.append(mae)\n", + " print(f\"Fold {fold} MAE:\", round(mae, 4))\n", + "\n", + "print(\"\\nAverage MAE across folds:\", round(float(np.mean(mae_scores)), 4))\n", + "\n" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/434/Q2.ipynb b/submissions_extracted/434/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..379fac402108be1b5902812ad5503612cdb3b424 --- /dev/null +++ b/submissions_extracted/434/Q2.ipynb @@ -0,0 +1,319 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q2-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import os\n", + "import pandas as pd\n", + "import numpy as np\n", + "from PIL import Image\n", + "from sklearn.model_selection import train_test_split\n", + "\n", + "# Load Labels\n", + "labels_df = pd.read_csv(os.path.join(path, \"labels.csv\"))\n", + "img_dir = os.path.join(path, \"images\")\n", + "\n", + "images = []\n", + "ages = []\n", + "\n", + "print(\"Loading images...\")\n", + "for index, row in labels_df.iterrows():\n", + " img_name = row.iloc[0]\n", + " age = row.iloc[1]\n", + " img_path = os.path.join(img_dir, img_name)\n", + "\n", + " if os.path.exists(img_path):\n", + " img = Image.open(img_path).convert('RGB')\n", + " img_array = np.array(img) / 255.0 # Normalize pixel values to [0, 1]\n", + " images.append(img_array)\n", + " ages.append(age)\n", + "\n", + "X = np.array(images)\n", + "y = np.array(ages)\n", + "\n", + "# Transpose image dimensions to match PyTorch format (N, C, H, W)\n", + "X = np.transpose(X, (0, 3, 1, 2))\n", + "\n", + "# Split Data\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n", + "\n", + "print(f\"X_train shape: {X_train.shape}\")\n", + "print(f\"X_test shape: {X_test.shape}\")\n", + "print(f\"y_train shape: {y_train.shape}\")\n", + "print(f\"y_test shape: {y_test.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 1. Convert Numpy arrays to PyTorch Tensors\n", + "\n", + "import torch\n", + "\n", + "X_train_t = torch.tensor(X_train, dtype=torch.float32)\n", + "X_test_t = torch.tensor(X_test, dtype=torch.float32)\n", + "\n", + "y_train_t = torch.tensor(y_train, dtype=torch.float32).view(-1, 1)\n", + "y_test_t = torch.tensor(y_test, dtype=torch.float32).view(-1, 1)\n", + "\n", + "print(X_train_t.shape, y_train_t.shape)\n", + "print(X_test_t.shape, y_test_t.shape)\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 2. Create TensorDataset objects\n", + "\n", + "\n", + "from torch.utils.data import TensorDataset\n", + "\n", + "train_dataset = TensorDataset(X_train_t, y_train_t)\n", + "test_dataset = TensorDataset(X_test_t, y_test_t)\n", + "\n", + "len(train_dataset), len(test_dataset)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 3. Create DataLoaders\n", + "\n", + "from torch.utils.data import DataLoader\n", + "\n", + "train_loader = DataLoader(train_dataset, batch_size=32, shuffle=True)\n", + "test_loader = DataLoader(test_dataset, batch_size=32, shuffle=False)\n", + "\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 4. Print shape of one batch\n", + "xb, yb = next(iter(train_loader))\n", + "print(\"X batch:\", xb.shape)\n", + "print(\"y batch:\", yb.shape)\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 5. Display sample images\n", + "import matplotlib.pyplot as plt\n", + "\n", + "xb, yb = next(iter(train_loader))\n", + "\n", + "fig, axes = plt.subplots(1, 5, figsize=(12, 3))\n", + "for i in range(5):\n", + " img = xb[i].permute(1, 2, 0).numpy() # (H, W, C)\n", + " axes[i].imshow(img)\n", + " axes[i].set_title(f\"Age: {yb[i].item():.0f}\")\n", + " axes[i].axis(\"off\")\n", + "plt.show()\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your model class here:\n", + "import torch.nn as nn\n", + "\n", + "class AgeRegressor(nn.Module):\n", + " def __init__(self):\n", + " super().__init__()\n", + " # Flatten 3x36x36 into a vector\n", + " self.flatten = nn.Flatten()\n", + " self.net = nn.Sequential(\n", + " nn.Linear(3*36*36, 512), # 1\n", + " nn.ReLU(),\n", + " nn.Linear(512, 128), # 2\n", + " nn.ReLU(),\n", + " nn.Linear(128, 32), # 3\n", + " nn.ReLU(),\n", + " nn.Linear(32, 1) # 4\n", + "\n", + " def forward(self, x):\n", + " x = self.flatten(x)\n", + " return self.net(x)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your training loop here:\n", + "import torch\n", + "\n", + "def train_one_epoch(model, loader, optimizer, loss_fn, device):\n", + " model.train()\n", + " total_loss = 0.0\n", + "\n", + " for xb, yb in loader:\n", + " xb, yb = xb.to(device), yb.to(device)\n", + "\n", + " optimizer.zero_grad()\n", + " preds = model(xb)\n", + " loss = loss_fn(preds, yb)\n", + " loss.backward()\n", + " optimizer.step()\n", + "\n", + " total_loss += loss.item() * xb.size(0)\n", + "\n", + " return total_loss / len(loader.dataset)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your validation loop here:\n", + "def validate(model, loader, loss_fn, device):\n", + " model.eval()\n", + " total_loss = 0.0\n", + "\n", + " with torch.no_grad():\n", + " for xb, yb in loader:\n", + " xb, yb = xb.to(device), yb.to(device)\n", + " preds = model(xb)\n", + " loss = loss_fn(preds, yb)\n", + " total_loss += loss.item() * xb.size(0)\n", + "\n", + " return total_loss / len(loader.dataset)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Define device, model, loss, optimizer:\n", + "import torch.optim as optim\n", + "import torch.nn as nn\n", + "\n", + "device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n", + "\n", + "model = AgeRegressor().to(device)\n", + "loss_fn = nn.MSELoss()\n", + "optimizer = optim.Adam(model.parameters(), lr=1e-3)\n", + "\n", + "device\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Start training for 20 epochs:\n", + "train_losses = []\n", + "val_losses = []\n", + "\n", + "for epoch in range(20):\n", + " tr_loss = train_one_epoch(model, train_loader, optimizer, loss_fn, device)\n", + " va_loss = validate(model, test_loader, loss_fn, device)\n", + "\n", + " train_losses.append(tr_loss)\n", + " val_losses.append(va_loss)\n", + "\n", + " print(f\"Epoch {epoch+1:02d} | train loss: {tr_loss:.4f} | val loss: {va_loss:.4f}\")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "import matplotlib.pyplot as plt\n", + "\n", + "plt.plot(train_losses, label=\"train\")\n", + "plt.plot(val_losses, label=\"val\")\n", + "plt.title(\"Loss over epochs\")\n", + "plt.xlabel(\"Epoch\")\n", + "plt.ylabel(\"MSE Loss\")\n", + "plt.legend()\n", + "plt.show()\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2 (Bonus): Write your code here:\n", + "model.eval()\n", + "xb, yb = next(iter(test_loader))\n", + "xb, yb = xb.to(device), yb.to(device)\n", + "\n", + "with torch.no_grad():\n", + " preds = model(xb).squeeze(1)\n", + "\n", + "fig, axes = plt.subplots(1, 5, figsize=(12, 3))\n", + "for i in range(5):\n", + " img = xb[i].cpu().permute(1, 2, 0).numpy()\n", + " axes[i].imshow(img)\n", + " axes[i].set_title(f\"P:{preds[i].item():.1f}\\nT:{yb[i].item():.0f}\")\n", + " axes[i].axis(\"off\")\n", + "plt.show()\n" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/434/Q3.ipynb b/submissions_extracted/434/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..f69fd284abc070b037ab11484bcd69dd47eb3f68 --- /dev/null +++ b/submissions_extracted/434/Q3.ipynb @@ -0,0 +1,259 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "\n", + "\n", + "# Download latest version\n", + "\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q3-exam-data\")\n", + "\n", + "\n", + "\n", + "print(\"Path to dataset files:\", path)\n", + "os.listdir(path)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "\n", + "import pandas as pd\n", + "import numpy as np\n", + "import os\n", + "import matplotlib.pyplot as plt\n", + "\n", + "file_path = os.path.join(path, \"Q3_data.csv\")\n", + "\n", + "df = pd.read_csv(file_path)\n", + "\n", + "df.head()\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "df.head()\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "df.info()\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "df.describe(include=\"all\")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "\n", + "\n", + "missing = df.isnull().sum().sort_values(ascending=False)\n", + "print(missing[missing > 0])\n", + "\n", + "\n", + "missing = df.isnull().sum()\n", + "print(missing[missing > 0])\n", + "\n", + "num_cols = df.select_dtypes(include=[\"number\"]).columns\n", + "cat_cols = df.select_dtypes(exclude=[\"number\"]).columns\n", + "\n", + "df[num_cols] = df[num_cols].fillna(df[num_cols].median())\n", + "for c in cat_cols:\n", + " df[c] = df[c].fillna(df[c].mode()[0])\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "print(\"Duplicate rows:\", df.duplicated().sum())\n", + "\n", + "\n", + "\n", + "dup = df.duplicated().sum()\n", + "print(\"Duplicates:\", dup)\n", + "if dup > 0:\n", + " df = df.drop_duplicates()\n", + " print(\"New shape:\", df.shape)\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "\n", + "cat_cols = df.select_dtypes(exclude=[\"number\"]).columns\n", + "print(\"Categorical columns:\", list(cat_cols))\n", + "\n", + "if len(cat_cols) > 0:\n", + " df = pd.get_dummies(df, columns=cat_cols, drop_first=True)\n", + " print(\"Applied One-Hot Encoding\")\n", + "\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "\n", + "from sklearn.preprocessing import StandardScaler\n", + "\n", + "# Separate target before scaling\n", + "target_col = \"B_6\"\n", + "X = df.drop(columns=[target_col])\n", + "y = df[target_col]\n", + "\n", + "scaler = StandardScaler()\n", + "X_scaled = scaler.fit_transform(X)\n", + "\n", + "X = pd.DataFrame(X_scaled, columns=X.columns)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "\n", + "counts = y.value_counts()\n", + "print(\"Target value counts:\")\n", + "print(counts)\n", + "\n", + "print(\"\\nTarget proportions:\")\n", + "print((counts / counts.sum()).round(4))\n", + "\n", + "counts.plot(kind=\"bar\", title=\"Target Distribution\")\n", + "plt.show()\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "\n", + "# Task 1: Split dataset into X and y\n", + "\n", + "target_col = \"B_6\"\n", + "\n", + "X = df.drop(columns=[target_col])\n", + "y = df[target_col]\n", + "\n", + "print(\"X shape:\", X.shape)\n", + "print(\"y shape:\", y.shape)\n", + "print(\"Target distribution:\")\n", + "print(y.value_counts(normalize=True))\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:\n", + "\n", + "print(\"Columns:\", list(df.columns))\n", + "\n", + "for c in df.columns:\n", + " nun = df[c].nunique(dropna=True)\n", + " if nun <= 20:\n", + " print(c, \"nunique =\", nun, \"| sample values:\", df[c].dropna().unique()[:10])\n", + "\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "print(\":(\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "\n", + "print(\":(\")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:\n", + "\n", + "print(\":(\")" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/435/Q1.ipynb b/submissions_extracted/435/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..fe13170eaf1a32149a7b13c6fe53775e8b0d1725 --- /dev/null +++ b/submissions_extracted/435/Q1.ipynb @@ -0,0 +1,296 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import pandas as pd\n", + "import numpy as np\n", + "import matplotlib.pyplot as plt\n", + "import seaborn as sns\n", + "import kagglehub\n", + "import os\n", + "from tqdm import tqdm\n", + "\n", + "%matplotlib inline" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q1-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "CSV_PATH = \"data.csv\" # read_csv()\n", + "#LABEL_COL = \"label\"\n", + "#USE_FALLBACK_IRIS = True\n", + "#csv_path = os.path.join(path ,\"q1-exam-data\")\n", + "#f = pd.read_csv(csv_path)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "\n", + "from pathlib import Path\n", + "import numpy as np\n", + "\n", + "csv_file = Path(CSV_PATH)\n", + "\n", + "if csv_file.exists() and not q1-exam-data:\n", + "\n", + " df = pd.read_csv(CSV_PATH)\n", + " print(\"✅ Loaded:\", CSV_PATH)\n", + "\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "df.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "df.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "df['age'].value_counts().plot(kind='bar')\n", + "\n", + "plt.show()\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "N = 250\n", + "\n", + "df = pd.DataFrame({\n", + " 'age': np.random.randint(18, 60, size=N).astype(float),\n", + " 'salary': np.random.normal(8000, 2500, size=N),\n", + " 'city': np.random.choice(['Riyadh', 'Jeddah', 'Dammam'], size=N, p=[0.5, 0.35, 0.15]),\n", + " 'has_experience': np.random.choice(['yes', 'no'], size=N, p=[0.65, 0.35]),\n", + "})\n", + "\n", + "\n", + "prob = 1 / (1 + np.exp(-( (df['salary'] - 8000)/1800 + (df['has_experience'] == 'yes')*0.8 )))\n", + "df['bought'] = (np.random.rand(N) < prob).astype(int)\n", + "\n", + "\n", + "df.loc[np.random.choice(df.index, size=12, replace=False), 'age'] = np.nan\n", + "df.loc[np.random.choice(df.index, size=10, replace=False), 'salary'] = np.nan\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "\n", + "\n", + "df.loc[np.random.choice(df.index, size=12, replace=False), 'age'] = np.nan\n", + "df.loc[np.random.choice(df.index, size=10, replace=False), 'salary'] = np.nan\n", + "\n", + "display(df.info())\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "df.dropna(how='all' , inplace=True)\n", + "df" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "df.describe(include=['object']).T\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "df.isna().sum()\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "missing = df.isnull().sum().sort_values(ascending=False)\n", + "display(missing)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 3. Do we have categorical columns?\n", + "categorical_cols = df.select_dtypes(include=[\"object\"]).columns\n", + "\n", + "print(\"Categorical Columns:\", list(categorical_cols))\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "for fold_idx, (train_index, test_index) in enumerate(skf.split(X, y)):\n", + " print(f\"\\nFold {fold_idx + 1}/{n_splits}\")\n", + "\n", + " # 1. Split data\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]" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:\n", + "\n", + "\n", + " # 2. Train & Validate sklearn models\n", + " for model_name, model in sklearn_models.items():\n", + " print(f\"Training {model_name}...\")\n", + " model.fit(X_train, y_train) # train\n", + " y_pred = model.predict(X_test) # validate\n", + "\n", + " # 3. Save metrics for that model in this fold\n", + " accuracy = accuracy_score(y_test, y_pred)\n", + " precision = precision_score(y_test, y_pred, zero_division=0)\n", + " recall = recall_score(y_test, y_pred, zero_division=0)\n", + " f1 = f1_score(y_test, y_pred, zero_division=0)\n", + "\n", + " all_results[model_name]['accuracy'].append(accuracy)\n", + " all_results[model_name]['precision'].append(precision)\n", + " all_results[model_name]['recall'].append(recall)\n", + " all_results[model_name]['f1'].append(f1)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "importances = {}\n", + "\n", + "importances['Random Forest'] = sklearn_models['Random Forest'].feature_importances_" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/435/Q2.ipynb b/submissions_extracted/435/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..ad291ef46886b42ea8a7498bf1cc31773c8e3817 --- /dev/null +++ b/submissions_extracted/435/Q2.ipynb @@ -0,0 +1,390 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q2-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import os\n", + "import pandas as pd\n", + "import numpy as np\n", + "from PIL import Image\n", + "from sklearn.datasets import load_breast_cancer\n", + "from sklearn.model_selection import train_test_split\n", + "from torch.utils.data import TensorDataset\n", + "from torch.utils.data import DataLoader\n", + "import torch\n", + "from torchvision.datasets import MNIST\n", + "from torchvision.transforms.functional import to_tensor\n", + "import torch\n", + "import torch.nn as nn\n", + "\n", + "\n", + "# Load Labels\n", + "labels_df = pd.read_csv(os.path.join(path, \"labels.csv\"))\n", + "img_dir = os.path.join(path, \"images\")\n", + "\n", + "images = []\n", + "ages = []\n", + "\n", + "# Load Images and Resize\n", + "print(\"Loading images...\")\n", + "for index, row in labels_df.iterrows():\n", + " img_name = row.iloc[0]\n", + " age = row.iloc[1]\n", + " img_path = os.path.join(img_dir, img_name)\n", + "\n", + " if os.path.exists(img_path):\n", + " img = Image.open(img_path).convert('RGB')\n", + " img_array = np.array(img) / 255.0 # Normalize pixel values to [0, 1]\n", + " images.append(img_array)\n", + " ages.append(age)\n", + "\n", + "X = np.array(images)\n", + "y = np.array(ages)\n", + "\n", + "# Transpose image dimensions to match PyTorch format (N, C, H, W)\n", + "X = np.transpose(X, (0, 3, 1, 2))\n", + "\n", + "# Split Data\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n", + "\n", + "print(f\"X_train shape: {X_train.shape}\")\n", + "print(f\"X_test shape: {X_test.shape}\")\n", + "print(f\"y_train shape: {y_train.shape}\")\n", + "print(f\"y_test shape: {y_test.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 2. Create data loaders\n", + "\n", + "\n", + "data = load_breast_cancer()\n", + "X = data.data\n", + "y = data.target\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 1. Convert Numpy arrays to PyTorch Tensors\n", + "\n", + "X_train = torch.tensor(X_train, dtype=torch.float32)\n", + "X_test = torch.tensor(X_test, dtype=torch.float32)\n", + "y_train = torch.tensor(y_train, dtype=torch.float32)\n", + "y_test = torch.tensor(y_test, dtype=torch.float32)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "\n", + "train_dataset = TensorDataset(X_train, y_train)\n", + "test_dataset = TensorDataset(X_test, y_test)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 3. Display a few images\n", + "\n", + "train_dataset = MNIST(\n", + " root='./datasets', # Dataset storage path\n", + " train=True, # Use training data\n", + " transform=to_tensor, # Convert images to tensors\n", + " download=True # Download if not available\n", + ")\n", + "\n", + "# Testing dataset\n", + "test_dataset = MNIST(\n", + " root='./datasets',\n", + " train=False,\n", + " transform=to_tensor,\n", + " download=True\n", + ")\n", + "\n", + "# print one sample from the dataset\n", + "# Each sample consists of an image tensor and its label\n", + "sample_image, sample_label = train_dataset[0]\n", + "\n", + "print(f\"\\n Image shape: {sample_image.shape}\") # (1, 28, 28)\n", + "print(f\"Label: {sample_label}\")\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 4. Print shape of one batch\n", + "\n", + "# DataLoader for training data\n", + "train_loader = DataLoader(\n", + " train_dataset,\n", + " batch_size=32,\n", + " shuffle=True,\n", + " num_workers=2\n", + ")\n", + "# DataLoader for test/validation data\n", + "test_loader = DataLoader(\n", + " test_dataset,\n", + " batch_size=32,\n", + " shuffle=False,\n", + " num_workers=2\n", + ")\n", + "# Get the first batch from the training DataLoader\n", + "X_batch, y_batch = next(iter(train_loader))\n", + "print(f\"Training batch input shape: {X_batch.shape}\")\n", + "print(f\"Training batch labels shape: {y_batch.shape}\")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your model class here:\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "class NN4Layer(nn.Module):\n", + " def __init__(self, input_dim, hidden_dim):\n", + " super(NN4Layer, self).__init__()\n", + "\n", + "" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "class NN4Layer(nn.Module):\n", + " def __init__(self, input_dim, hidden_dim):\n", + " super(NN4Layer, self).__init__()\n", + "\n", + " # First linear layer: input features -> hidden layer\n", + " self.layer1 = nn.Linear(input_dim, hidden_dim)\n", + "\n", + " # Second linear layer: hidden layer -> hidden layer\n", + " self.layer2 = nn.Linear(hidden_dim, hidden_dim)\n", + " self.layer3 = nn.Linear(hidden_dim ,3)\n", + "\n", + " # Output layer: hidden layer -> single continuous value\n", + " self.layer3 = nn.Linear(hidden_dim, 1)\n", + " self.layer4= nn.Linear(hidden_dim ,2 )\n", + "\n", + " # ReLU activation for non-linearity in hidden layers\n", + " self.relu = nn.ReLU()\n", + "\n", + " # Defines how input data flows through the network\n", + " def forward(self, x):\n", + " # First hidden layer\n", + " a1 = self.relu(self.layer1(x))\n", + "\n", + " # Second hidden layer\n", + " a2 = self.relu(self.layer2(a1))\n", + "\n", + " # Output layer (regression output)\n", + " output = self.layer3(a2)\n", + "\n", + " return output" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your training loop here:\n", + "\n", + "def train_one_epoch(model, optimizer, criterion, train_loader, device):\n", + " # Set the model to training mode\n", + " model.train()\n", + "\n", + " running_loss = 0.0\n", + "\n", + " for X_batch, y_batch in train_loader:\n", + " # Move batch to the selected device\n", + " X_batch = X_batch.to(device)\n", + " y_batch = y_batch.view(-1, 1).to(device)\n", + "\n", + " # Forward pass\n", + " outputs = model(X_batch)\n", + " loss = criterion(outputs, y_batch)\n", + "\n", + " # Backward pass & optimization\n", + " optimizer.zero_grad() #\n", + " loss.backward() #\n", + " optimizer.step() #\n", + "\n", + " running_loss += loss.item()\n", + "\n", + " # Average loss over all batches\n", + " avg_loss = running_loss / len(train_loader)\n", + "\n", + " return avg_loss" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your validation loop here:\n", + "def validate(model, criterion, test_loader, device):\n", + " # Set the model to evaluation mode\n", + " model.eval()\n", + "\n", + " running_loss = 0.0\n", + " correct = 0\n", + " total = 0\n", + "\n", + " with torch.no_grad(): # Disable gradient computation\n", + " for X_batch, y_batch in test_loader:\n", + " # Move batch to the selected device\n", + " X_batch = X_batch.to(device)\n", + " y_batch = y_batch.view(-1, 1).to(device)\n", + "\n", + " # Forward pass\n", + " outputs = model(X_batch)\n", + " loss = criterion(outputs, y_batch)\n", + " running_loss += loss.item()\n", + "\n", + " # Binary predictions\n", + " predicted = (outputs > 0.5).float()\n", + "\n", + " # Accuracy calculation\n", + " correct += (predicted == y_batch).sum().item()\n", + " total += y_batch.size(0)\n", + "\n", + " avg_loss = running_loss / len(test_loader)\n", + " accuracy = correct / total\n", + "\n", + " return avg_loss, accuracy\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Define device, model, loss, optimizer:\n", + "\n", + "# Device setup\n", + "device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n", + "\n", + "# Model parameters\n", + "input_dim = X_train.shape[1] # Number of tabular features\n", + "hidden_dim = 14 # Design choice\n", + "output_dim = 4 # Weather classes: Rainy, Sunny, Cloudy, Snowy\n", + "model = NN4Layer(input_dim, hidden_dim).to(device)\n", + "\n", + "# Print the model architecture\n", + "print(\"Model Architecture:\\n\")\n", + "print(model)\n", + "\n", + "# Calculate the total number of trainable parameters\n", + "total_params = sum(p.numel() for p in model.parameters() if p.requires_grad)\n", + "print(f\"\\nTotal trainable parameters: {total_params}\")\n", + "\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Start training for 20 epochs:\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2 (Bonus): Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/435/Q3.ipynb b/submissions_extracted/435/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..ad041215868f67d9f20ebafb7bb20bc4c1e05649 --- /dev/null +++ b/submissions_extracted/435/Q3.ipynb @@ -0,0 +1,177 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "import pandas as pd\n", + "\n", + "import numpy as np\n", + "import torch\n", + "import torch.nn as nn\n", + "from torch.optim import AdamW\n", + "import matplotlib.pyplot as plt\n", + "from torch.utils.data import DataLoader, TensorDataset\n", + "from sklearn.model_selection import train_test_split\n", + "from sklearn.preprocessing import StandardScaler, LabelEncoder\n", + "from sklearn.metrics import mean_absolute_error, mean_squared_error, r2_score\n", + "\n", + "\n", + "# Download latest version\n", + "\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q3-exam-data\")\n", + "\n", + "\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Download latest version\n", + "\n", + "df = pd.read_csv(path , \"/kaggle/input/q3-exam-data\")\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "df.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "df.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "missing = df.isnull().sum().sort_values(ascending=False)\n", + "display(missing)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/436/Q1.ipynb b/submissions_extracted/436/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..c1ee0a446e55b6bd89280712628b7753c23266d1 --- /dev/null +++ b/submissions_extracted/436/Q1.ipynb @@ -0,0 +1,395 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "\n", + "import numpy as np\n", + "import pandas as pd\n", + "import matplotlib.pyplot as plt\n", + "import seaborn as sns\n", + "\n", + "from sklearn.model_selection import train_test_split, KFold, cross_val_score\n", + "from sklearn.preprocessing import StandardScaler, OneHotEncoder, LabelEncoder, PolynomialFeatures\n", + "from sklearn.compose import ColumnTransformer\n", + "from sklearn.pipeline import Pipeline\n", + "from sklearn.linear_model import LinearRegression\n", + "from sklearn.metrics import mean_absolute_error, mean_squared_error, r2_score\n", + "\n", + "from sklearn.ensemble import RandomForestRegressor\n", + "\n", + "import warnings\n", + "warnings.filterwarnings('ignore')\n", + "\n", + "plt.rcParams['figure.figsize'] = (8, 5)\n", + "plt.rcParams['axes.grid'] = True\n", + "\n", + "print(\"Done\")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q1-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import os\n", + "\n", + "data_path = os.path.join(path, \"Q1_data.csv\")\n", + "print (data_path)\n", + "\n", + "df = pd.read_csv(data_path)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "print(\"First 5 rows of the dataset:\")\n", + "display(df.head())\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "print(\"\\nData info:\")\n", + "print(df.info())\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "print(\"\\nStatistical summary for numeric columns:\")\n", + "display(df.describe())" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "plt.figure(figsize=(10, 5))\n", + "plt.hist(df['Delivery_Time'].dropna(), bins=50, edgecolor='black')\n", + "plt.title('Price Distribution')\n", + "plt.xlabel('Delivery_Time')\n", + "plt.ylabel('Frequency')\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "df_model = df.copy()\n", + "df_model = df_model.drop(columns=[\"Order_ID\"])" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "print(\"Missing values per column before handling:\")\n", + "print(df_model.isna().sum())\n", + "\n", + "df_model = df_model.dropna(subset=[\"Delivery_Time\"])\n", + "print(\"Shape after dropping rows with missing target:\", df_model.shape)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "print(\"Shape before dropping duplicates:\", df_model.shape)\n", + "df_model = df_model.drop_duplicates()\n", + "print(\"Shape after dropping duplicates:\", df_model.shape)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "\n", + "from sklearn.impute import SimpleImputer\n", + "\n", + "numeric_features = [\"Distance_km\", \"Preparation_Time_min\", \"Courier_Experience_yrs\"]\n", + "categorical_features = [\"Weather\", \"Traffic_Level\", \"Time_of_Day\", \"Vehicle_Type\"]\n", + "\n", + "numeric_transformer = Pipeline(steps=[\n", + " (\"imputer\", SimpleImputer(strategy=\"median\"))\n", + "])\n", + "\n", + "categorical_transformer = Pipeline(steps=[\n", + " (\"imputer\", SimpleImputer(strategy=\"most_frequent\")),\n", + " (\"onehot\", OneHotEncoder(handle_unknown=\"ignore\"))\n", + "])\n", + "\n", + "preprocessor = ColumnTransformer(\n", + " transformers=[\n", + " (\"num\", numeric_transformer, numeric_features),\n", + " (\"cat\", categorical_transformer, categorical_features)\n", + " ]\n", + ")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "\n", + "rf_model = RandomForestRegressor(random_state=42)\n", + "\n", + "pipeline = Pipeline(steps=[\n", + " (\"preprocessor\", preprocessor),\n", + " (\"scaler\", StandardScaler(with_mean=False)),\n", + " (\"model\", rf_model)\n", + "])\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "\n", + "y = df_model[\"Delivery_Time\"]\n", + "print(\"Target description (Delivery_Time):\")\n", + "print(y.describe())\n", + "print(\"Target imbalance check: not applicable for continuous regression target.\")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "\n", + "# Split the dataset into features (X) and target (y)\n", + "X = df_model.drop(columns=[\"Delivery_Time\"])\n", + "print(\"Final feature columns:\", X.columns.tolist())\n", + "print(\"X shape:\", X.shape)\n", + "print(\"y shape:\", y.shape)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "\n", + "kf = KFold(n_splits=5, shuffle=True, random_state=42)\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "\n", + "mae_scores = []\n", + "fold_index = 1\n", + "\n", + "for train_idx, test_idx in kf.split(X):\n", + " print(f\"Starting fold {fold_index}\")\n", + " X_train, X_test = X.iloc[train_idx], X.iloc[test_idx]\n", + " y_train, y_test = y.iloc[train_idx], y.iloc[test_idx]\n", + "\n", + " pipeline.fit(X_train, y_train)\n", + " y_pred = pipeline.predict(X_test)\n", + "\n", + " mae = mean_absolute_error(y_test, y_pred)\n", + " mae_scores.append(mae)\n", + " print(f\"Fold {fold_index} MAE: {mae:.4f}\")\n", + " fold_index += 1\n", + "\n", + "print(\"MAE scores for each fold:\", mae_scores)\n", + "print(f\"Average MAE across folds: {np.mean(mae_scores):.4f}\")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Plot feature importance from your trained model\n", + "rf_full = RandomForestRegressor(\n", + " n_estimators=300,\n", + " max_depth=None,\n", + " random_state=42,\n", + " n_jobs=-1\n", + ")\n", + "\n", + "pipeline_full = Pipeline(steps=[\n", + " (\"preprocessor\", preprocessor),\n", + " (\"model\", rf_full)\n", + "])\n", + "\n", + "print(\"Fitting RandomForest model on full data for feature importance...\")\n", + "pipeline_full.fit(X, y)\n", + "\n", + "preproc_fitted = pipeline_full.named_steps[\"preprocessor\"]\n", + "feature_names = preproc_fitted.get_feature_names_out()\n", + "importances = pipeline_full.named_steps[\"model\"].feature_importances_\n", + "\n", + "sorted_idx = np.argsort(importances)[::-1]\n", + "top_n = 20 if len(feature_names) > 20 else len(feature_names)\n", + "top_idx = sorted_idx[:top_n]\n", + "\n", + "plt.figure(figsize=(10, 8))\n", + "plt.barh(range(top_n), importances[top_idx][::-1])\n", + "plt.yticks(range(top_n), [feature_names[i] for i in top_idx][::-1])\n", + "plt.xlabel(\"Feature importance\")\n", + "plt.title(\"Top feature importances (RandomForestRegressor)\")\n", + "plt.tight_layout()\n", + "plt.show()\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "\n", + "y_pred_full = pipeline_full.predict(X)\n", + "\n", + "plt.figure(figsize=(8, 5))\n", + "plt.hist(y_pred_full, bins=30, edgecolor=\"black\")\n", + "plt.xlabel(\"Predicted delivery time\")\n", + "plt.ylabel(\"Frequency\")\n", + "plt.title(\"Histogram of predicted delivery time\")\n", + "plt.grid(True)\n", + "plt.show()\n", + "\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "!pip install catboost" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "from catboost import CatBoostRegressor\n", + "\n", + "kf = KFold(n_splits=5, shuffle=True, random_state=42)\n", + "mae_scores_ensemble = []\n", + "fold_index = 1\n", + "\n", + "for train_idx, val_idx in kf.split(X):\n", + " print(f\"Starting fold {fold_index}\")\n", + " X_train, X_val = X.iloc[train_idx], X.iloc[val_idx]\n", + " y_train, y_val = y.iloc[train_idx], y.iloc[val_idx]\n", + "\n", + " # Preprocess + scale inside each fold\n", + " X_train_proc = preprocessor.fit_transform(X_train)\n", + " X_val_proc = preprocessor.transform(X_val)\n", + "\n", + " scaler = StandardScaler(with_mean=False)\n", + " X_train_scaled = scaler.fit_transform(X_train_proc)\n", + " X_val_scaled = scaler.transform(X_val_proc)\n", + "\n", + " rf_model = RandomForestRegressor(\n", + " n_estimators=300,\n", + " max_depth=None,\n", + " random_state=42,\n", + " n_jobs=-1\n", + " )\n", + "\n", + " cb_model = CatBoostRegressor(\n", + " depth=6,\n", + " learning_rate=0.1,\n", + " n_estimators=300,\n", + " loss_function=\"RMSE\",\n", + " verbose=False,\n", + " random_state=42\n", + " )\n", + "\n", + " rf_model.fit(X_train_scaled, y_train)\n", + " cb_model.fit(X_train_scaled, y_train)\n", + "\n", + " preds_rf = rf_model.predict(X_val_scaled)\n", + " preds_cb = cb_model.predict(X_val_scaled)\n", + " preds_avg = (preds_rf + preds_cb) / 2.0\n", + "\n", + " mae_fold = mean_absolute_error(y_val, preds_avg)\n", + " mae_scores_ensemble.append(mae_fold)\n", + " print(f\"Fold {fold_index} MAE (ensemble): {mae_fold:.4f}\")\n", + " fold_index += 1\n", + "\n", + "print(\"MAE scores for each fold (ensemble):\", mae_scores_ensemble)\n", + "print(f\"Average MAE across folds (ensemble): {np.mean(mae_scores_ensemble):.4f}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/436/Q2.ipynb b/submissions_extracted/436/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..c05844f9cf5884d2e6b13acfb5cce143568b919b --- /dev/null +++ b/submissions_extracted/436/Q2.ipynb @@ -0,0 +1,330 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q2-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import os\n", + "import pandas as pd\n", + "import numpy as np\n", + "from PIL import Image\n", + "from sklearn.model_selection import train_test_split\n", + "\n", + "# Load Labels\n", + "labels_df = pd.read_csv(os.path.join(path, \"labels.csv\"))\n", + "img_dir = os.path.join(path, \"images\")\n", + "\n", + "images = []\n", + "ages = []\n", + "\n", + "# Load Images and Resize\n", + "print(\"Loading images...\")\n", + "for index, row in labels_df.iterrows():\n", + " img_name = row.iloc[0]\n", + " age = row.iloc[1]\n", + " img_path = os.path.join(img_dir, img_name)\n", + "\n", + " if os.path.exists(img_path):\n", + " img = Image.open(img_path).convert('RGB')\n", + " img_array = np.array(img) / 255.0 # Normalize pixel values to [0, 1]\n", + " images.append(img_array)\n", + " ages.append(age)\n", + "\n", + "X = np.array(images)\n", + "y = np.array(ages)\n", + "\n", + "# Transpose image dimensions to match PyTorch format (N, C, H, W)\n", + "X = np.transpose(X, (0, 3, 1, 2))\n", + "\n", + "# Split Data\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n", + "\n", + "print(f\"X_train shape: {X_train.shape}\")\n", + "print(f\"X_test shape: {X_test.shape}\")\n", + "print(f\"y_train shape: {y_train.shape}\")\n", + "print(f\"y_test shape: {y_test.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Convert to Tensors: Convert the numpy arrays (X_train, X_test, y_train, y_test) into PyTorch tensors.\n", + "import torch\n", + "import torch.nn as nn\n", + "import torch.optim as optim\n", + "from torch.utils.data import TensorDataset, DataLoader\n", + "import matplotlib.pyplot as plt\n", + "\n", + "X_train_tensor = torch.tensor(X_train, dtype=torch.float32)\n", + "X_test_tensor = torch.tensor(X_test, dtype=torch.float32)\n", + "y_train_tensor = torch.tensor(y_train, dtype=torch.float32)\n", + "y_test_tensor = torch.tensor(y_test, dtype=torch.float32)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 2. Create TensorDataset objects\n", + "train_dataset = TensorDataset(X_train_tensor, y_train_tensor)\n", + "test_dataset = TensorDataset(X_test_tensor, y_test_tensor)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 3. Create DataLoaders\n", + "\n", + "train_loader = DataLoader(train_dataset, batch_size=32, shuffle=True)\n", + "test_loader = DataLoader(test_dataset, batch_size=32, shuffle=False)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 4. Print shape of one batch.\n", + "images_batch, ages_batch = next(iter(train_loader))\n", + "print(\"Train batch images shape:\", images_batch.shape)\n", + "print(\"Train batch ages shape:\", ages_batch.shape)\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 5. Display sample images\n", + "\n", + "images_batch_show = images_batch[:6]\n", + "ages_batch_show = ages_batch[:6]\n", + "\n", + "fig, axes = plt.subplots(2, 3, figsize=(10, 7))\n", + "axes = axes.flatten()\n", + "for i in range(len(images_batch_show)):\n", + " img = images_batch_show[i].permute(1, 2, 0).numpy()\n", + " axes[i].imshow(img)\n", + " axes[i].set_title(f\"Actual age: {ages_batch_show[i].item():.0f}\")\n", + " axes[i].axis(\"off\")\n", + "plt.tight_layout()\n", + "plt.show()\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your model class here:\n", + "class AgeRegressor(nn.Module):\n", + " def __init__(self):\n", + " super().__init__()\n", + " self.flatten = nn.Flatten()\n", + " self.fc1 = nn.Linear(3 * 36 * 36, 512)\n", + " self.fc2 = nn.Linear(512, 256)\n", + " self.fc3 = nn.Linear(256, 128)\n", + " self.fc4 = nn.Linear(128, 1)\n", + " self.relu = nn.ReLU()\n", + "\n", + " def forward(self, x):\n", + " x = self.flatten(x)\n", + " x = self.relu(self.fc1(x))\n", + " x = self.relu(self.fc2(x))\n", + " x = self.relu(self.fc3(x))\n", + " x = self.fc4(x)\n", + " return x\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your training loop here:\n", + "def train_one_epoch(model, loader, criterion, optimizer, device):\n", + " model.train()\n", + " running_loss = 0.0\n", + " total = 0\n", + " for images_batch, ages_batch in loader:\n", + " images_batch = images_batch.to(device)\n", + " ages_batch = ages_batch.to(device).float()\n", + " optimizer.zero_grad()\n", + " outputs = model(images_batch).squeeze(1)\n", + " loss = criterion(outputs, ages_batch)\n", + " loss.backward()\n", + " optimizer.step()\n", + " batch_size = images_batch.size(0)\n", + " running_loss += loss.item() * batch_size\n", + " total += batch_size\n", + " epoch_loss = running_loss / total\n", + " return epoch_loss\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your validation loop here:\n", + "def evaluate(model, loader, criterion, device):\n", + " model.eval()\n", + " running_loss = 0.0\n", + " total = 0\n", + " with torch.no_grad():\n", + " for images_batch, ages_batch in loader:\n", + " images_batch = images_batch.to(device)\n", + " ages_batch = ages_batch.to(device).float()\n", + " outputs = model(images_batch).squeeze(1)\n", + " loss = criterion(outputs, ages_batch)\n", + " batch_size = images_batch.size(0)\n", + " running_loss += loss.item() * batch_size\n", + " total += batch_size\n", + " epoch_loss = running_loss / total\n", + " return epoch_loss\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Define device, model, loss, optimizer:\n", + "\n", + "device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n", + "print(\"Device used for training:\", device)\n", + "\n", + "model = AgeRegressor().to(device)\n", + "criterion = nn.MSELoss()\n", + "optimizer = optim.Adam(model.parameters(), lr=1e-3)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Start training for 20 epochs:\n", + "num_epochs = 40\n", + "train_losses = []\n", + "val_losses = []\n", + "\n", + "print(\"Starting training...\")\n", + "for epoch in range(num_epochs):\n", + " train_loss = train_one_epoch(model, train_loader, criterion, optimizer, device)\n", + " val_loss = evaluate(model, test_loader, criterion, device)\n", + " train_losses.append(train_loss)\n", + " val_losses.append(val_loss)\n", + " print(f\"Epoch {epoch + 1}/{num_epochs} - Train Loss: {train_loss:.4f} - Val Loss: {val_loss:.4f}\")\n", + "print(\"Training finished.\")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "\n", + "# Plot the training and validation loss over epochs.\n", + "epochs_range = range(1, num_epochs + 1)\n", + "plt.figure(figsize=(8, 5))\n", + "plt.plot(epochs_range, train_losses, label=\"Train Loss\")\n", + "plt.plot(epochs_range, val_losses, label=\"Validation Loss\")\n", + "plt.xlabel(\"Epoch\")\n", + "plt.ylabel(\"Loss\")\n", + "plt.title(\"Training and Validation Loss over Epochs\")\n", + "plt.legend()\n", + "plt.grid(True)\n", + "plt.show()\n", + "\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "\n", + "model.eval()\n", + "images_batch, ages_batch = next(iter(test_loader))\n", + "images_batch_device = images_batch.to(device)\n", + "ages_batch_device = ages_batch.to(device)\n", + "\n", + "with torch.no_grad():\n", + " preds = model(images_batch_device).squeeze(1)\n", + "\n", + "images_batch = images_batch.cpu()\n", + "ages_batch = ages_batch.cpu()\n", + "preds = preds.cpu()\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2 (Bonus): Write your code here:\n", + "num_show = 6\n", + "fig, axes = plt.subplots(2, 3, figsize=(10, 7))\n", + "axes = axes.flatten()\n", + "for i in range(num_show):\n", + " img = images_batch[i].permute(1, 2, 0).numpy()\n", + " axes[i].imshow(img)\n", + " axes[i].set_title(f\"Actual: {ages_batch[i].item():.0f} - Predicted: {preds[i].item():.1f}\")\n", + " axes[i].axis(\"off\")\n", + "plt.tight_layout()\n", + "plt.show()\n" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/436/Q3.ipynb b/submissions_extracted/436/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..14b45d7711d109948583ffa25d3fa69ba69bdfeb --- /dev/null +++ b/submissions_extracted/436/Q3.ipynb @@ -0,0 +1,379 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import numpy as np\n", + "import pandas as pd\n", + "import matplotlib.pyplot as plt\n", + "import seaborn as sns\n", + "\n", + "from sklearn.model_selection import train_test_split, KFold, cross_val_score\n", + "from sklearn.preprocessing import StandardScaler, OneHotEncoder, LabelEncoder, PolynomialFeatures\n", + "from sklearn.compose import ColumnTransformer\n", + "from sklearn.pipeline import Pipeline\n", + "from sklearn.linear_model import LinearRegression\n", + "from sklearn.metrics import mean_absolute_error, mean_squared_error, r2_score\n", + "\n", + "from sklearn.ensemble import RandomForestRegressor\n", + "\n", + "import warnings\n", + "warnings.filterwarnings('ignore')\n", + "\n", + "plt.rcParams['figure.figsize'] = (8, 5)\n", + "plt.rcParams['axes.grid'] = True\n", + "\n", + "print(\"Done\")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "\n", + "\n", + "# Download latest version\n", + "\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q3-exam-data\")\n", + "\n", + "\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import os\n", + "import pandas as pd\n", + "\n", + "data_path = os.path.join(path, \"Q3_data.csv\")\n", + "print (data_path)\n", + "\n", + "df = pd.read_csv(data_path)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "print(\"First 5 rows of the dataset:\")\n", + "display(df.head())\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "print(\"\\nData info:\")\n", + "print(df.info())\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "print(\"\\nStatistical summary for numeric columns:\")\n", + "display(df.describe())" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "!pip install catboost" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "from catboost import CatBoostClassifier\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "import numpy as np\n", + "import matplotlib.pyplot as plt\n", + "\n", + "from sklearn.model_selection import StratifiedKFold\n", + "from sklearn.preprocessing import StandardScaler\n", + "from sklearn.impute import SimpleImputer\n", + "from sklearn.pipeline import Pipeline\n", + "from sklearn.metrics import f1_score\n", + "\n", + "df_model = df.copy()\n", + "\n", + "print(\"Missing values per column (first 10):\")\n", + "print(df_model.isna().sum().head(10))\n", + "print(\"Total missing values in dataset:\", df_model.isna().sum().sum())\n", + "\n", + "df_model = df_model.dropna(subset=[\"Target\"])\n", + "print(\"Shape after ensuring non-missing target:\", df_model.shape)\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "print(\"Shape before dropping duplicates:\", df_model.shape)\n", + "df_model = df_model.drop_duplicates()\n", + "print(\"Shape after dropping duplicates:\", df_model.shape)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "categorical_features = df_model.select_dtypes(include=[\"object\"]).columns.tolist()\n", + "print(\"Categorical features detected:\", categorical_features)\n", + "\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "X = df_model.drop(columns=[\"Target\"])\n", + "y = df_model[\"Target\"].astype(int)\n", + "\n", + "numeric_features = X.columns.tolist()\n", + "print(\"Number of numerical features:\", len(numeric_features))\n", + "\n", + "model_full = Pipeline(steps=[\n", + " (\"imputer\", SimpleImputer(strategy=\"median\")),\n", + " (\"scaler\", StandardScaler()),\n", + " (\"classifier\", CatBoostClassifier(\n", + " depth=6,\n", + " learning_rate=0.1,\n", + " n_estimators=300,\n", + " loss_function=\"Logloss\",\n", + " eval_metric=\"F1\",\n", + " verbose=False,\n", + " random_state=42\n", + " ))\n", + "])\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "class_counts = y.value_counts()\n", + "class_ratios = y.value_counts(normalize=True)\n", + "\n", + "print(\"Target class counts:\")\n", + "print(class_counts)\n", + "print(\"Target class ratios:\")\n", + "print(class_ratios)\n", + "\n", + "imbalance_ratio = class_ratios.max()\n", + "if imbalance_ratio > 0.6:\n", + " print(\"The target is imbalanced. F1-score will be used as the main evaluation metric.\")\n", + "else:\n", + " print(\"The target is relatively balanced. F1-score will still be used as the main evaluation metric.\")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "\n", + "print(\"Final X shape:\", X.shape)\n", + "print(\"Final y shape:\", y.shape)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:\n", + "skf = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)\n", + "\n", + "f1_scores_full = []\n", + "fold_index = 1\n", + "\n", + "\n", + "for train_idx, test_idx in skf.split(X, y):\n", + " print(f\"Starting fold {fold_index}\")\n", + " X_train, X_valid = X.iloc[train_idx], X.iloc[test_idx]\n", + " y_train, y_valid = y.iloc[train_idx], y.iloc[test_idx]\n", + "\n", + " model_full.fit(X_train, y_train)\n", + " y_pred = model_full.predict(X_valid)\n", + "\n", + " f1 = f1_score(y_valid, y_pred)\n", + " f1_scores_full.append(f1)\n", + " print(f\"Fold {fold_index} F1-score: {f1:.4f}\")\n", + " fold_index += 1\n", + "\n", + "avg_f1_full = np.mean(f1_scores_full)\n", + "print(\"F1-scores for each fold (full model):\", f1_scores_full)\n", + "print(f\"Average F1-score across folds (full model): {avg_f1_full:.4f}\")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "model_full.fit(X, y)\n", + "cat_model = model_full.named_steps[\"classifier\"]\n", + "feature_importances = cat_model.get_feature_importance()\n", + "feature_names = X.columns.tolist()\n", + "\n", + "sorted_idx = np.argsort(feature_importances)[::-1]\n", + "\n", + "plt.figure(figsize=(10, 8))\n", + "top_n = 20 if len(feature_names) > 20 else len(feature_names)\n", + "top_idx = sorted_idx[:top_n]\n", + "plt.barh(range(top_n), feature_importances[top_idx][::-1])\n", + "plt.yticks(range(top_n), [feature_names[i] for i in top_idx][::-1])\n", + "plt.xlabel(\"Feature importance\")\n", + "plt.title(\"Top feature importances (CatBoostClassifier)\")\n", + "plt.tight_layout()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "golden_index = sorted_idx[0]\n", + "golden_feature = feature_names[golden_index]\n", + "golden_importance = feature_importances[golden_index]\n", + "\n", + "print(\"Most important feature (golden feature):\", golden_feature)\n", + "print(\"Importance of golden feature:\", golden_importance)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "X_golden = df_model[[golden_feature]]\n", + "print(\"Shape of X with only golden feature:\", X_golden.shape)\n", + "\n", + "model_golden = Pipeline(steps=[\n", + " (\"imputer\", SimpleImputer(strategy=\"median\")),\n", + " (\"scaler\", StandardScaler()),\n", + " (\"classifier\", CatBoostClassifier(\n", + " depth=6,\n", + " learning_rate=0.1,\n", + " n_estimators=300,\n", + " loss_function=\"Logloss\",\n", + " eval_metric=\"F1\",\n", + " verbose=False,\n", + " random_state=42\n", + " ))\n", + "])\n", + "\n", + "f1_scores_golden = []\n", + "fold_index = 1\n", + "\n", + "for train_idx, test_idx in skf.split(X_golden, y):\n", + " print(f\"Starting fold (golden feature) {fold_index}\")\n", + " X_train_g, X_valid_g = X_golden.iloc[train_idx], X_golden.iloc[test_idx]\n", + " y_train_g, y_valid_g = y.iloc[train_idx], y.iloc[test_idx]\n", + "\n", + " model_golden.fit(X_train_g, y_train_g)\n", + " y_pred_g = model_golden.predict(X_valid_g)\n", + "\n", + " f1_g = f1_score(y_valid_g, y_pred_g)\n", + " f1_scores_golden.append(f1_g)\n", + " print(f\"Fold {fold_index} F1-score (golden feature): {f1_g:.4f}\")\n", + " fold_index += 1\n", + "\n", + "avg_f1_golden = np.mean(f1_scores_golden)\n", + "print(\"F1-scores for each fold (golden feature model):\", f1_scores_golden)\n", + "print(f\"Average F1-score across folds (golden feature model): {avg_f1_golden:.4f}\")\n", + "\n", + "print(f\"Full model average F1-score: {avg_f1_full:.4f}\")\n", + "print(f\"Golden feature model average F1-score: {avg_f1_golden:.4f}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/437/Q1.ipynb b/submissions_extracted/437/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..c0043f78eea7fc2946cab40c99f4bc52e9fcfc01 --- /dev/null +++ b/submissions_extracted/437/Q1.ipynb @@ -0,0 +1,351 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q1-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import pandas as pd\n", + "import numpy as np\n", + "import matplotlib.pyplot as plt\n", + "import seaborn as sns\n", + "import kagglehub\n", + "import os\n", + "from tqdm import tqdm\n", + "\n", + "#Task 1: Write your code here:\n", + "csv_path = os.path.join(path, \"Q1_data.csv\")\n", + "df = pd.read_csv(csv_path)\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "df.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "df.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "def target_distribution(df, target_column):\n", + " df[target_column].hist(bins=30, edgecolor='black')\n", + "\n", + " plt.title(f\"Target Distribution ({target_column})\")\n", + " plt.xlabel(target_column)\n", + " plt.ylabel(\"Frequency\")\n", + " plt.grid(False)\n", + "\n", + " plt.show()\n", + "\n", + "target_distribution(df, \"Delivery_Time\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "data = df.copy()\n", + "data = data.drop(columns=['Order_ID'])\n", + "data" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "data.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "\n", + "def fill_missing_values(df, target_col=None, num_strategy=\"mean\"):\n", + "\n", + " df = df.copy()\n", + "\n", + " # Numerical columns (except target)\n", + " numerical_cols = df.select_dtypes(include=[\"int64\", \"float64\"]).columns\n", + " if target_col in numerical_cols:\n", + " numerical_cols = numerical_cols.drop(target_col)\n", + "\n", + " # Categorical columns\n", + " categorical_cols = df.select_dtypes(include=[\"object\"]).columns\n", + "\n", + " # Fill numerical columns\n", + " for col in numerical_cols:\n", + " if df[col].isnull().sum() > 0:\n", + " if num_strategy == \"mean\":\n", + " df[col].fillna(df[col].mean(), inplace=True)\n", + " elif num_strategy == \"median\":\n", + " df[col].fillna(df[col].median(), inplace=True)\n", + "\n", + " # Fill categorical columns\n", + " for col in categorical_cols:\n", + " if df[col].isnull().sum() > 0:\n", + " df[col].fillna(df[col].mode()[0], inplace=True)\n", + "\n", + " # Drop rows where target is missing\n", + " if target_col is not None:\n", + " df = df.dropna(subset=[target_col])\n", + "\n", + " return df\n", + "data = fill_missing_values(data)\n", + "data.info()\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "data.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "def check_duplicates(df):\n", + " duplicates = df.duplicated().sum()\n", + " print(f\"Number of Duplicate Samples: {duplicates}\")\n", + " if duplicates > 0:\n", + " print(\"Dropping Duplicates...\")\n", + " df.drop_duplicates(inplace=True)\n", + " print(\"Duplicates Dropped.\")\n", + " else:\n", + " print(\"No Duplicate Samples Found.\")\n", + "\n", + "check_duplicates(df)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "categorical_cols = data.select_dtypes(include=[\"object\"]).columns\n", + "\n", + "from sklearn.preprocessing import LabelEncoder\n", + "\n", + "label_encoders = {}\n", + "for col in categorical_cols:\n", + " le = LabelEncoder()\n", + " data[col] = le.fit_transform(data[col])\n", + " label_encoders[col] = le\n", + "\n", + "data\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "from sklearn.preprocessing import StandardScaler\n", + "\n", + "features = data.columns.drop(\"Delivery_Time\")\n", + "\n", + "scaler = StandardScaler()\n", + "data[features] = scaler.fit_transform(data[features])" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 6: Write your code here:\n", + "# not needed cuz its linear reg" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "X = data.drop(\"Delivery_Time\", axis=1).astype(float)\n", + "y = data['Delivery_Time'].astype(float)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:\n", + "from sklearn.model_selection import KFold\n", + "n_splits = 5\n", + "\n", + "kf = KFold(n_splits=n_splits, shuffle=True, random_state=42)\n", + "lr_mae = []\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "from sklearn.ensemble import RandomForestRegressor\n", + "from sklearn.metrics import mean_absolute_error" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "n_estimators = 200\n", + "max_depth = None\n", + "model = RandomForestRegressor(n_estimators=n_estimators, max_depth=max_depth)\n", + "\n", + "for fold_idx, (train_index, test_index) in enumerate(kf.split(X)):\n", + " print(f\"\\nFold {fold_idx + 1}/{n_splits}\")\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", + " # Train\n", + " model.fit(X_train, y_train)\n", + "\n", + " # Predict\n", + " y_pred = model.predict(X_test)\n", + "\n", + " # Metrics\n", + " mae = mean_absolute_error(y_test, y_pred)\n", + " print(f\" MAE: {mae:.4f}\")\n", + "\n", + " # Store results\n", + " lr_mae.append(mae)\n", + "\n", + "y_pred" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "def plot_trained_feature_importance(model, X, model_type=\"Randomforest\"):\n", + " coef_ = model.feature_importances_\n", + "\n", + " plt.figure(figsize=(10,5))\n", + " plt.bar(X.columns, coef_)\n", + " plt.xticks(rotation=45)\n", + " plt.title(f\"Feature Importance after Training ({model_type})\")\n", + " plt.show()\n", + "\n", + "plot_trained_feature_importance(model, X)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "plt.figure(figsize=(10,5))\n", + "plt.hist(y_pred, edgecolor='black')\n", + "plt.xticks(rotation=45)\n", + "plt.show()\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/437/Q2.ipynb b/submissions_extracted/437/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..8508903dcd7854bf752032aa945fd0aeb499c0aa --- /dev/null +++ b/submissions_extracted/437/Q2.ipynb @@ -0,0 +1,391 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q2-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import os\n", + "import pandas as pd\n", + "import numpy as np\n", + "from PIL import Image\n", + "from sklearn.model_selection import train_test_split\n", + "\n", + "# Load Labels\n", + "labels_df = pd.read_csv(os.path.join(path, \"labels.csv\"))\n", + "img_dir = os.path.join(path, \"images\")\n", + "\n", + "images = []\n", + "ages = []\n", + "\n", + "# Load Images and Resize\n", + "print(\"Loading images...\")\n", + "for index, row in labels_df.iterrows():\n", + " img_name = row.iloc[0]\n", + " age = row.iloc[1]\n", + " img_path = os.path.join(img_dir, img_name)\n", + "\n", + " if os.path.exists(img_path):\n", + " img = Image.open(img_path).convert('RGB')\n", + " img_array = np.array(img) / 255.0 # Normalize pixel values to [0, 1]\n", + " images.append(img_array)\n", + " ages.append(age)\n", + "\n", + "X = np.array(images)\n", + "y = np.array(ages)\n", + "\n", + "# Transpose image dimensions to match PyTorch format (N, C, H, W)\n", + "X = np.transpose(X, (0, 3, 1, 2))\n", + "\n", + "# Split Data\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n", + "\n", + "print(f\"X_train shape: {X_train.shape}\")\n", + "print(f\"X_test shape: {X_test.shape}\")\n", + "print(f\"y_train shape: {y_train.shape}\")\n", + "print(f\"y_test shape: {y_test.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "import pandas as pd\n", + "import torch\n", + "import torch.nn as nn\n", + "from torch.optim import AdamW\n", + "import matplotlib.pyplot as plt\n", + "import torch.nn.functional as F\n", + "from torch.utils.data import DataLoader, TensorDataset\n", + "from sklearn.model_selection import train_test_split\n", + "from sklearn.preprocessing import StandardScaler, LabelEncoder" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 1. Convert Numpy arrays to PyTorch Tensors\n", + "X_train = torch.tensor(X_train , dtype=torch.float32)\n", + "X_test = torch.tensor(X_test , dtype=torch.float32)\n", + "y_train = torch.tensor(y_train , dtype=torch.float32)\n", + "y_test = torch.tensor(y_test , dtype=torch.float32)\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 2. Create TensorDataset objects\n", + "train_dataset = TensorDataset(X_train, y_train)\n", + "test_dataset = TensorDataset(X_test, y_test)\n", + "\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 3. Create DataLoaders\n", + "train_loader = DataLoader(train_dataset, batch_size=32, shuffle=True)\n", + "test_loader = DataLoader(test_dataset, batch_size=32, shuffle=False)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 4. Print shape of one batch\n", + "X_batch, y_batch = next(iter(train_loader))\n", + "print(f\"Training batch input shape: {X_batch.shape}\")\n", + "print(f\"Training batch labels shape: {y_batch.shape}\")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 5. Display sample images\n", + "images, labels = next(iter(train_loader))\n", + "\n", + "plt.figure(figsize=(8, 4))\n", + "plt.subplot(2, 3, 1)\n", + "plt.imshow(images[0].permute(1, 2, 0))\n", + "plt.title(f\"Label: {labels[0].item()}\")\n", + "plt.axis('off')\n", + "\n", + "plt.tight_layout()\n", + "plt.show()\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your model class here:\n", + "class NN4Layer(nn.Module):\n", + "\n", + " def __init__(self, input_dim, hidden_dim,output_dim):\n", + " super(NN4Layer, self).__init__()\n", + "\n", + " # First linear layer: input features -> hidden layer\n", + " self.layer1 = nn.Linear(input_dim, hidden_dim)\n", + "\n", + " # Second linear layer: hidden layer -> hidden layer\n", + " self.layer2 = nn.Linear(hidden_dim, hidden_dim)\n", + "\n", + " # Third linear layer: hidden layer -> hidden layer\n", + " self.layer3 = nn.Linear(hidden_dim, hidden_dim)\n", + "\n", + " # Output layer: hidden layer -> number of classes (logits)\n", + " self.layer4 = nn.Linear(hidden_dim, output_dim)\n", + "\n", + " # ReLU activation for non-linearity\n", + " self.relu = nn.ReLU()\n", + "\n", + " def forward(self, x):\n", + " # First hidden layer\n", + " a1 = self.relu(self.layer1(x))\n", + "\n", + " # Second hidden layer\n", + " a2 = self.relu(self.layer2(a1))\n", + "\n", + " # Third hidden layer\n", + " a3 = self.relu(self.layer3(a2))\n", + "\n", + " # Output layer\n", + " output = self.layer4(a3)\n", + "\n", + " return output" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your training loop here:\n", + "def train_one_epoch(model, optimizer, criterion, train_loader, device):\n", + " # Set the model to training mode\n", + " model.train()\n", + "\n", + " running_loss = 0.0\n", + "\n", + " for X_batch, y_batch in train_loader:\n", + " # Move batch to the selected device\n", + " X_batch = X_batch.to(device) # shape: (batch_size, num_features)\n", + " y_batch = y_batch.to(device) # shape: (batch_size,)\n", + "\n", + " # Forward pass (outputs are logits)\n", + " outputs = model(X_batch) # shape: (batch_size, num_classes)\n", + " loss = criterion(outputs, y_batch)\n", + "\n", + " # Backward pass & optimization\n", + " optimizer.zero_grad() # Clear previous gradients\n", + " loss.backward() # Compute gradients\n", + " optimizer.step() # Update model parameters\n", + "\n", + " running_loss += loss.item()\n", + "\n", + " # Average loss over all batches\n", + " avg_loss = running_loss / len(train_loader)\n", + "\n", + " return avg_loss" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your validation loop here:\n", + "def validate(model, criterion, test_loader, device):\n", + " # Set the model to evaluation mode\n", + " model.eval()\n", + "\n", + " running_loss = 0.0\n", + " correct = 0\n", + " total = 0\n", + "\n", + " with torch.no_grad():\n", + " for X_batch, y_batch in test_loader:\n", + " # Move data to device\n", + " X_batch = X_batch.to(device) # shape: (batch_size, num_features)\n", + " y_batch = y_batch.to(device) # shape: (batch_size,)\n", + "\n", + " # Forward pass\n", + " outputs = model(X_batch) # shape: (batch_size, num_classes)\n", + " loss = criterion(outputs, y_batch)\n", + " running_loss += loss.item()\n", + "\n", + " # Apply Softmax to get probabilities\n", + " probabilities = F.softmax(outputs, dim=1)\n", + "\n", + " # Pick the classes with highest probabilities\n", + " predicted = torch.argmax(probabilities, dim=1)\n", + "\n", + " # Accuracy calculation\n", + " correct += (predicted == y_batch).sum().item()\n", + " total += y_batch.size(0)\n", + "\n", + " avg_loss = running_loss / len(test_loader)\n", + " accuracy = correct / total\n", + "\n", + " return avg_loss, accuracy" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Define device, model, loss, optimizer:\n", + "device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n", + "\n", + "# Model parameters\n", + "input_dim =3*36*36\n", + "hidden_dim = 3456\n", + "output_dim = 10 # i though it was reg prob in the start but one ta said that its classifcation\n", + "\n", + "# Instantiate model\n", + "model = NN4Layer(input_dim, hidden_dim, output_dim).to(device)\n", + "\n", + "# Print the model architecture\n", + "print(\"Model Architecture:\\n\")\n", + "print(model)\n", + "\n", + "# Calculate the total number of trainable parameters\n", + "total_params = sum(p.numel() for p in model.parameters() if p.requires_grad)\n", + "print(f\"\\nTotal trainable parameters: {total_params}\")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Start training for 20 epochs:\n", + "num_epochs = 20\n", + "learning_rate = 0.001\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "criterion = nn.MSELoss()\n", + "# Define optimizer\n", + "optimizer = AdamW(model.parameters(), learning_rate)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Run Training\n", + "train_losses = []\n", + "val_losses = []\n", + "\n", + "print('Starting Training...')\n", + "for epoch in range(num_epochs):\n", + " # Train one epoch\n", + " train_loss = train_one_epoch(model, optimizer, criterion, train_loader, device)\n", + "\n", + " # Validate\n", + " val_loss = validate(model, criterion, test_loader, device)\n", + "\n", + " train_losses.append(train_loss)\n", + " val_losses.append(val_loss)\n", + "\n", + " if (epoch + 1) % 5 == 0:\n", + " print(\n", + " f'Epoch [{epoch+1}/{num_epochs}], '\n", + " f'Train Loss: {train_loss:.4f}, '\n", + " f'Val Loss: {val_loss:.4f}'\n", + " )\n", + "\n", + "print('Training Complete!')" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "plt.figure(figsize=(7, 5))\n", + "\n", + "plt.plot(train_losses, label='Train Loss')\n", + "plt.plot(val_losses, label='Validation Loss')\n", + "plt.title('Loss over Epochs')\n", + "plt.xlabel('Epoch')\n", + "plt.ylabel('Loss')\n", + "plt.legend()\n", + "\n", + "plt.tight_layout()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2 (Bonus): Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/437/Q3.ipynb b/submissions_extracted/437/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..5238dae557c53909d0806c1c23150e2492b5c209 --- /dev/null +++ b/submissions_extracted/437/Q3.ipynb @@ -0,0 +1,334 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "\n", + "\n", + "# Download latest version\n", + "\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q3-exam-data\")\n", + "\n", + "\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "import pandas as pd\n", + "import numpy as np\n", + "import matplotlib.pyplot as plt\n", + "import seaborn as sns\n", + "import kagglehub\n", + "import os\n", + "\n", + "csv_path = os.path.join(path, \"Q3_data.csv\")\n", + "df1 = pd.read_csv(csv_path)\n", + "df = df1.copy()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "df.head(25)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "df.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "df.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "def check_missing_values(df):\n", + " missing_values = df.isnull().sum()\n", + " print(\"Missing Values per Column:\")\n", + " print(missing_values[missing_values > 0])\n", + " if missing_values.any():\n", + " print(\"\\nHandle Missing Values as needed.\")\n", + " else:\n", + " print(\"\\nNo Missing Values Found.\")\n", + "\n", + "check_missing_values(df)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "def fill_missing_values(df, target_col=None, num_strategy=\"mean\"):\n", + " df = df.copy()\n", + "\n", + " # Numerical columns (except target)\n", + " numerical_cols = df.select_dtypes(include=[\"int64\", \"float64\"]).columns\n", + " if target_col in numerical_cols:\n", + " numerical_cols = numerical_cols.drop(target_col)\n", + "\n", + " # Categorical columns\n", + " categorical_cols = df.select_dtypes(include=[\"object\"]).columns\n", + "\n", + " # Fill numerical columns\n", + " for col in numerical_cols:\n", + " if df[col].isnull().sum() > 0:\n", + " if num_strategy == \"mean\":\n", + " df[col].fillna(df[col].mean(), inplace=True)\n", + " elif num_strategy == \"median\":\n", + " df[col].fillna(df[col].median(), inplace=True)\n", + "\n", + " # Fill categorical columns\n", + " for col in categorical_cols:\n", + " if df[col].isnull().sum() > 0:\n", + " df[col].fillna(df[col].mode()[0], inplace=True)\n", + "\n", + " # Drop rows where target is missing\n", + " if target_col is not None:\n", + " df = df.dropna(subset=[target_col])\n", + "\n", + " return df\n", + " df = fill_missing_values(df)\n", + " df" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "def check_duplicates(df):\n", + " duplicates = df.duplicated().sum()\n", + " print(f\"Number of Duplicate Samples: {duplicates}\")\n", + " if duplicates > 0:\n", + " print(\"Dropping Duplicates...\")\n", + " df.drop_duplicates(inplace=True)\n", + " print(\"Duplicates Dropped.\")\n", + " else:\n", + " print(\"No Duplicate Samples Found.\")\n", + "\n", + "check_duplicates(df)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "categorical_cols = df.select_dtypes(include=[\"object\"]).columns\n", + "\n", + "print(\"Categorical Columns:\", list(categorical_cols))" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "from sklearn.preprocessing import StandardScaler\n", + "\n", + "numerical_cols = df.select_dtypes(include=[\"int64\", \"float64\"]).columns.drop(\"Target\")\n", + "scaler = StandardScaler()\n", + "df[numerical_cols] = scaler.fit_transform(df[numerical_cols])\n", + "df.head()\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "def check_target_imbalance(df, target_column):\n", + " print(\"Target Distribution:\")\n", + " print(df[target_column].value_counts(normalize=True))\n", + " sns.countplot(x=df[target_column])\n", + " plt.title(\"Target Distribution\")\n", + " plt.show()\n", + "\n", + "check_target_imbalance(df, \"Target\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "X = df.drop(\"Target\", axis=1).astype(float)\n", + "y = df['Target'].astype(float)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:\n", + "from sklearn.model_selection import StratifiedKFold\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "from IPython.display import clear_output\n", + "\n", + "%pip install kagglehub catboost xgboost tqdm -q\n", + "\n", + "clear_output()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "from catboost import CatBoostClassifier\n", + "model= CatBoostClassifier(verbose=0,n_estimators=320,max_depth=4)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "n_splits = 5 # K\n", + "\n", + "# Stratified 5-Fold Cross-Validation, shuffled\n", + "skf = StratifiedKFold(n_splits=n_splits, shuffle=True, random_state=42)\n", + "\n", + "for fold_idx, (train_index, test_index) in enumerate(skf.split(X, y)):\n", + " print(f\"\\nFold {fold_idx + 1}/{n_splits}\")\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", + " # Train\n", + " model.fit(X_train, y_train)\n", + "\n", + " # Predict\n", + " y_pred = model.predict(X_test)\n", + "\n", + " # 3. Save metrics for that model in this fold\n", + " accuracy = accuracy_score(y_test, y_pred)\n", + " f1 = f1_score(y_test, y_pred, zero_division=0)\n", + " print(f\" f1: {f1:.4f}\")\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "def plot_trained_feature_importance(model, X):\n", + " coef_ = model.feature_importances_\n", + "\n", + " plt.figure(figsize=(10,5))\n", + " plt.bar(X.columns, coef_)\n", + " plt.xticks(rotation=45)\n", + " plt.title(f\"Feature Importance after Training )\")\n", + " plt.show()\n", + "\n", + "plot_trained_feature_importance(model, X)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "#first feture\n", + "print(\"the most important feature is P_2\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/438/Q1.ipynb b/submissions_extracted/438/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..a5d49a6c33c233352e6048ee85eedd9bfe36be06 --- /dev/null +++ b/submissions_extracted/438/Q1.ipynb @@ -0,0 +1,363 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q1-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import os\n", + "os.listdir(path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "import pandas as pd\n", + "q1_path = os.path.join(path, 'Q1_data.csv')# نباها تدمج الباث تخليه باث واحد\n", + "df = pd.read_csv(q1_path) # قرينا الداتا" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "df.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "df.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "import matplotlib.pyplot as plt\n", + "plt.figure(figsize=(10, 5))\n", + "plt.hist(df['Delivery_Time'].dropna(), bins=50, edgecolor='black')\n", + "plt.title('delivery_time Distribution')\n", + "plt.xlabel('delivery_time')\n", + "plt.ylabel('Frequency')\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "df = df.drop('Order_ID', axis=1)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "missing_values = df.isnull().sum()\n", + "print(\"Columns with missing values:\")\n", + "print(missing_values[missing_values > 0])" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "#df_clean['type2'] = df_clean['type2'].fillna('none')\n", + "df[\"Weather\"]=df[\"Weather\"].fillna('none')\n", + "df[\"Traffic_Level\"]=df[\"Traffic_Level\"].fillna('none')\n", + "df[\"Time_of_Day \"]=df[\"Time_of_Day\"].fillna('none')\n", + "df[\"Courier_Experience_yrs\"] = df[\"Courier_Experience_yrs\"].fillna(df[\"Courier_Experience_yrs\"].mean())\n", + "df[\"Delivery_Time\"] = df[\"Delivery_Time\"].fillna(df[\"Delivery_Time\"].mean())\n", + "# Fill missing values with mean for each column\n", + "#df = df.fillna(df.mean())\n", + "\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "missing_values = df.isnull().sum()\n", + "print(\"Columns with missing values:\")\n", + "print(missing_values[missing_values > 0])" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "def check_duplicates(df):\n", + " duplicates = df.duplicated().sum()\n", + " print(f\"Number of Duplicate Samples: {duplicates}\")\n", + " if duplicates > 0:\n", + " print(\"Dropping Duplicates...\")\n", + " df.drop_duplicates(inplace=True)\n", + " print(\"Duplicates Dropped.\")\n", + " else:\n", + " print(\"No Duplicate Samples Found.\")\n", + "\n", + "check_duplicates(df)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "# Encode categorical columns - converts text to integers\n", + "'''\n", + "2 Weather 1608 non-null object\n", + " 3 Traffic_Level 1612 non-null object\n", + " 4 Time_of_Day 1613 non-null object\n", + " 5 Vehicle_Type 1663 non-null object\n", + "\n", + "categorical_cols = [' Weather', 'Traffic_Level', 'Time_of_Day', 'Vehicle_Type']\n", + "for col in categorical_cols:\n", + " le = LabelEncoder()\n", + " df_clean[col] = le.fit_transform(df_clean[col].astype(str))\n", + "\n", + "df_clean.head()\n", + "'''\n", + "from sklearn.preprocessing import LabelEncoder\n", + "\n", + "categorical_cols = df.select_dtypes(include=[\"object\"]).columns\n", + "for col in categorical_cols:\n", + " print(f\"Encoding column: {col}\")\n", + " le = LabelEncoder()\n", + " df[col] = le.fit_transform(df[col])\n", + "df\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "from sklearn.preprocessing import StandardScaler\n", + "X = df.drop(\"Delivery_Time\", axis=1)\n", + "y = df[\"Delivery_Time\"]\n", + "scaler = StandardScaler()\n", + "X_scaled = scaler.fit_transform(X)\n", + "X_scaled = pd.DataFrame(X_scaled, columns=X.columns)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 6: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "X = X_scaled\n", + "y = y" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:\n", + "from sklearn.model_selection import KFold\n", + "from sklearn.ensemble import RandomForestRegressor\n", + "from sklearn.metrics import mean_absolute_error\n", + "import numpy as np\n", + "\n", + "kf = KFold(n_splits=5, shuffle=True, random_state=42)\n", + "mae_scores = []\n", + "\n", + "for train_index, val_index in kf.split(X):\n", + " X_train, X_val = X.iloc[train_index], X.iloc[val_index]\n", + " y_train, y_val = y.iloc[train_index], y.iloc[val_index]\n", + "model = RandomForestRegressor(random_state=42)\n", + "model.fit(X_train, y_train)\n", + "\n", + "y_pred = model.predict(X_val)\n", + "mae = mean_absolute_error(y_val, y_pred)\n", + "mae_scores.append(mae)\n", + "print(\"Average MAE across folds:\", np.mean(mae_scores))\n", + "\n", + "\n", + "\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "feature_importance = pd.Series( model.feature_importances_, index=X.columns ).sort_values(ascending=False)\n", + "plt.figure()\n", + "feature_importance.plot(kind=\"bar\")\n", + "plt.xlabel(\"Features\")\n", + "plt.ylabel(\"Importance\")\n", + "plt.title(\"Feature Importance - Random Forest\")\n", + "plt.show()\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "def check_target_distribution(df, target_column):\n", + " df[target_column].hist(bins=30, edgecolor='black')\n", + "\n", + " plt.title(f\"Target Distribution ({target_column})\")\n", + " plt.xlabel(target_column)\n", + " plt.ylabel(\"Frequency\")\n", + " plt.grid(False)\n", + "\n", + " plt.show()\n", + "\n", + "check_target_distribution(df, \"Delivery_Time\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "pip install catboost" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "\n", + "import numpy as np\n", + "from sklearn.model_selection import KFold\n", + "from sklearn.metrics import mean_absolute_error\n", + "from sklearn.ensemble import RandomForestRegressor\n", + "from catboost import CatBoostRegressor\n", + "\n", + "kf = KFold(n_splits=5, shuffle=True, random_state=42)\n", + "mae_scores = []\n", + "\n", + "for train_idx, val_idx in kf.split(X):\n", + " X_train, X_val = X.iloc[train_idx], X.iloc[val_idx]\n", + " y_train, y_val = y.iloc[train_idx], y.iloc[val_idx]\n", + "\n", + "# Model 1: Random Forest\n", + "rf = RandomForestRegressor(random_state=42)\n", + "rf.fit(X_train, y_train)\n", + "rf_preds = rf.predict(X_val)\n", + "\n", + "# Model 2: CatBoost\n", + "cb = CatBoostRegressor(verbose=0, random_state=42)\n", + "cb.fit(X_train, y_train)\n", + "cb_preds = cb.predict(X_val)\n", + "\n", + "\n", + "avg_preds = (rf_preds + cb_preds) / 2\n", + "\n", + "\n", + "mae = mean_absolute_error(y_val, avg_preds)\n", + "mae_scores.append(mae)\n", + "\n", + "\n", + "print(\"Ensemble Average MAE across folds:\", np.mean(mae_scores))\n" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/438/Q2.ipynb b/submissions_extracted/438/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..ec1d4dec8a8aa99c553a1ed1cedf08f260c1da26 --- /dev/null +++ b/submissions_extracted/438/Q2.ipynb @@ -0,0 +1,387 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q2-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import os\n", + "import pandas as pd\n", + "import numpy as np\n", + "from PIL import Image\n", + "from sklearn.model_selection import train_test_split\n", + "\n", + "# Load Labels\n", + "labels_df = pd.read_csv(os.path.join(path, \"labels.csv\"))\n", + "img_dir = os.path.join(path, \"images\")\n", + "\n", + "images = []\n", + "ages = []\n", + "\n", + "# Load Images and Resize\n", + "print(\"Loading images...\")\n", + "for index, row in labels_df.iterrows():\n", + " img_name = row.iloc[0]\n", + " age = row.iloc[1]\n", + " img_path = os.path.join(img_dir, img_name)\n", + "\n", + " if os.path.exists(img_path):\n", + " img = Image.open(img_path).convert('RGB')\n", + " img_array = np.array(img) / 255.0 # Normalize pixel values to [0, 1]\n", + " images.append(img_array)\n", + " ages.append(age)\n", + "\n", + "X = np.array(images)\n", + "y = np.array(ages)\n", + "\n", + "# Transpose image dimensions to match PyTorch format (N, C, H, W)\n", + "X = np.transpose(X, (0, 3, 1, 2))\n", + "\n", + "# Split Data\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n", + "\n", + "print(f\"X_train shape: {X_train.shape}\")\n", + "print(f\"X_test shape: {X_test.shape}\")\n", + "print(f\"y_train shape: {y_train.shape}\")\n", + "print(f\"y_test shape: {y_test.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 1. Convert Numpy arrays to PyTorch Tensors\n", + "import torch\n", + "X_train=torch.tensor(X_train)\n", + "X_test=torch.tensor(X_test)\n", + "y_train=torch.tensor(y_train)\n", + "y_test=torch.tensor(y_test)\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 2. Create TensorDataset objects\n", + "from torch.utils.data import TensorDataset\n", + "train_dataset = TensorDataset(X_train, y_train)\n", + "test_dataset = TensorDataset(X_test, y_test)\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 3. Create DataLoaders\n", + "from torch.utils.data import DataLoader\n", + "\n", + "train_loader = DataLoader(\n", + " train_dataset,\n", + " batch_size=32,\n", + " shuffle=True\n", + ")\n", + "\n", + "test_loader = DataLoader(\n", + " test_dataset,\n", + " batch_size=32,\n", + " shuffle=False\n", + ")\n", + "\n", + "\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 4. Print shape of one batch\n", + "images_batch, ages_batch = next(iter(train_loader))\n", + "print(\"Image batch shape:\", images_batch.shape) # (batch_size, C, H, W) print(\"Age batch shape:\", ages_batch.shape)\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 5. Display sample images\n", + "import matplotlib.pyplot as plt\n", + "\n", + "# Display first 5 images from the batch\n", + "plt.figure(figsize=(10, 4))\n", + "\n", + "for i in range(5):\n", + " plt.subplot(1, 5, i + 1)\n", + "\n", + " img = images_batch[i].permute(1, 2, 0)\n", + " plt.imshow(img)\n", + " plt.title(f\"Age: {ages_batch[i].item()}\")\n", + " plt.axis(\"off\")\n", + "\n", + "plt.show()\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your model class here:\n", + "import torch.nn as nn\n", + "class NN4Layer(nn.Module):\n", + "\n", + " def __init__(self, input_dim, hidden_dim, output_dim):\n", + " super(NN4Layer, self).__init__()\n", + "\n", + " # First linear layer: input features -> hidden layer\n", + " self.layer1 = nn.Linear(input_dim, hidden_dim)\n", + "\n", + " # Second linear layer: hidden layer -> hidden layer\n", + " self.layer2 = nn.Linear(hidden_dim, hidden_dim)\n", + "\n", + " # Third linear layer: hidden layer -> hidden layer\n", + " self.layer3 = nn.Linear(hidden_dim, hidden_dim)\n", + "\n", + " # Output layer: hidden layer -> number of classes (logits)\n", + " self.layer4 = nn.Linear(hidden_dim, output_dim)\n", + "\n", + " # ReLU activation for non-linearity\n", + " self.relu = nn.ReLU()\n", + "\n", + " # Defines how input data flows through the network\n", + " def forward(self, x):\n", + " # First hidden layer\n", + " a1 = self.relu(self.layer1(x))\n", + "\n", + " # Second hidden layer\n", + " a2 = self.relu(self.layer2(a1)) #preferred to use ReLu in headen layer rather than sigmoid\n", + "\n", + " # Third hidden layer\n", + " a3 = self.relu(self.layer3(a2))\n", + "\n", + " # Output layer (raw scores / logits) # we didn't use sofmax here cause we will use cross intropy loss function which already do it internally\n", + " output = self.layer4(a3) # we said we'll use softmax, where is it? ¯\\(ツ)/¯\n", + "\n", + " return output\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your training loop here:\n", + "\n", + "def train_one_epoch(model, optimizer, criterion, train_loader, device):\n", + " # Set the model to training mode\n", + " model.train()\n", + "\n", + " running_loss = 0.0\n", + "\n", + " for X_batch, y_batch in train_loader:\n", + " # Move batch to the selected device\n", + " X_batch = X_batch.to(device) # shape: (batch_size, num_features) # they mean the GPU by device\n", + " y_batch = y_batch.to(device).unsqueeze(1) # shape: (batch_size,)\n", + "\n", + " # Forward pass (outputs are logits)\n", + " outputs = model(X_batch) # shape: (batch_size, num_classes)\n", + " loss = criterion(outputs, y_batch)\n", + "\n", + " # Backward pass & optimization\n", + " optimizer.zero_grad() # Clear previous gradients\n", + " loss.backward() # Compute gradients\n", + " optimizer.step() # Update model parameters\n", + "\n", + " running_loss += loss.item()\n", + "\n", + " # Average loss over all batches\n", + " avg_loss = running_loss / len(train_loader)\n", + "\n", + " return avg_loss\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your validation loop here:\n", + "def validate(model, criterion, test_loader, device):\n", + " # Set the model to evaluation mode\n", + " model.eval()\n", + "\n", + " running_loss = 0.0\n", + " correct = 0\n", + " total = 0\n", + "\n", + " with torch.no_grad():\n", + " for X_batch, y_batch in test_loader:\n", + " # Move data to device\n", + " X_batch = X_batch.to(device) # shape: (batch_size, num_features)\n", + " y_batch = y_batch.to(device) # shape: (batch_size,)\n", + "\n", + " # Forward pass\n", + " outputs = model(X_batch) # shape: (batch_size, num_classes)\n", + " loss = criterion(outputs, y_batch) # criterion want the data to be raw that's why we didn't used softmax\n", + " running_loss += loss.item()\n", + "\n", + " # Apply Softmax to get probabilities\n", + " probabilities = F.softmax(outputs, dim=1)\n", + "\n", + " # Pick the classes with highest probabilities\n", + " predicted = torch.argmax(probabilities, dim=1) #argmax behave on column\n", + "\n", + " # Accuracy calculation\n", + " correct += (predicted == y_batch).sum().item()\n", + " total += y_batch.size(0)\n", + "\n", + " avg_loss = running_loss / len(test_loader)\n", + " accuracy = correct / total\n", + "\n", + " return avg_loss, accuracy" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Define device, model, loss, optimizer:\n", + "from torch.optim import Adam\n", + "learning_rate=0.001\n", + "device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n", + "input_dim = 3*36*36\n", + "hidden_dim = 14\n", + "output_dim = 1\n", + "model = NN4Layer(input_dim, hidden_dim, output_dim).to(device)\n", + "criterion = nn.CrossEntropyLoss()\n", + "optimizer = optimizer = Adam(model.parameters(), learning_rate)\n", + "\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Start training for 20 epochs:\n", + "num_epochs = 20\n", + "# Run Training\n", + "train_losses = []\n", + "val_losses = []\n", + "val_accuracies = []\n", + "\n", + "print('Starting Training...')\n", + "for epoch in range(num_epochs):\n", + " # Train one epoch\n", + " train_loss = train_one_epoch(model, optimizer, criterion, train_loader, device)\n", + "\n", + " # Validate\n", + " val_loss, val_accuracy = validate(model, criterion, test_loader, device)\n", + "\n", + " train_losses.append(train_loss)\n", + " val_losses.append(val_loss)\n", + " val_accuracies.append(val_accuracy)\n", + "\n", + " print(f'Epoch [{epoch+1}/{num_epochs}], Train Loss: {train_loss:.4f}, Val Loss: {val_loss:.4f}, Val Accuracy: {val_accuracy:.4f}')\n", + "\n", + "print('Training Complete!')\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "plt.figure(figsize=(7, 5))\n", + "\n", + "plt.plot(train_losses, label='Train Loss')\n", + "plt.plot(val_losses, label='Validation Loss')\n", + "plt.title('Loss over Epochs')\n", + "plt.xlabel('Epoch')\n", + "plt.ylabel('Loss')\n", + "plt.legend()\n", + "\n", + "plt.tight_layout()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2 (Bonus): Write your code here:\n", + "model.eval()\n", + "images_batch, ages_batch = next(iter(test_loader))\n", + "images_batch = images_batch.to(device)\n", + "with torch.no_grad():\n", + " preds = model(images_batch)\n", + " images_batch = images_batch.cpu()\n", + " preds = preds.cpu()\n", + " ages_batch = ages_batch.cpu()\n", + " plt.figure(figsize=(12, 4))\n", + "for i in range(5):\n", + " plt.subplot(1, 5, i + 1)\n", + " img = images_batch[i].permute(1, 2, 0)\n", + " plt.imshow(img)\n", + " plt.title(\n", + " f\"Pred: {preds[i].item():.1f}\\nActual: {ages_batch[i].item():.1f}\"\n", + " )\n", + " plt.axis(\"off\")\n", + "\n", + " plt.show()\n", + "\n" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/438/Q3.ipynb b/submissions_extracted/438/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..759d6208980fd23d9933d3e9e3cb683b175a644c --- /dev/null +++ b/submissions_extracted/438/Q3.ipynb @@ -0,0 +1,306 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "\n", + "\n", + "# Download latest version\n", + "\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q3-exam-data\")\n", + "\n", + "\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "import pandas as pd\n", + "import os\n", + "q3_path = os.path.join(path, 'Q3_data.csv')# نباها تدمج الباث تخليه باث واحد\n", + "df = pd.read_csv(q3_path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "df.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "df.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "missing_values = df.isnull().sum()\n", + "print(\"Columns with missing values:\")\n", + "print(missing_values[missing_values > 0])" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "df = df.fillna(df.mean())" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "def check_duplicates(df):\n", + " duplicates = df.duplicated().sum()\n", + " print(f\"Number of Duplicate Samples: {duplicates}\")\n", + " if duplicates > 0:\n", + " print(\"Dropping Duplicates...\")\n", + " df.drop_duplicates(inplace=True)\n", + " print(\"Duplicates Dropped.\")\n", + " else:\n", + " print(\"No Duplicate Samples Found.\")\n", + "\n", + "check_duplicates(df)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "from sklearn.preprocessing import LabelEncoder\n", + "\n", + "categorical_cols = df.select_dtypes(include=[\"object\"]).columns\n", + "for col in categorical_cols:\n", + " print(f\"Encoding column: {col}\")\n", + " le = LabelEncoder()\n", + " df[col] = le.fit_transform(df[col])\n", + "df" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "from sklearn.preprocessing import StandardScaler\n", + "\n", + "scaler = StandardScaler()\n", + "df_scaled = scaler.fit_transform(df)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "import matplotlib.pyplot as plt\n", + "def check_target_imbalance(df, target_column):\n", + " print(\"Target Distribution:\")\n", + "\n", + " df[target_column].hist() # Yeah you can just do this :)\n", + " plt.show()\n", + "\n", + "check_target_imbalance(df, \"Target\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "print(\"It is imbalanced\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "X = df.drop(\"Target\", axis=1)\n", + "y = df[\"Target\"]" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "pip install catboost" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "from catboost import CatBoostClassifier\n", + "from sklearn.model_selection import StratifiedKFold\n", + "from sklearn.metrics import f1_score\n", + "import numpy as np\n", + "kf = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)\n", + "\n", + "model = CatBoostClassifier(iterations=500, learning_rate=0.1, depth=6, verbose=0 )\n", + "f1_scores = []\n", + "for train_index, test_index in kf.split(X, y):\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", + "# Fit the model\n", + "model.fit(X_train, y_train)\n", + "\n", + "# Predict on test set\n", + "y_pred = model.predict(X_test)\n", + "\n", + "# Calculate F1-score\n", + "score = f1_score(y_test, y_pred)\n", + "f1_scores.append(score)\n", + "print(\"F1-score for each fold:\", f1_scores)\n", + "print(\"Average F1-score:\", np.mean(f1_scores))\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "import matplotlib.pyplot as plt\n", + "import pandas as pd\n", + "\n", + "# Get feature importance from the trained model\n", + "feature_importances = model.get_feature_importance()\n", + "feature_names = X.columns\n", + "\n", + "# Create a DataFrame for better visualization\n", + "importance_df = pd.DataFrame({\n", + " 'Feature': feature_names,\n", + " 'Importance': feature_importances\n", + "})\n", + "\n", + "# Sort by importance descending\n", + "importance_df = importance_df.sort_values(by='Importance', ascending=False)\n", + "plt.figure(figsize=(12,6))\n", + "plt.barh(importance_df['Feature'][:20][::-1], importance_df['Importance'][:20][::-1])\n", + "plt.xlabel(\"Importance\")\n", + "plt.ylabel(\"Feature\")\n", + "plt.title(\"Top 20 Feature Importances\")\n", + "plt.show()\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "\n", + "golden_feature = importance_df['Feature'].iloc[0]\n", + "print(\"The most important feature (Golden Feature) is:\", golden_feature)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:\n", + "X_golden = X[[golden_feature]]\n", + "model_single = CatBoostClassifier( iterations=500, learning_rate=0.1, depth=6, verbose=0 )\n", + "kf = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)\n", + "from sklearn.metrics import accuracy_score\n", + "import numpy as np\n", + "\n", + "# List to store accuracy scores\n", + "accuracy_scores = []\n", + "\n", + "# KFold loop\n", + "for train_index, test_index in kf.split(X_golden, y):\n", + " X_train, X_test = X_golden.iloc[train_index], X_golden.iloc[test_index]\n", + " y_train, y_test = y.iloc[train_index], y.iloc[test_index]\n", + "\n", + " # Train model\n", + " model_single.fit(X_train, y_train)\n", + "\n", + " # Predict\n", + " y_pred = model_single.predict(X_test)\n", + "\n", + " # Calculate accuracy\n", + " acc = accuracy_score(y_test, y_pred)\n", + " accuracy_scores.append(acc)\n", + "\n", + "# Print results\n", + "print(\"Accuracy for each fold using only the golden feature:\", accuracy_scores)\n", + "print(\"Average accuracy using only the golden feature:\", np.mean(accuracy_scores))\n", + "print(\"Average F1-score of full model:\", np.mean(f1_scores))\n", + "print(\"Average accuracy using only golden feature:\", np.mean(accuracy_scores))\n", + "\n", + "\n" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/439/Q1.ipynb b/submissions_extracted/439/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..149e2d868ae7bc8190abcead5cb5e301e7e977ba --- /dev/null +++ b/submissions_extracted/439/Q1.ipynb @@ -0,0 +1,272 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "import numpy as np\n", + "import pandas as pd\n", + "import matplotlib.pyplot as plt\n", + "import os\n", + "from sklearn.ensemble import RandomForestRegressor\n", + "from sklearn.model_selection import KFold, cross_val_score\n", + "from catboost import CatBoostRegressor\n", + "from sklearn.metrics import mean_absolute_error\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q1-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "file_path = os.path.join(path, 'Q1_data.csv')\n", + "df = pd.read_csv(file_path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "print(f\"Shape: {df.shape}\")\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "df.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "print(\"\\nDataFrame Description:\")\n", + "df.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "\n", + "plt.hist(df['Delivery_Time'].dropna(), bins=30)\n", + "plt.title('Delivery Time Distribution')\n", + "plt.xlabel('Time')\n", + "plt.ylabel('Frequency')\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# delet the column\n", + "df = df.drop(columns=['Order_ID'])\n", + "\n", + "# to ensure it deleted\n", + "print(df.columns)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "print(\"Missing values:\")\n", + "print(df.isnull().sum())\n", + "\n", + "df['Weather'] = df['Weather'].fillna(df['Weather'].mode()[0])\n", + "df['Traffic_Level'] = df['Traffic_Level'].fillna(df['Traffic_Level'].mode()[0])\n", + "df['Time_of_Day'] = df['Time_of_Day'].fillna(df['Time_of_Day'].mode()[0])\n", + "\n", + "df['Courier_Experience_yrs'] = df['Courier_Experience_yrs'].fillna(df['Courier_Experience_yrs'].median())\n", + "df['Delivery_Time'] = df['Delivery_Time'].fillna(df['Delivery_Time'].median())\n", + "\n", + "print(df.isnull().sum())" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "df = df.drop_duplicates() #delete any duplicates column if there" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "df = pd.get_dummies(df, columns=['Weather', 'Traffic_Level', 'Time_of_Day', 'Vehicle_Type'])" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "from sklearn.preprocessing import StandardScaler\n", + "scaler = StandardScaler()\n", + "features = df.drop(columns=['Delivery_Time']).columns\n", + "df[features] = scaler.fit_transform(df[features])" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "#determine data and target\n", + "X = df.drop(columns=['Delivery_Time'])\n", + "y = df['Delivery_Time']" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "\n", + "# we use k fold , k = 5\n", + "kf = KFold(n_splits=5, shuffle=True, random_state=42)\n", + "\n", + "# intilaization the model\n", + "model = RandomForestRegressor(n_estimators=100, random_state=42)\n", + "\n", + "# use MSA\n", + "mae_scores = cross_val_score(model, X, y, cv=kf, scoring='neg_mean_absolute_error')\n", + "mae_scores = -mae_scores\n", + "\n", + "# 5. print the average\n", + "print(f\"Average MAE across all folds: {mae_scores.mean():.2f}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "\n", + "# start training\n", + "model.fit(X, y)\n", + "\n", + "importances = pd.Series(model.feature_importances_, index=X.columns).sort_values(ascending=True)\n", + "\n", + "# plot\n", + "plt.figure(figsize=(10, 8))\n", + "importances.plot(kind='barh', color='teal')\n", + "plt.title('Feature Importance - What affects delivery time?')\n", + "plt.xlabel('Importance Score')\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Get the forecast\n", + "y_pred = model.predict(X)\n", + "\n", + "# plot\n", + "plt.figure(figsize=(10, 6))\n", + "plt.hist(y_pred, bins=30, color='orange', alpha=0.7, label='Predicted')\n", + "plt.hist(y, bins=30, color='blue', alpha=0.3, label='Actual')\n", + "plt.title('Distribution of Predicted vs Actual Delivery Time')\n", + "plt.xlabel('Delivery Time (min)')\n", + "plt.ylabel('Frequency')\n", + "plt.legend()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "\n", + "\n", + "kf = KFold(n_splits=5, shuffle=True, random_state=42)\n", + "rf_model = RandomForestRegressor(n_estimators=100, random_state=42)\n", + "cb_model = CatBoostRegressor(verbose=0, random_state=42) # verbose=0 لتقليل المخرجات\n", + "\n", + "mae_list = []\n", + "\n", + "for train_index, test_index in kf.split(X):\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", + " rf_model.fit(X_train, y_train)\n", + " cb_model.fit(X_train, y_train)\n", + "\n", + " rf_preds = rf_model.predict(X_test)\n", + " cb_preds = cb_model.predict(X_test)\n", + "\n", + " final_preds = (rf_preds + cb_preds) / 2\n", + "\n", + " mae = mean_absolute_error(y_test, final_preds)\n", + " mae_list.append(mae)\n", + "\n", + "print(f\"Average Ensemble MAE: {np.mean(mae_list):.4f}\")" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/439/Q2.ipynb b/submissions_extracted/439/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..f505761c697c0168eb8248c49cda4ca807f88299 --- /dev/null +++ b/submissions_extracted/439/Q2.ipynb @@ -0,0 +1,338 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "import pandas as pd\n", + "import numpy as np\n", + "import torch\n", + "import torch.nn as nn\n", + "from torch.optim import AdamW\n", + "import matplotlib.pyplot as plt\n", + "from torch.utils.data import DataLoader, TensorDataset\n", + "from sklearn.model_selection import train_test_split\n", + "from sklearn.preprocessing import StandardScaler, LabelEncoder\n", + "from sklearn.metrics import mean_absolute_error, mean_squared_error, r2_score\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q2-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import os\n", + "import pandas as pd\n", + "import numpy as np\n", + "from PIL import Image\n", + "from sklearn.model_selection import train_test_split\n", + "\n", + "# Load Labels\n", + "labels_df = pd.read_csv(os.path.join(path, \"labels.csv\"))\n", + "img_dir = os.path.join(path, \"images\")\n", + "\n", + "images = []\n", + "ages = []\n", + "\n", + "# Load Images and Resize\n", + "print(\"Loading images...\")\n", + "for index, row in labels_df.iterrows():\n", + " img_name = row.iloc[0]\n", + " age = row.iloc[1]\n", + " img_path = os.path.join(img_dir, img_name)\n", + "\n", + " if os.path.exists(img_path):\n", + " img = Image.open(img_path).convert('RGB')\n", + " img_array = np.array(img) / 255.0 # Normalize pixel values to [0, 1]\n", + " images.append(img_array)\n", + " ages.append(age)\n", + "\n", + "X = np.array(images)\n", + "y = np.array(ages)\n", + "\n", + "# Transpose image dimensions to match PyTorch format (N, C, H, W)\n", + "X = np.transpose(X, (0, 3, 1, 2))\n", + "\n", + "# Split Data\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n", + "\n", + "print(f\"X_train shape: {X_train.shape}\")\n", + "print(f\"X_test shape: {X_test.shape}\")\n", + "print(f\"y_train shape: {y_train.shape}\")\n", + "print(f\"y_test shape: {y_test.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 1. Convert Numpy arrays to PyTorch Tensors\n", + "\n", + "\n", + "X_train_tensor = torch.tensor(X_train, dtype=torch.float32)\n", + "X_test_tensor = torch.tensor(X_test, dtype=torch.float32)\n", + "y_train_tensor = torch.tensor(y_train, dtype=torch.float32)\n", + "y_test_tensor = torch.tensor(y_test, dtype=torch.float32)\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 2. Create TensorDataset objects\n", + "\n", + "train_dataset = TensorDataset(X_train_tensor, y_train_tensor)\n", + "test_dataset = TensorDataset(X_test_tensor, y_test_tensor)\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 3. Create DataLoaders\n", + "\n", + "train_loader = DataLoader(train_dataset, batch_size=32, shuffle=True)\n", + "test_loader = DataLoader(test_dataset, batch_size=32, shuffle=False)\n", + "\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 4. Print shape of one batch\n", + "\n", + "for X_batch, y_batch in train_loader:\n", + " print(f\"Batch images shape: {X_batch.shape}\")\n", + " print(f\"Batch labels shape: {y_batch.shape}\")\n", + " break\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 5. Display sample images\n", + "\n", + "images, labels = next(iter(train_loader))\n", + "\n", + "fig, axes = plt.subplots(2, 3, figsize=(12, 8))\n", + "for i, ax in enumerate(axes.flat):\n", + " if i < len(images):\n", + " img = images[i].permute(1, 2, 0).numpy()\n", + " ax.imshow(img)\n", + " ax.set_title(f\"Age: {labels[i].item():.0f}\")\n", + " ax.axis('off')\n", + "plt.tight_layout()\n", + "plt.show()\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "class AgeRegressionModel(nn.Module):\n", + " def __init__(self, input_dim, hidden_dim):\n", + " super(AgeRegressionModel, self).__init__()\n", + "\n", + " self.flatten = nn.Flatten()\n", + "\n", + " self.layer1 = nn.Linear(input_dim, hidden_dim)\n", + " self.layer2 = nn.Linear(hidden_dim, hidden_dim)\n", + " self.layer3 = nn.Linear(hidden_dim, hidden_dim)\n", + " self.layer4 = nn.Linear(hidden_dim, 1)\n", + " self.relu = nn.ReLU()\n", + "\n", + " def forward(self, x):\n", + " x = self.flatten(x)\n", + "\n", + " a1 = self.relu(self.layer1(x))\n", + " a2 = self.relu(self.layer2(a1))\n", + " a3 = self.relu(self.layer3(a2))\n", + " output = self.layer4(a3)\n", + "\n", + " return output\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "def train_one_epoch(model, optimizer, criterion, train_loader, device):\n", + " model.train()\n", + "\n", + " running_loss = 0.0\n", + "\n", + " for X_batch, y_batch in train_loader:\n", + " X_batch = X_batch.to(device)\n", + " y_batch = y_batch.to(device)\n", + "\n", + " outputs = model(X_batch)\n", + " loss = criterion(outputs, y_batch)\n", + "\n", + " optimizer.zero_grad()\n", + " loss.backward()\n", + " optimizer.step()\n", + "\n", + " running_loss += loss.item()\n", + "\n", + " avg_loss = running_loss / len(train_loader)\n", + "\n", + " return avg_loss\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "def validate(model, criterion, test_loader, device):\n", + " model.eval()\n", + " running_loss = 0.0\n", + " with torch.no_grad():\n", + " for X_batch, y_batch in test_loader:\n", + " X_batch = X_batch.to(device)\n", + " y_batch = y_batch.to(device)\n", + " outputs = model(X_batch)\n", + " loss = criterion(outputs, y_batch)\n", + " running_loss += loss.item()\n", + " avg_loss = running_loss / len(test_loader)\n", + "\n", + " return avg_loss\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "from torch.optim import AdamW\n", + "device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\n", + "input_dim = X_train.shape[1] * X_train.shape[2] * X_train.shape[3]\n", + "hidden_dim = 512\n", + "model = AgeRegressionModel(input_dim, hidden_dim).to(device)\n", + "print(\"Model Architecture:\")\n", + "print(model)\n", + "total_params = sum(p.numel() for p in model.parameters() if p.requires_grad)\n", + "print(f\"\\nTotal trainable parameters: {total_params}\")\n", + "criterion = nn.MSELoss()\n", + "learning_rate = 0.001\n", + "optimizer = AdamW(model.parameters(), lr=learning_rate)\n", + "print(f\"\\nUsing device: {device}\")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "num_epochs = 20\n", + "train_losses = []\n", + "val_losses = []\n", + "print(\"Starting Training...\")\n", + "for epoch in range(num_epochs):\n", + " train_loss = train_one_epoch(model, optimizer, criterion, train_loader, device)\n", + " val_loss = validate(model, criterion, test_loader, device)\n", + " train_losses.append(train_loss)\n", + " val_losses.append(val_loss)\n", + " if (epoch + 1) % 5 == 0:\n", + " print(\n", + " f\"Epoch [{epoch+1}/{num_epochs}], \"\n", + " f\"Train Loss: {train_loss:.4f}, \"\n", + " f\"Val Loss: {val_loss:.4f}\"\n", + " )\n", + "print(\"Training Complete!\")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "plt.figure(figsize=(10, 6))\n", + "plt.plot(range(1, num_epochs+1), train_losses, label='Training Loss', marker='o')\n", + "plt.plot(range(1, num_epochs+1), val_losses, label='Validation Loss', marker='s')\n", + "plt.xlabel('Epoch', fontsize=12)\n", + "plt.ylabel('Loss', fontsize=12)\n", + "plt.title('Training and Validation Loss Over Epochs', fontsize=14)\n", + "plt.legend()\n", + "plt.grid(True, alpha=0.3)\n", + "plt.tight_layout()\n", + "plt.show()\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "model.eval()\n", + "images, labels = next(iter(test_loader))\n", + "images, labels = images.to(device), labels.to(device)\n", + "with torch.no_grad():\n", + " predictions = model(images)\n", + "fig, axes = plt.subplots(2, 3, figsize=(15, 10))\n", + "for i, ax in enumerate(axes.flat):\n", + " if i < len(images):\n", + " img = images[i].cpu().permute(1, 2, 0).numpy()\n", + " actual_age = labels[i].item()\n", + " predicted_age = predictions[i].item()\n", + " ax.imshow(img)\n", + " ax.set_title(f\"Actual: {actual_age:.0f}, Predicted: {predicted_age:.0f}\")\n", + " ax.axis('off')\n", + "plt.tight_layout()\n", + "plt.show()\n" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/439/Q3.ipynb b/submissions_extracted/439/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..9c701bd1dc76eac3c6827f30b14b1caee1df9946 --- /dev/null +++ b/submissions_extracted/439/Q3.ipynb @@ -0,0 +1,292 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "!pip install catboost -q\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "import pandas as pd\n", + "import numpy as np\n", + "import matplotlib.pyplot as plt\n", + "import seaborn as sns\n", + "from sklearn.model_selection import train_test_split, KFold, cross_val_score\n", + "from sklearn.preprocessing import LabelEncoder, OneHotEncoder, StandardScaler\n", + "from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score, confusion_matrix\n", + "from sklearn.linear_model import LogisticRegression\n", + "from sklearn.tree import DecisionTreeClassifier\n", + "from sklearn.ensemble import RandomForestClassifier\n", + "from sklearn.svm import SVC\n", + "from sklearn.model_selection import StratifiedKFold\n", + "from catboost import CatBoostClassifier\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "\n", + "\n", + "\n", + "\n", + "# Download latest version\n", + "\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q3-exam-data\")\n", + "\n", + "\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "df = pd.read_csv(path + '/Q3_data.csv')\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "df.head()\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "df.info()\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "df.describe()\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "print(\"Missing Values:\")\n", + "print(df.isnull().sum())\n", + "\n", + "# Fill missing values with mean for numerical columns\n", + "df = df.fillna(df.mean(numeric_only=True))\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "print(\"Checking for duplicate rows...\")\n", + "duplicate_rows = df.duplicated().sum()\n", + "\n", + "if duplicate_rows > 0:\n", + " print(f\"Found {duplicate_rows} duplicate rows. Removing them...\")\n", + " df.drop_duplicates(inplace=True)\n", + " print(\"Duplicate rows removed.\")\n", + "else:\n", + " print(\"No duplicate rows found.\")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "from sklearn.preprocessing import LabelEncoder\n", + "\n", + "# Check for categorical columns\n", + "categorical_cols = df.select_dtypes(include=['object']).columns\n", + "print(f\"Categorical columns: {list(categorical_cols)}\")\n", + "\n", + "# Encode if any exist\n", + "for col in categorical_cols:\n", + " if col != 'target': # Don't encode the target variable\n", + " le = LabelEncoder()\n", + " df[col] = le.fit_transform(df[col])\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "\n", + "X = df.drop('Target', axis=1)\n", + "y = df['Target']\n", + "\n", + "scaler = StandardScaler() # Standardize features\n", + "X_scaled = pd.DataFrame(scaler.fit_transform(X), columns=X.columns)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "print(\"Target distribution:\")\n", + "print(y.value_counts())\n", + "print(\"\\nPercentages:\")\n", + "print(y.value_counts(normalize=True))\n", + "if y.value_counts(normalize=True).min() < 0.3:\n", + " print(\"\\nThe dataset is IMBALANCED\")\n", + "else:\n", + " print(\"\\nThe dataset is BALANCED\")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "X = X_scaled\n", + "y = df['Target']\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:\n", + "from sklearn.model_selection import StratifiedKFold\n", + "from catboost import CatBoostClassifier\n", + "from sklearn.metrics import f1_score\n", + "import numpy as np\n", + "\n", + "# use stratified for imbalanced data\n", + "kfold = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)\n", + "\n", + "scores = []\n", + "\n", + "for fold, (train_idx, val_idx) in enumerate(kfold.split(X, y)):\n", + " X_train, X_val = X.iloc[train_idx], X.iloc[val_idx]\n", + " y_train, y_val = y.iloc[train_idx], y.iloc[val_idx]\n", + "\n", + " # train model\n", + " clf = CatBoostClassifier(iterations=100, verbose=0, random_state=42)\n", + " clf.fit(X_train, y_train)\n", + "\n", + " # predict\n", + " preds = clf.predict(X_val)\n", + "\n", + " # evaluate\n", + " score = f1_score(y_val, preds)\n", + " scores.append(score)\n", + " print(f\"Fold {fold+1} F1 Score: {score:.4f}\")\n", + "\n", + "print(f\"\\nAverage F1 Score: {np.mean(scores):.4f}\")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "import matplotlib.pyplot as plt\n", + "feature_importance = model.get_feature_importance()\n", + "features = X.columns\n", + "importance_df = pd.DataFrame({\n", + " 'feature': features,\n", + " 'importance': feature_importance\n", + "}).sort_values('importance', ascending=False)\n", + "plt.figure(figsize=(10, 6))\n", + "plt.barh(importance_df['feature'][:10], importance_df['importance'][:10])\n", + "plt.xlabel('Importance')\n", + "plt.title('Top 10 Feature Importance')\n", + "plt.gca().invert_yaxis()\n", + "plt.show()\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "golden_feature = importance_df.iloc[0]['feature']\n", + "print(f\"The Golden Feature is: {golden_feature}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:\n", + "X_golden = X[[golden_feature]]\n", + "scores_golden = []\n", + "for fold, (train_idx, val_idx) in enumerate(skf.split(X_golden, y)):\n", + " X_train, X_val = X_golden.iloc[train_idx], X_golden.iloc[val_idx]\n", + " y_train, y_val = y.iloc[train_idx], y.iloc[val_idx]\n", + " model_golden = CatBoostClassifier(iterations=100, verbose=0, random_state=42)\n", + " model_golden.fit(X_train, y_train)\n", + " y_pred = model_golden.predict(X_val)\n", + " score = f1_score(y_val, y_pred)\n", + " scores_golden.append(score)\n", + "\n", + "print(f\"Full Model Average F1: {np.mean(scores):.4f}\")\n", + "print(f\"Golden Feature Only F1: {np.mean(scores_golden):.4f}\")\n", + "print(f\"Difference: {np.mean(scores) - np.mean(scores_golden):.4f}\")" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/44/Q1.ipynb b/submissions_extracted/44/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..ffe622d047beda07723b5dbba36002fde5b2ae88 --- /dev/null +++ b/submissions_extracted/44/Q1.ipynb @@ -0,0 +1,330 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q1-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "#Read the dataset Q1_data.csv using read_csv()\n", + "import numpy as np\n", + "import pandas as pd\n", + "import matplotlib.pyplot as plt\n", + "import os\n", + "import kagglehub\n", + "\n", + "from sklearn.model_selection import train_test_split, KFold\n", + "from sklearn.preprocessing import StandardScaler, LabelEncoder\n", + "from sklearn.ensemble import RandomForestRegressor\n", + "from sklearn.metrics import mean_absolute_error, mean_squared_error\n", + "\n", + "import warnings\n", + "warnings.filterwarnings('ignore')\n", + "df_path = os.path.join(path, 'Q1_data.csv')\n", + "Q1_data = pd.read_csv(df_path)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "#Inspect the first few rows using head()\n", + "print(f\"Dataset shape: {Q1_data.shape}\")\n", + "Q1_data.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "#Display dataset information using info()\n", + "# Check data types and structure\n", + "Q1_data.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "#Show statistical description using describe()\n", + "# Descriptive statistics for numerical columns\n", + "Q1_data.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "#Plot the target distribution (delivery_time)\n", + "plt.figure(figsize=(10, 5))\n", + "plt.hist(Q1_data['Delivery_Time'].dropna(), bins=50, edgecolor='black')\n", + "plt.title('Delivery_Time')\n", + "plt.xlabel('Delivery_Time')\n", + "plt.ylabel('Frequency')\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "#Drop the 'Order_ID' column from the data\n", + "Q1_data.drop(columns=['Order_ID'],inplace=True)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "#Handle missing values appropriately\n", + "Q1_data = Q1_data.dropna(subset=['Distance_km','Weather',\t'Traffic_Level',\t'Time_of_Day',\t'Vehicle_Type',\t'Preparation_Time_min',\t'Courier_Experience_yrs'])\n", + "print(f\"After dropping missing price/year/odometer: {Q1_data.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "#Check and remove duplicates if any exist\n", + "Q1_data.drop_duplicates(inplace=True)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "Q1_data.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Encode categorical columns - converts text to integers\n", + "categorical_cols = ['Weather', 'Traffic_Level', 'Time_of_Day', 'Vehicle_Type']\n", + "for col in categorical_cols:\n", + " le = LabelEncoder()\n", + " Q1_data[col] = le.fit_transform(Q1_data[col])\n", + " #onehot_encoder = OneHotEncoder(sparse_output=False) # Instantiate OneHotEncoder\n", + " #data_onehot_encoded = onehot_encoder.fit_transform(categorical_cols)\n", + "\n", + "Q1_data.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "#Apply feature scaling for all features (Use StandardScaler)\n", + "from sklearn.preprocessing import StandardScaler #import StandardScaler\n", + "\n", + "print('data before scaling:\\n',Q1_data ) #show before scaling\n", + "standard_scaler = StandardScaler() # Instantiate StandardScaler\n", + "data_standard_scaled = standard_scaler.fit_transform(Q1_data) # Apply fit_transform\n", + "\n", + "print('\\nData after scaling:\\n', data_standard_scaled) #show after scaling" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 6: Write your code here:\n", + "#Check for target imbalance and state if it is imbalanced or not (keep this cell empty if not needed)\n", + "plt.figure(figsize=(5, 5))\n", + "plt.hist(Q1_data['Delivery_Time'].dropna(), bins=30, edgecolor='black')\n", + "plt.title('Delivery_Time')\n", + "plt.xlabel('Delivery_Time')\n", + "plt.ylabel('Frequency')\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "feature_cols=['Distance_km','Weather','Traffic_Level','Time_of_Day','Vehicle_Type','Courier_Experience_yrs']\n", + "X = Q1_data[feature_cols]\n", + "y = Q1_data['Delivery_Time']\n", + "\n", + "# Train-test split (80% train, 20% test)\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n", + "print(f\"Train: {X_train.shape}, Test: {X_test.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:\n", + "#Use the correct split: KFold OR StratifiedKFold\n", + "from sklearn.model_selection import KFold\n", + "\n", + "# Use previously generated random data (example: regression data)\n", + "#X, y = X_reg.copy(), y_reg.copy()\n", + "\n", + "# Define K-Fold Cross Validation\n", + "kf = KFold(n_splits=5, shuffle=True, random_state=42)\n", + "\n", + "# Iterate through folds\n", + "for fold, (train_idx, test_idx) in enumerate(kf.split(X), start=1):\n", + " # indexing for each fold\n", + " X_train, X_test = X.iloc[train_idx], X.iloc[test_idx]\n", + " y_train, y_test = y.iloc[train_idx], y.iloc[test_idx]\n", + " # print shapes\n", + " print(f\"Fold {fold}\")\n", + " print(\" X_train shape:\", X_train.shape)\n", + " print(\" X_test shape :\", X_test.shape)\n", + " print(\" y_train shape:\", y_train.shape)\n", + " print(\" y_test shape :\", y_test.shape)\n", + " print(\"-\" * 30)\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "#Train a RandomForest model\n", + "#Train Random Forest Regressor\n", + "model = RandomForestRegressor(n_estimators=100, max_depth=20, random_state=42, n_jobs=-1)\n", + "#model.fit(X_train, y_train)\n", + "print(\"Model !\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "#Evaluate using MAE (Mean Absolute Error) ONLY\n", + "\n", + "y_pred = model.predict(X_test)\n", + "\n", + "mae = mean_absolute_error(y_test, y_pred)\n", + "rmse = np.sqrt(mean_squared_error(y_test, y_pred))\n", + "\n", + "print(f\"MAE: ${mae:,.2f}\")\n", + "print(f\"RMSE: ${rmse:,.2f}\")\n", + "#Print the averaged score across all folds" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "## Predict and evaluate" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "# Feature importance\n", + "feature_importance = pd.DataFrame({\n", + " 'feature': feature_cols,\n", + " 'importance': model.feature_importances_\n", + "}).sort_values('importance', ascending=False)\n", + "\n", + "plt.figure(figsize=(10, 6))\n", + "plt.barh(feature_importance['feature'], feature_importance['importance'])\n", + "plt.xlabel('Importance')\n", + "plt.title('Feature Importance')\n", + "plt.gca().invert_yaxis()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + " ## Predictions and metrics\n", + "y_pred = model.predict(X_test_scaled)\n", + "\n", + "print(f\"Accuracy: {accuracy_score(y_test, y_pred):.4f}\\n\")\n", + "print(classification_report(y_test, y_pred, target_names=['Normal', 'Legendary']))" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/44/Q2.ipynb b/submissions_extracted/44/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..3a06a4e7abf4a7675f31adef95005104bc322b36 --- /dev/null +++ b/submissions_extracted/44/Q2.ipynb @@ -0,0 +1,372 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q2-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import os\n", + "import pandas as pd\n", + "import numpy as np\n", + "from PIL import Image\n", + "from sklearn.model_selection import train_test_split\n", + "\n", + "# Load Labels\n", + "labels_df = pd.read_csv(os.path.join(path, \"labels.csv\"))\n", + "img_dir = os.path.join(path, \"images\")\n", + "\n", + "images = []\n", + "ages = []\n", + "\n", + "# Load Images and Resize\n", + "print(\"Loading images...\")\n", + "for index, row in labels_df.iterrows():\n", + " img_name = row.iloc[0]\n", + " age = row.iloc[1]\n", + " img_path = os.path.join(img_dir, img_name)\n", + "\n", + " if os.path.exists(img_path):\n", + " img = Image.open(img_path).convert('RGB')\n", + " img_array = np.array(img) / 255.0 # Normalize pixel values to [0, 1]\n", + " images.append(img_array)\n", + " ages.append(age)\n", + "\n", + "X = np.array(images)\n", + "y = np.array(ages)\n", + "\n", + "# Transpose image dimensions to match PyTorch format (N, C, H, W)\n", + "X = np.transpose(X, (0, 3, 1, 2))\n", + "\n", + "# Split Data\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n", + "\n", + "print(f\"X_train shape: {X_train.shape}\")\n", + "print(f\"X_test shape: {X_test.shape}\")\n", + "print(f\"y_train shape: {y_train.shape}\")\n", + "print(f\"y_test shape: {y_test.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 1. Convert Numpy arrays to PyTorch Tensors\n", + "import torch\n", + "import torch.nn as nn\n", + "from torch.optim import AdamW\n", + "import matplotlib.pyplot as plt\n", + "import torch.nn.functional as F\n", + "from torch.utils.data import DataLoader, TensorDataset\n", + "from sklearn.model_selection import train_test_split\n", + "from sklearn.preprocessing import StandardScaler, LabelEncoder\n", + "# transform to tensors\n", + "X_train = torch.tensor(X_train.values, dtype=torch.float32)\n", + "X_test = torch.tensor(X_test.values, dtype=torch.float32)\n", + "y_train = torch.tensor(y_train.values, dtype=torch.long)\n", + "y_test = torch.tensor(y_test.values, dtype=torch.long)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 2. Create TensorDataset objects\n", + "# Create TensorDatasets for training and testing\n", + "train_dataset = TensorDataset(X_train, y_train)\n", + "test_dataset = TensorDataset(X_test, y_test)\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 3. Create DataLoaders\n", + "\n", + "# Create Dataloaders to train and test data in batches\n", + "train_loader = DataLoader(train_dataset, batch_size=32, shuffle=True)\n", + "test_loader = DataLoader(test_dataset, batch_size=32, shuffle=False)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 4. Print shape of one batch\n", + "\n", + "# Print dataset sizes\n", + "print(\"Train dataset:\", len(train_dataset))\n", + "print(\"Test dataset:\", len(test_dataset))" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 5. Display sample images\n", + "\n", + "# Get the first batch from the training DataLoader\n", + "X_batch, y_batch = next(iter(train_loader))\n", + "print(f\"Training batch input shape: {X_batch.shape}\")\n", + "print(f\"Training batch labels shape: {y_batch.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your model class here:\n", + "class NN4Layer(nn.Module):\n", + "\n", + " def __init__(self, input_dim, hidden_dim, output_dim):\n", + " super(NN4Layer, self).__init__()\n", + "\n", + " # First linear layer: input features -> hidden layer\n", + " self.layer1 = nn.Linear(input_dim, hidden_dim)\n", + "\n", + " # Second linear layer: hidden layer -> hidden layer\n", + " self.layer2 = nn.Linear(hidden_dim, hidden_dim)\n", + "\n", + " # Third linear layer: hidden layer -> hidden layer\n", + " self.layer3 = nn.Linear(hidden_dim, hidden_dim)\n", + "\n", + " # Output layer: hidden layer -> number of classes (logits)\n", + " self.layer4 = nn.Linear(hidden_dim, output_dim)\n", + "\n", + " # ReLU activation for non-linearity\n", + " self.relu = nn.ReLU()\n", + "\n", + " # Defines how input data flows through the network\n", + " def forward(self, x):\n", + " # First hidden layer\n", + " a1 = self.relu(self.layer1(x))\n", + "\n", + " # Second hidden layer\n", + " a2 = self.relu(self.layer2(a1))\n", + "\n", + " # Third hidden layer\n", + " a3 = self.relu(self.layer3(a2))\n", + "\n", + " # Output layer (raw scores / logits)\n", + " output = self.layer4(a3) # we said we'll use softmax, where is it? ¯\\(ツ)/¯\n", + "\n", + " return output\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your training loop here:\n", + "def train_one_epoch(model, optimizer, criterion, train_loader, device):\n", + " # Set the model to training mode\n", + " model.train()\n", + "\n", + " running_loss = 0.0\n", + "\n", + " for X_batch, y_batch in train_loader:\n", + " # Move batch to the selected device\n", + " X_batch = X_batch.to(device) # shape: (batch_size, num_features)\n", + " y_batch = y_batch.to(device) # shape: (batch_size,)\n", + "\n", + " # Forward pass (outputs are logits)\n", + " outputs = model(X_batch) # shape: (batch_size, num_classes)\n", + " loss = criterion(outputs, y_batch)\n", + "\n", + " # Backward pass & optimization\n", + " optimizer.zero_grad() # Clear previous gradients\n", + " loss.backward() # Compute gradients\n", + " optimizer.step() # Update model parameters\n", + "\n", + " running_loss += loss.item()\n", + "\n", + " # Average loss over all batches\n", + " avg_loss = running_loss / len(train_loader)\n", + "\n", + " return avg_loss\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your validation loop here:\n", + "def validate(model, criterion, test_loader, device):\n", + " # Set the model to evaluation mode\n", + " model.eval()\n", + "\n", + " running_loss = 0.0\n", + " correct = 0\n", + " total = 0\n", + "\n", + " with torch.no_grad():\n", + " for X_batch, y_batch in test_loader:\n", + " # Move data to device\n", + " X_batch = X_batch.to(device) # shape: (batch_size, num_features)\n", + " y_batch = y_batch.to(device) # shape: (batch_size,)\n", + "\n", + " # Forward pass\n", + " outputs = model(X_batch) # shape: (batch_size, num_classes)\n", + " loss = criterion(outputs, y_batch)\n", + " running_loss += loss.item()\n", + "\n", + " # Apply Softmax to get probabilities\n", + " probabilities = F.softmax(outputs, dim=1)\n", + "\n", + " # Pick the classes with highest probabilities\n", + " predicted = torch.argmax(probabilities, dim=1)\n", + "\n", + " # Accuracy calculation\n", + " correct += (predicted == y_batch).sum().item()\n", + " total += y_batch.size(0)\n", + "\n", + " avg_loss = running_loss / len(test_loader)\n", + " accuracy = correct / total\n", + "\n", + " return avg_loss, accuracy" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Define device, model, loss, optimizer:\n", + "# Device setup\n", + "device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n", + "\n", + "# Model parameters\n", + "input_dim = X_train.shape[1] # Number of tabular features\n", + "hidden_dim = 14 # Design choice\n", + "output_dim = 4 # Weather classes: Rainy, Sunny, Cloudy, Snowy\n", + "\n", + "# Instantiate model\n", + "model = NN4Layer(input_dim, hidden_dim, output_dim).to(device)\n", + "\n", + "# Print the model architecture\n", + "print(\"Model Architecture:\\n\")\n", + "print(model)\n", + "\n", + "# Calculate the total number of trainable parameters\n", + "total_params = sum(p.numel() for p in model.parameters() if p.requires_grad)\n", + "print(f\"\\nTotal trainable parameters: {total_params}\")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Start training for 20 epochs:\n", + "num_epochs = 20\n", + "learning_rate = 0.001\n", + "\n", + "# Define criterion (loss function) - using CrossEntropyLoss as model now outputs logits\n", + "criterion = nn.CrossEntropyLoss()\n", + "# Define optimizer\n", + "optimizer = AdamW(model.parameters(), learning_rate)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Run Training\n", + "train_losses = []\n", + "val_losses = []\n", + "val_accuracies = []\n", + "\n", + "print('Starting Training...')\n", + "for epoch in range(num_epochs):\n", + " # Train one epoch\n", + " train_loss = train_one_epoch(model, optimizer, criterion, train_loader, device)\n", + "\n", + " # Validate\n", + " val_loss, val_accuracy = validate(model, criterion, test_loader, device)\n", + "\n", + " train_losses.append(train_loss)\n", + " val_losses.append(val_loss)\n", + " val_accuracies.append(val_accuracy)\n", + "\n", + " print(f'Epoch [{epoch+1}/{num_epochs}], Train Loss: {train_loss:.4f}, Val Loss: {val_loss:.4f}, Val Accuracy: {val_accuracy:.4f}')\n", + "\n", + "print('Training Complete!')" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:# Plotting results\n", + "plt.figure(figsize=(7, 5))\n", + "\n", + "plt.plot(train_losses, label='Train Loss')\n", + "plt.plot(val_losses, label='Validation Loss')\n", + "plt.title('Loss over Epochs')\n", + "plt.xlabel('Epoch')\n", + "plt.ylabel('Loss')\n", + "plt.legend()\n", + "\n", + "plt.tight_layout()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2 (Bonus): Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/44/Q3.ipynb b/submissions_extracted/44/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..7fd513254abd9f92523e022606d419586c00bc0f --- /dev/null +++ b/submissions_extracted/44/Q3.ipynb @@ -0,0 +1,190 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "\n", + "\n", + "# Download latest version\n", + "\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q3-exam-data\")\n", + "\n", + "\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Import required libraries\n", + "import kagglehub\n", + "import pandas as pd\n", + "import numpy as np\n", + "import torch\n", + "import torch.nn as nn\n", + "from torch.optim import AdamW\n", + "import matplotlib.pyplot as plt\n", + "from torch.utils.data import DataLoader, TensorDataset\n", + "from sklearn.model_selection import train_test_split\n", + "from sklearn.preprocessing import StandardScaler, LabelEncoder\n", + "from sklearn.metrics import mean_absolute_error, mean_squared_error, r2_score\n", + "\n", + "print(f\"PyTorch version: {torch.__version__}\")\n", + "print(f\"CUDA available: {torch.cuda.is_available()}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "df = pd.read_csv(path + \"Q3_data.csv\")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "df.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "df.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "# Drop rows with missing stat values\n", + "df_clean = df.dropna(subset=stat_cols).copy()\n", + "print(f\"Shape after cleaning: {df_clean.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/440/Q1.ipynb b/submissions_extracted/440/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..859925e2d3d7a571da99a9c8df138a102f47640a --- /dev/null +++ b/submissions_extracted/440/Q1.ipynb @@ -0,0 +1,290 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "import numpy as np\n", + "import pandas as pd\n", + "import matplotlib.pyplot as plt\n", + "import os\n", + "import kagglehub\n", + "\n", + "\n", + "\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q1-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "food_delivery = os.path.join(path, 'Q1_data.csv')\n", + "df = pd.read_csv(food_delivery)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "df.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "df.describe()\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "plt.figure(figsize=(10,5))\n", + "plt.hist(df['Delivery_Time'].dropna(), bins=40, edgecolor = 'black', color = 'green')\n", + "plt.title(\"Delivery Time\")\n", + "plt.ylabel('Time taken (in minutes?)')\n", + "plt.xlabel('Deliveries')\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "df_copy = df.copy()\n", + "df_copy.drop(columns=['Order_ID'], inplace= True)\n", + "df_copy.head(10)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "df_copy.dropna(subset=['Delivery_Time'], inplace = True) #Dropping rows from Delivery_Time column\n", + "df_copy['Weather'].fillna(df['Weather'].mode()[0], inplace = True)\n", + "df_copy['Traffic_Level'].fillna(df['Traffic_Level'].mode()[0], inplace = True)\n", + "df_copy['Time_of_Day'].fillna(df['Time_of_Day'].mode()[0], inplace = True)\n", + "df_copy['Courier_Experience_yrs'].fillna(df['Courier_Experience_yrs'].mode()[0], inplace = True)\n", + "\n", + "df_copy.isnull().sum()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "duplicates = df_copy.duplicated().sum()\n", + "print(f\"Number of duplicate rows: {duplicates}\")\n", + "\n", + "if duplicates > 0:\n", + " df_copy.drop_duplicates(inplace=True)\n", + " print(f\"Removed {duplicates} duplicate rows\")\n", + "else:\n", + " print(\"No duplicates found!\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "from sklearn.preprocessing import LabelEncoder\n", + "df_copy[['Weather','Traffic_Level','Time_of_Day','Vehicle_Type']]\n", + "\n", + "for col in ['Weather','Traffic_Level','Time_of_Day','Vehicle_Type']:\n", + " if col in df_copy.columns:\n", + " unique_count = df_copy[col].nunique()\n", + " print(f\" {col}: {unique_count} unique values\")\n", + "\n", + "\n", + "le = LabelEncoder()\n", + "df_copy['Weather'] = le.fit_transform(df_copy['Weather'])\n", + "df_copy['Traffic_Level'] = le.fit_transform(df_copy['Traffic_Level'])\n", + "df_copy['Time_of_Day'] = le.fit_transform(df_copy['Time_of_Day'])\n", + "df_copy['Vehicle_Type'] = le.fit_transform(df_copy['Vehicle_Type'])\n", + "\n", + "df_copy.head(10)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "from sklearn.preprocessing import StandardScaler\n", + "ss = StandardScaler()\n", + "\n", + "features = ['Distance_km','Weather','Traffic_Level','Time_of_Day','Vehicle_Type','Preparation_Time_min','Courier_Experience_yrs']\n", + "\n", + "\n", + "print('data before scaling:\\n', df_copy[features]) # before scaling\n", + "df_copy[features] = ss.fit_transform(df_copy[features]) # Applying fit_transform to the copied\n", + "print('\\nData after scaling:\\n', df_copy[features]) # after scaling\n", + "\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 6: Write your code here:\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "from sklearn.model_selection import KFold\n", + "feature_cols = ['Distance_km','Weather','Traffic_Level','Time_of_Day','Vehicle_Type','Preparation_Time_min','Courier_Experience_yrs']\n", + "\n", + "X = df_copy[feature_cols]\n", + "y = df_copy['Delivery_Time']" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:\n", + "from sklearn.ensemble import RandomForestRegressor\n", + "from sklearn.metrics import mean_absolute_error\n", + "\n", + "kf = KFold(n_splits=5, shuffle=True, random_state=42)\n", + "\n", + "for fold, (train_idx, test_idx) in enumerate(kf.split(X), start=1):\n", + " X_train, X_test = X.iloc[train_idx], X.iloc[test_idx]\n", + " y_train, y_test = y.iloc[train_idx], y.iloc[test_idx]\n", + "\n", + "\n", + "rf = RandomForestRegressor(n_estimators=100, max_depth=5, random_state=42)\n", + "rf.fit(X_train, y_train)\n", + "print(\"Random Forest R²:\", rf.score(X_test, y_test))\n", + "\n", + "\n", + "y_pred = rf.predict(X_test)\n", + "\n", + "mae = mean_absolute_error(y_test, y_pred)\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "\n", + "importance = pd.DataFrame({\n", + " 'feature': feature_cols,\n", + " 'importance': rf.feature_importances_\n", + "}).sort_values('importance', ascending=False)\n", + "\n", + "plt.figure(figsize=(10, 6))\n", + "plt.barh(importance['feature'], importance['importance'], color='red')\n", + "plt.xlabel('Importance')\n", + "plt.title('Feature Importance')\n", + "plt.gca().invert_yaxis()\n", + "plt.show()\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "plt.figure(figsize=(10,5))\n", + "plt.hist(y_pred, bins=40, edgecolor = 'black', color = 'yellow')\n", + "plt.title(\"Delivery Time\")\n", + "plt.ylabel('Time taken (in minutes) ')\n", + "plt.xlabel('Deliveries')\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/440/Q3.ipynb b/submissions_extracted/440/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..095e6a8c54f7a565243f41e1a39f176ce24e7404 --- /dev/null +++ b/submissions_extracted/440/Q3.ipynb @@ -0,0 +1,206 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "import numpy as np\n", + "import matplotlib.pyplot as plt\n", + "import pandas as pd\n", + "import os\n", + "\n", + "\n", + "# Download latest version\n", + "\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q3-exam-data\")\n", + "\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "new = os.path.join(path, 'Q3_data.csv')\n", + "df = pd.read_csv(new)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "df.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "df.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "df_copy = df.copy()\n", + "def check_missing_values(df_copy):\n", + " missing_values = df_copy.isnull().sum()\n", + " print(\"Missing Values per Column:\")\n", + " print(missing_values[missing_values > 0])\n", + " if missing_values.any():\n", + " df_copy.drop(columns=missing_values, inplace= True)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "def check_duplicates(df_copy):\n", + " duplicates = df.duplicated().sum()\n", + " print(f\"Number of Duplicate Samples: {duplicates}\")\n", + " if duplicates > 0:\n", + " print(\"Dropping Duplicates...\")\n", + " df_copy.drop_duplicates(inplace=True)\n", + " print(\"Duplicates Dropped.\")\n", + " else:\n", + " print(\"No Duplicate Samples Found.\")\n", + "\n", + "check_duplicates(df_copy)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "#There are no categorical variables\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "from sklearn.preprocessing import StandardScaler\n", + "ss = StandardScaler()\n", + "\n", + "df_copy = ss.fit_transform(df_copy) # Applying fit_transform to the copied\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "\n", + "plt.figure(figsize=(10, 5))\n", + "plt.hist(df['Target'], bins=50, edgecolor='black')\n", + "plt.title('Distribution')\n", + "plt.xlabel('...')\n", + "plt.ylabel('..')\n", + "plt.show()\n", + "\n", + "#This data is imbalanced as we can see the values are skewed at 0\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "from sklearn.model_selection import KFold\n", + "feature_cols =\n", + "\n", + "X = df_copy[feature_cols]\n", + "y = df_copy['Target']" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/441/Q1.ipynb b/submissions_extracted/441/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..2cd95b9ec953fcfdcc718e9458bd68be946f0ae2 --- /dev/null +++ b/submissions_extracted/441/Q1.ipynb @@ -0,0 +1,393 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q1-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import numpy as np\n", + "import pandas as pd\n", + "import matplotlib.pyplot as plt\n", + "import os\n", + "import kagglehub\n", + "\n", + "from sklearn.model_selection import train_test_split, StratifiedKFold, cross_val_score\n", + "from sklearn.preprocessing import StandardScaler, LabelEncoder, OneHotEncoder\n", + "from sklearn.ensemble import RandomForestClassifier\n", + "from sklearn.metrics import classification_report, confusion_matrix, accuracy_score\n", + "\n", + "import warnings\n", + "warnings.filterwarnings('ignore')" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "\n", + "# Load the CSV file\n", + "data_path = os.path.join(path, 'Q1_data.csv')\n", + "df_data = pd.read_csv(data_path)\n", + "\n", + "print(f\"Shape: {df_data.shape}\")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "\n", + "df_data.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "\n", + "# Check data info\n", + "df_data.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "\n", + "df_data.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "\n", + "# 1. What does our target variable look like?\n", + "def check_target_distribution(df, target_column):\n", + " df[target_column].hist(bins=30, edgecolor='black')\n", + "\n", + " plt.title(f\"Target Distribution ({target_column})\")\n", + " plt.xlabel(target_column)\n", + " plt.ylabel(\"Frequency\")\n", + " plt.grid(False)\n", + "\n", + " plt.show()\n", + "\n", + "check_target_distribution(df_data, \"Delivery_Time\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "\n", + "# Define columns\n", + "cols = ['Order_ID']\n", + "\n", + "# Drop\n", + "df_clean = df_data.drop(columns=cols).copy()\n", + "print(f\"Shape after cleaning: {df_clean.shape}\")\n", + "df_clean.copy().head()\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "\n", + "# Missing values\n", + "print(\"Missing values:\")\n", + "print(df_data.isnull().sum())" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Define stat columns\n", + "stat_cols = ['Weather', 'Traffic_Level', 'Time_of_Day', 'Courier_Experience_yrs']\n", + "\n", + "# Drop rows with missing stat values\n", + "df_clean = df_data.dropna(subset=stat_cols).copy()\n", + "print(f\"Shape after cleaning: {df_clean.shape}\")\n", + "\n", + "# Fill missing delivery time\n", + "df_clean['Delivery_Time'] = df_clean['Delivery_Time'].fillna('none')" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "\n", + "def check_duplicates(df):\n", + " duplicates = df.duplicated().sum()\n", + " print(f\"Number of Duplicate Samples: {duplicates}\")\n", + " if duplicates > 0:\n", + " print(\"Dropping Duplicates...\")\n", + " df.drop_duplicates(inplace=True) ##inplace changes original data\n", + " print(\"Duplicates Dropped.\")\n", + " else:\n", + " print(\"No Duplicate Samples Found.\")\n", + "\n", + "check_duplicates(df_data)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "\n", + "categorical_cols = df_data.select_dtypes(include=[\"object\"]).columns\n", + "\n", + "print(\"Categorical Columns:\", list(categorical_cols))\n", + "\n", + "label_encoders = {}\n", + "for col in categorical_cols:\n", + " le = LabelEncoder()\n", + " df_data[col] = le.fit_transform(df_data[col])\n", + " label_encoders[col] = le\n", + "\n", + "df_data\n", + "\n", + "\n", + "#onehot_encoder = OneHotEncoder(handle_unknown='ignore', sparse_output=False)\n", + "#X_encoded = pd.DataFrame(onehot_encoder.fit_transform(X), columns=onehot_encoder.get_feature_names_out(X.columns))" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "\n", + "numerical_cols = df_data.select_dtypes(include=[\"int64\", \"float64\"]).columns.drop(\"Delivery_Time\") # DON'T SCALE THE TARGET\n", + "\n", + "\n", + "scaler = StandardScaler()\n", + "df_data[numerical_cols] = scaler.fit_transform(df_data[numerical_cols])\n", + "df_data.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 6: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "\n", + "X = df_data.drop(\"Delivery_Time\",axis=1)\n", + "y = df_data[\"Delivery_Time\"]" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "from sklearn.ensemble import RandomForestRegressor\n", + "from sklearn.model_selection import KFold\n", + "from sklearn.metrics import mean_squared_error as sklearn_mse, mean_absolute_error, r2_score" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "model= RandomForestRegressor(n_estimators=200)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:\n", + "\n", + "# Mean Squared Error in NumPy\n", + "def mean_squared_error(y, y_hat):\n", + " return (1 / (2 * len(y))) * np.sum((y_hat - y) ** 2)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "n_splits = 5 # K=5 Folds\n", + "\n", + "# 5-Fold Cross-Validation, shuffled\n", + "kf = KFold(n_splits=n_splits, shuffle=True, random_state=42)\n", + "\n", + "\n", + "for fold_idx, (train_index, test_index) in enumerate(kf.split(X)):\n", + " print(f\"\\nFold {fold_idx + 1}/{n_splits}\")\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", + "\n", + "\n", + " # Train\n", + " model.fit(X_train, y_train)\n", + "\n", + " # Predict\n", + " y_pred = model.predict(X_test)\n", + "\n", + " # Calculate metrics\n", + " mse = mean_absolute_error(y_test, y_pred)\n", + "\n", + "\n", + "" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Calculate the baseline predictions (mean of the target)\n", + "baseline_pred = np.full_like(y, y.mean()) ##same size as 1\n", + "\n", + "# Evaluate the baseline\n", + "baseline_mae = mean_absolute_error(y, baseline_pred)\n", + "\n", + "\n", + "print(f\"Baseline MAE (using mean target): {baseline_mse:.4f}\")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "\n", + "coeffs = {}\n", + "\n", + "coeffs['Lasso'] = model['LASSO Regression'].coef_\n", + "coeffs['Ridge'] = model['Ridge Regression'].coef_\n", + "\n", + "fig, axes = plt.subplots(1, 2, figsize=(15, 6))\n", + "axes = axes.flatten()\n", + "features = X.columns\n", + "\n", + "for i, (model_name, coef) in enumerate(coeffs.items()):\n", + " # Sort features by absolute coefficient value\n", + " absolute_coef = np.abs(coef)\n", + " sorted_idx = np.argsort(absolute_coef)\n", + "\n", + " ax = axes[i]\n", + " ax.barh(features[sorted_idx], coef[sorted_idx])\n", + " ax.set_title(f\"{model_name} Coefficients\")\n", + " ax.set_xlabel(\"Coefficient Value (Impact)\")\n", + "\n", + "plt.tight_layout()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "\n", + "average_losses = np.mean(lr_losses, axis=0)\n", + "\n", + "plt.figure(figsize=(10, 6))\n", + "plt.plot(average_losses, label='Average Loss')\n", + "plt.xlabel('Iteration')\n", + "plt.ylabel('MSE Loss')\n", + "plt.title('Plot')\n", + "plt.legend()\n", + "plt.grid(True, alpha=0.3)\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/441/Q2.ipynb b/submissions_extracted/441/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..dfec389d370036755de814ed90b77cd97afcb70b --- /dev/null +++ b/submissions_extracted/441/Q2.ipynb @@ -0,0 +1,219 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q2-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import os\n", + "import pandas as pd\n", + "import numpy as np\n", + "from PIL import Image\n", + "from sklearn.model_selection import train_test_split\n", + "\n", + "# Load Labels\n", + "labels_df = pd.read_csv(os.path.join(path, \"labels.csv\"))\n", + "img_dir = os.path.join(path, \"images\")\n", + "\n", + "images = []\n", + "ages = []\n", + "\n", + "# Load Images and Resize\n", + "print(\"Loading images...\")\n", + "for index, row in labels_df.iterrows():\n", + " img_name = row.iloc[0]\n", + " age = row.iloc[1]\n", + " img_path = os.path.join(img_dir, img_name)\n", + "\n", + " if os.path.exists(img_path):\n", + " img = Image.open(img_path).convert('RGB')\n", + " img_array = np.array(img) / 255.0 # Normalize pixel values to [0, 1]\n", + " images.append(img_array)\n", + " ages.append(age)\n", + "\n", + "X = np.array(images)\n", + "y = np.array(ages)\n", + "\n", + "# Transpose image dimensions to match PyTorch format (N, C, H, W)\n", + "X = np.transpose(X, (0, 3, 1, 2))\n", + "\n", + "# Split Data\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n", + "\n", + "print(f\"X_train shape: {X_train.shape}\")\n", + "print(f\"X_test shape: {X_test.shape}\")\n", + "print(f\"y_train shape: {y_train.shape}\")\n", + "print(f\"y_test shape: {y_test.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 1. Convert Numpy arrays to PyTorch Tensors\n", + "\n", + "X_train = torch.tensor(X_train, dtype=torch.float32)\n", + "X_test = torch.tensor(X_test, dtype=torch.float32)\n", + "y_train = torch.tensor(y_train, dtype=torch.float32)\n", + "y_test = torch.tensor(y_test, dtype=torch.float32)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 2. Create TensorDataset objects\n", + "# Each item in the dataset is returned as (X[i], y[i])\n", + "train_dataset = TensorDataset(X_train, y_train)\n", + "test_dataset = TensorDataset(X_test, y_test)\n", + "# Access a single sample from the dataset\n", + "# This helps verify the shape of one data sample\n", + "first_sample, _ = train_dataset[0]\n", + "print(f\"Shape of one sample: {first_sample.shape}\")\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 3. Create DataLoaders\n", + "\n", + "# DataLoader for training data\n", + "train_loader = DataLoader(\n", + " train_dataset, ##returns 32 samples and features (dataset: 1 sample, dataloader: make them batches)\n", + " batch_size=32,\n", + " shuffle=True,\n", + " num_workers=2\n", + ")\n", + "# DataLoader for test/validation data\n", + "test_loader = DataLoader(\n", + " test_dataset,\n", + " batch_size=32,\n", + " shuffle=False,\n", + " num_workers=2\n", + ")\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 4. Print shape of one batch\n", + "\n", + "# Get the first batch from the training DataLoader\n", + "X_batch, y_batch = next(iter(train_loader)) ##train loader not iteratable so thats why we use iter\n", + "print(f\"Training batch input shape: {X_batch.shape}\")\n", + "print(f\"Training batch labels shape: {y_batch.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 5. Display sample images\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your model class here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your training loop here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your validation loop here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Define device, model, loss, optimizer:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Start training for 20 epochs:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2 (Bonus): Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/441/Q3.ipynb b/submissions_extracted/441/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..9e3052249123306f3acd69a7a7296b7a9fcbde31 --- /dev/null +++ b/submissions_extracted/441/Q3.ipynb @@ -0,0 +1,373 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "\n", + "\n", + "# Download latest version\n", + "\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q3-exam-data\")\n", + "\n", + "\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "from IPython.display import clear_output\n", + "\n", + "%pip install kagglehub catboost xgboost tqdm -q\n", + "\n", + "clear_output()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import numpy as np\n", + "import pandas as pd\n", + "import matplotlib.pyplot as plt\n", + "import os\n", + "import kagglehub\n", + "\n", + "from sklearn.model_selection import train_test_split, StratifiedKFold, cross_val_score\n", + "from sklearn.preprocessing import StandardScaler, LabelEncoder, OneHotEncoder\n", + "from sklearn.ensemble import RandomForestClassifier\n", + "from sklearn.metrics import classification_report, confusion_matrix, accuracy_score\n", + "\n", + "import warnings\n", + "warnings.filterwarnings('ignore')" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "\n", + "data_path = os.path.join(path, 'Q3_data.csv')\n", + "df_data = pd.read_csv(data_path)\n", + "\n", + "print(f\"Shape: {df_data.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "\n", + "df_data.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "\n", + "df_data.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "\n", + "df_data.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "\n", + "# Missing values\n", + "print(\"Missing values:\")\n", + "print(df_data.isnull().sum())" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "stat_cols = ['P_2', 'B_2', 'D_142', 'D_143','D_144','D_145']\n", + "\n", + "# Drop rows with missing stat values\n", + "df_clean = df_data.dropna(subset=stat_cols).copy()\n", + "print(f\"Shape after cleaning: {df_clean.shape}\")\n", + "\n", + "# Fill missing delivery time\n", + "df_clean['Target'] = df_clean['Target'].fillna('none')" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "\n", + "def check_duplicates(df):\n", + " duplicates = df.duplicated().sum()\n", + " print(f\"Number of Duplicate Samples: {duplicates}\")\n", + " if duplicates > 0:\n", + " print(\"Dropping Duplicates...\")\n", + " df.drop_duplicates(inplace=True) ##inplace changes original data\n", + " print(\"Duplicates Dropped.\")\n", + " else:\n", + " print(\"No Duplicate Samples Found.\")\n", + "\n", + "check_duplicates(df_data)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "\n", + "# Encode features and target using LabelEncoder\n", + "categorical_cols = df_data.select_dtypes(include=[\"object\"]).columns\n", + "for col in categorical_cols:\n", + " print(f\"Encoding column: {col}\")\n", + " le = LabelEncoder()\n", + " df_data[col] = le.fit_transform(df_data[col])\n", + "df_data" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "\n", + "# Standardize features using StandardScaler\n", + "numerical_cols = df_data.select_dtypes(include=[\"int64\", \"float64\"]).columns.drop(\"Target\") ### DON'T SCALE THE TARGET\n", + "scaler = StandardScaler()\n", + "df_data[numerical_cols] = scaler.fit_transform(df_data[numerical_cols])\n", + "df_data" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "\n", + "def check_target_distribution(df, target_column):\n", + " df[target_column].hist(bins=30, edgecolor='black')\n", + "\n", + " plt.title(f\"Target Distribution ({target_column})\")\n", + " plt.xlabel(target_column)\n", + " plt.ylabel(\"Frequency\")\n", + " plt.grid(False)\n", + "\n", + " plt.show()\n", + "\n", + "check_target_distribution(df_data, \"Target\")\n", + "\n", + "#not imbalanced" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "\n", + "X = df_data.drop(\"Target\", axis=1).astype(float) ##should be same types of could raise errors in the model when writing the equation in code, in SKlearn we dont need to do it but in numpy u cant do math betwwen 2 different types\n", + "y = df_data['Target'].astype(float)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "from sklearn.model_selection import StratifiedKFold\n", + "from sklearn.metrics import accuracy_score, f1_score\n", + "from catboost import CatBoostClassifier" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "model= CatBoostClassifier( ##for each level asks question , catgorical columns no need for encoding\n", + " verbose=0,\n", + " n_estimators=320,\n", + " max_depth=4\n", + " )" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:\n", + "\n", + "# sigmoid in NumPy\n", + "def sigmoid(z):\n", + " return 1 / (1 + np.exp(-z))\n", + "\n", + "# BCE in NumPy\n", + "def binary_cross_entropy(y, y_hat):\n", + " epsilon = 1e-15 # Very small number to prevent log(0)\n", + " y_hat = np.clip(y_hat, epsilon, 1 - epsilon) # np.clip(value, min, max) ##if its out of range clip this certain value\n", + "\n", + " loss = -1/len(y) * np.sum(y * np.log(y_hat) + (1 - y) * np.log(1 - y_hat))\n", + " return loss\n", + "\n", + "\n", + "def gradient_descent(X, y, learning_rate, n_iters=500):\n", + " m, n = X.shape # m rows, n columns (dimensions)\n", + " theta = np.zeros(n) # initialize a zeros weight vector with n dimensions\n", + " losses = []\n", + "\n", + " for _ in tqdm(range(n_iters), desc=\"Training Logistic Regression\"):\n", + " z = np.dot(X, theta)\n", + " y_hat = sigmoid(z)\n", + " gradient = np.dot(X.T, (y_hat - y)) / m\n", + " theta -= learning_rate * gradient\n", + "\n", + " loss = binary_cross_entropy(y, y_hat)\n", + " losses.append(loss)\n", + "\n", + " return theta, losses\n", + "\n", + "n_splits = 5 # K=5 Folds\n", + "\n", + "# Stratified 5-Fold Cross-Validation, shuffled\n", + "skf = StratifiedKFold(n_splits=n_splits, shuffle=True, random_state=42)\n", + "\n", + "\n", + "for fold_idx, (train_index, test_index) in enumerate(skf.split(X, y)):\n", + " print(f\"\\nFold {fold_idx + 1}/{n_splits}\")\n", + "\n", + " # 1. Split data\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", + " # 2. Train & Validate sklearn models\n", + " model.fit(X_train, y_train) # train\n", + " y_pred = model.predict(X_test) # validate\n", + "\n", + " # 3. Save metrics for that model in this fold\n", + " accuracy = accuracy_score(y_test, y_pred)\n", + " f1 = f1_score(y_test, y_pred, zero_division=0)\n", + "\n", + "\n", + "\n", + " print(f\" Accuracy: {np.mean(accuracy[model]['accuracy']):.4f}\")\n", + " print(f\" F1-Score: {np.mean(f1[model]['f1']):.4f}\")\n", + "" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "\n", + "# Gather importances from the models (from the last fold)\n", + "importances = {}\n", + "\n", + "\n", + "importances['CatBoost'] = model.feature_importances_\n", + "\n", + "# Create a 1x3 plot\n", + "fig, axes = plt.subplots(1, 3, figsize=(18, 6))\n", + "axes = axes.flatten()\n", + "features = X.columns\n", + "\n", + "for i, (model_name, imp) in enumerate(importances.items()):\n", + " # Sort features by importance for a cleaner plot\n", + " sorted_idx = np.argsort(imp)\n", + "\n", + " ax = axes[i]\n", + " ax.barh(features[sorted_idx], imp[sorted_idx])\n", + " ax.set_title(f\"{model_name} Feature Importance\")\n", + " ax.set_xlabel(\"Importance Score\")\n", + "\n", + "plt.tight_layout()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "\n", + "##the top 1 with longest figure im guessing D4 (i see there's something wrong in my looping)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/442/Q1.ipynb b/submissions_extracted/442/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..a6600d7ac3e4286b4b977709e701146f9a12713f --- /dev/null +++ b/submissions_extracted/442/Q1.ipynb @@ -0,0 +1,324 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q1-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "from IPython.display import clear_output\n", + "\n", + "%pip install kagglehub catboost lightgbm tqdm -q\n", + "\n", + "clear_output()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import pandas as pd\n", + "import numpy as np\n", + "import matplotlib.pyplot as plt\n", + "import seaborn as sns\n", + "import kagglehub\n", + "import os\n", + "from tqdm import tqdm\n", + "\n", + "%matplotlib inline" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "csv_path = os.path.join(path, \"Q1_data.csv\")\n", + "\n", + "df = pd.read_csv(csv_path)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "df.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "df.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "def check_target_distribution(df, target_column):\n", + " df[target_column].hist(bins=30, edgecolor='black')\n", + "\n", + " plt.title(f\"Target Distribution ({target_column})\")\n", + " plt.xlabel(target_column)\n", + " plt.ylabel(\"Frequency\")\n", + " plt.grid(False)\n", + "\n", + " plt.show()\n", + "\n", + "check_target_distribution(df, \"Delivery_Time\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "df= df.drop(columns='Order_ID')\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "def check_missing_values(df):\n", + " missing_values = df.isnull().sum()\n", + " print(\"Missing Values per Column:\")\n", + " print(missing_values[missing_values > 0])\n", + " if missing_values.any():\n", + " print(\"\\nHandle Missing Values as needed.\")\n", + " else:\n", + " print(\"\\nNo Missing Values Found.\")\n", + "\n", + "check_missing_values(df)\n", + "df.dropna(inplace=True)\n", + "#the task didnt specify how to handle missing values" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "def check_duplicates(df):\n", + "\n", + " #TODO: get duplicated data using pandas\n", + " duplicates = df.duplicated().sum()\n", + "\n", + " print(f\"Number of Duplicate Samples: {duplicates}\")\n", + " if duplicates > 0:\n", + " print(\"Dropping Duplicates...\")\n", + " df.drop_duplicates(inplace=True)\n", + " print(\"Duplicates Dropped.\")\n", + " else:\n", + " print(\"No Duplicate Samples Found.\")\n", + "\n", + "check_duplicates(df)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "from sklearn.preprocessing import LabelEncoder\n", + "\n", + "categorical_cols = df.select_dtypes(include=[\"object\"]).columns\n", + "\n", + "print(\"Categorical Columns:\", list(categorical_cols))\n", + "\n", + "label_encoders = {}\n", + "for col in categorical_cols:\n", + " le = LabelEncoder()\n", + " df[col] = le.fit_transform(df[col])\n", + " label_encoders[col] = le\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "from sklearn.preprocessing import StandardScaler\n", + "\n", + "numerical_cols = df.select_dtypes(include=[\"int64\", \"float64\"]).columns.drop(\"Delivery_Time\") # DON'T SCALE THE TARGET\n", + "\n", + "scaler = StandardScaler()\n", + "df[numerical_cols] = scaler.fit_transform(df[numerical_cols])\n", + "df.head()\n", + "#all columns are numerical since I encoded first" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 6: Write your code here:\n", + "#Target is not binary" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "X = df.drop(\"Delivery_Time\", axis=1).astype(float)\n", + "y = df['Delivery_Time'].astype(float)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:\n", + "from sklearn.model_selection import KFold\n", + "from sklearn.metrics import mean_squared_error as sklearn_mse, mean_absolute_error, r2_score\n", + "from sklearn.ensemble import RandomForestRegressor\n", + "\n", + "n_splits = 5 # K=5 Folds\n", + "# 5-Fold Cross-Validation, shuffled\n", + "kf = KFold(n_splits=n_splits, shuffle=True, random_state=42)\n", + "\n", + "model = RandomForestRegressor(n_estimators=200)\n", + "\n", + "maErorrs = []\n", + "\n", + "for fold_idx, (train_index, test_index) in enumerate(kf.split(X)):\n", + " print(f\"\\nFold {fold_idx + 1}/{n_splits}\")\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", + " # Train\n", + " model.fit(X_train, y_train)\n", + "\n", + " # Predict\n", + " y_pred = model.predict(X_test)\n", + "\n", + " # Calculate metrics\n", + " mae = mean_absolute_error(y_test, y_pred)\n", + "\n", + " # Store results\n", + " maErorrs.append(mae)\n", + "\n", + "print(np.mean(maErorrs))\n", + "\n", + "\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "feature_importance = pd.DataFrame({\n", + " 'feature': X.columns,\n", + " 'importance': model.feature_importances_\n", + "}).sort_values('importance', ascending=False)\n", + "\n", + "plt.figure(figsize=(10, 6))\n", + "plt.barh(feature_importance['feature'], feature_importance['importance'])\n", + "plt.xlabel('Importance')\n", + "plt.title('Feature Importance')\n", + "plt.gca().invert_yaxis()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "df[].hist(bins=30, edgecolor='black')\n", + "\n", + "plt.title(f\"Target Distribution ({})\")\n", + "plt.xlabel()\n", + "plt.ylabel(\"Frequency\")\n", + "plt.grid(False)\n", + "\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/442/Q2.ipynb b/submissions_extracted/442/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..a0db4e4c9acc1e949b38430495f3f53984102e4f --- /dev/null +++ b/submissions_extracted/442/Q2.ipynb @@ -0,0 +1,438 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q2-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import os\n", + "import pandas as pd\n", + "import numpy as np\n", + "from PIL import Image\n", + "from sklearn.model_selection import train_test_split\n", + "\n", + "# Load Labels\n", + "labels_df = pd.read_csv(os.path.join(path, \"labels.csv\"))\n", + "img_dir = os.path.join(path, \"images\")\n", + "\n", + "images = []\n", + "ages = []\n", + "\n", + "# Load Images and Resize\n", + "print(\"Loading images...\")\n", + "for index, row in labels_df.iterrows():\n", + " img_name = row.iloc[0]\n", + " age = row.iloc[1]\n", + " img_path = os.path.join(img_dir, img_name)\n", + "\n", + " if os.path.exists(img_path):\n", + " img = Image.open(img_path).convert('RGB')\n", + " img_array = np.array(img) / 255.0 # Normalize pixel values to [0, 1]\n", + " images.append(img_array)\n", + " ages.append(age)\n", + "\n", + "X = np.array(images)\n", + "y = np.array(ages)\n", + "\n", + "# Transpose image dimensions to match PyTorch format (N, C, H, W)\n", + "X = np.transpose(X, (0, 3, 1, 2))\n", + "\n", + "# Split Data\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n", + "\n", + "print(f\"X_train shape: {X_train.shape}\")\n", + "print(f\"X_test shape: {X_test.shape}\")\n", + "print(f\"y_train shape: {y_train.shape}\")\n", + "print(f\"y_test shape: {y_test.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import torch\n", + "from sklearn.datasets import load_breast_cancer\n", + "from sklearn.model_selection import train_test_split\n", + "from sklearn.preprocessing import StandardScaler\n", + "from torch.utils.data import TensorDataset\n", + "from torch.utils.data import DataLoader\n", + "import matplotlib.pyplot as plt\n", + "import torch.nn as nn\n", + "from torch.optim import Adam\n", + "from torch.utils.data import DataLoader\n", + "from torchvision.datasets import MNIST\n", + "from torchvision.transforms import ToTensor, Compose, Normalize\n", + "\n", + "from sklearn.decomposition import PCA\n", + "from sklearn.manifold import TSNE\n", + "from sklearn.cluster import KMeans\n", + "\n", + "import matplotlib.pyplot as plt\n", + "import numpy as np\n", + "from collections import Counter" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 1. Convert Numpy arrays to PyTorch Tensors\n", + "\n", + "X_train = torch.tensor(X_train.numpy().flatten(), dtype=torch.float32)\n", + "X_test = torch.tensor(np.array(X_test), dtype=torch.float32)\n", + "y_train = torch.tensor(np.array(y_train), dtype=torch.float32)\n", + "y_test = torch.tensor(np.array(y_test), dtype=torch.float32)\n", + "\n", + "\n", + "# Extract images and labels\n", + "images = []\n", + "labels = []\n", + "\n", + "for img in X_train:\n", + " img = img.numpy().flatten() # Flatten makes each 28x28 image into 784D\n", + " images.append(img)\n", + "\n", + "X = np.array(images)\n", + "pca = PCA(n_components=28*28)\n", + "\n", + "X_train = pca.fit_transform(X)\n", + "X_test = pca.fit_transform(X)\n", + "y_train = pca.fit_transform(X)\n", + "y_test = pca.fit_transform(X)\n", + "\n", + "# Calculate cumulative variance\n", + "# trying to reshape it to 28*28 ):" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 2. Create TensorDataset objects\n", + "train_dataset = TensorDataset(X_train, y_train)\n", + "test_dataset = TensorDataset(X_test, y_test)\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 3. Create DataLoaders\n", + "train_loader = DataLoader(\n", + " train_dataset,\n", + " batch_size=32,\n", + " shuffle=True,\n", + " num_workers=2\n", + ")\n", + "# DataLoader for test/validation data\n", + "test_loader = DataLoader(\n", + " test_dataset,\n", + " batch_size=32,\n", + " shuffle=False,\n", + " num_workers=2\n", + ")\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 4. Print shape of one batch\n", + "X_batch, y_batch = next(iter(train_loader))\n", + "print(f\"Training batch input shape: {X_batch.shape}\")\n", + "print(f\"Training batch labels shape: {y_batch.shape}\")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 5. Display sample images\n", + "# Get one batch of images and labels\n", + "images, labels = next(iter(train_loader))\n", + "\n", + "# Display the first 6 images in the batch\n", + "plt.figure(figsize=(8, 4))\n", + "\n", + "for i in range(6):\n", + " plt.subplot(2, 3, i + 1)\n", + " plt.imshow(images[i].squeeze(), cmap='gray')\n", + " plt.title(f\"Label: {labels[i].item()}\")\n", + " plt.axis('off')\n", + "\n", + "plt.tight_layout()\n", + "plt.show()\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import torch\n", + "import torch.nn as nn\n", + "from torchvision.datasets import MNIST\n", + "from torch.utils.data import DataLoader\n", + "from torch.optim import Adam\n", + "from torchvision.transforms.functional import to_tensor\n", + "import torch.nn.functional as F\n", + "import matplotlib.pyplot as plt" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your model class here:\n", + "class NN4Layer(nn.Module):\n", + "\n", + " def __init__(self, input_dim, hidden_dim, output_dim):\n", + " super(NN4Layer, self).__init__()\n", + "\n", + " # First linear layer: input features -> hidden layer\n", + " self.layer1 = nn.Linear(input_dim, hidden_dim)\n", + "\n", + " # Second linear layer: hidden layer -> hidden layer\n", + " self.layer2 = nn.Linear(hidden_dim, hidden_dim)\n", + "\n", + " # Output layer: hidden layer -> number of classes (logits)\n", + " self.layer3 = nn.Linear(hidden_dim, hidden_dim)\n", + "\n", + " self.layer4 = nn.Linear(hidden_dim, output_dim)\n", + "\n", + "\n", + " # ReLU activation for non-linearity\n", + " self.relu = nn.ReLU()\n", + "\n", + " # Defines how input data flows through the network\n", + " def forward(self, x):\n", + " # First hidden layer\n", + " z1 = self.layer1(x)\n", + " a1 = self.relu(z1)\n", + "\n", + " # Second hidden layer\n", + " z2 = self.layer2(a1)\n", + " a2 = self.relu(z2)\n", + "\n", + " z3 = self.layer2(a2)\n", + " a3 = self.relu(z3)\n", + "\n", + " output = self.layer3(a3)\n", + "\n", + " return output" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your training loop here:\n", + "def train_one_epoch(model, optimizer, criterion, train_loader, device):\n", + " # Set the model to training mode\n", + " model.train()\n", + "\n", + " running_loss = 0.0\n", + "\n", + " for X_batch, y_batch in train_loader:\n", + " # Move batch to the selected device\n", + " X_batch = X_batch.view(X_batch.size(0), -1).to(device)\n", + " y_batch = y_batch.to(device)\n", + "\n", + " # Forward pass\n", + " outputs = model(X_batch) # shape: (batch_size, 10)\n", + " loss = criterion(outputs, y_batch)\n", + "\n", + " # Backward pass & optimization\n", + " optimizer.zero_grad() # Clear previous gradients\n", + " loss.backward() # Compute gradients\n", + " optimizer.step() # Update model parameters\n", + "\n", + " running_loss += loss.item()\n", + "\n", + " # Average loss over all batches\n", + " avg_loss = running_loss / len(train_loader)\n", + "\n", + " return avg_loss" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your validation loop here:\n", + "def validate(model, criterion, test_loader, device):\n", + " # Set the model to evaluation mode\n", + " model.eval()\n", + "\n", + " running_loss = 0.0\n", + " correct = 0\n", + " total = 0\n", + "\n", + " with torch.no_grad():\n", + " for X_batch, y_batch in test_loader:\n", + " # Move data to device\n", + " X_batch = X_batch.view(X_batch.size(0), -1).to(device)\n", + " y_batch = y_batch.to(device)\n", + "\n", + " # Forward pass\n", + " outputs = model(X_batch) # shape: (batch_size, 10)\n", + " loss = criterion(outputs, y_batch)\n", + " running_loss += loss.item()\n", + "\n", + " # Apply Softmax to get probabilities\n", + " probabilities = F.softmax(outputs, dim=1)\n", + "\n", + " # Multiclass predictions\n", + " predicted = torch.argmax(probabilities, dim=1)\n", + "\n", + " # Accuracy calculation\n", + " correct += (predicted == y_batch).sum().item()\n", + " total += y_batch.size(0)\n", + "\n", + " avg_loss = running_loss / len(test_loader)\n", + " accuracy = correct / total\n", + "\n", + " return avg_loss, accuracy" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Define device, model, loss, optimizer:\n", + "# Device setup\n", + "device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n", + "\n", + "# Model parameters\n", + "input_dim = 28 * 28 # MNIST images flattened\n", + "hidden_dim = 14 # Design choice\n", + "output_dim = 10 # Digits 0–9\n", + "\n", + "# Instantiate model\n", + "model = NN4Layer(input_dim, hidden_dim, output_dim).to(device)\n", + "\n", + "# Print the model architecture\n", + "print(\"Model Architecture:\\n\")\n", + "print(model)\n", + "\n", + "# Calculate the total number of trainable parameters\n", + "total_params = sum(p.numel() for p in model.parameters() if p.requires_grad)\n", + "print(f\"\\nTotal trainable parameters: {total_params}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Start training for 20 epochs:\n", + "num_epochs = 10\n", + "learning_rate = 0.001\n", + "\n", + "criterion = nn.MSELoss() #I guess I should not use cross entropy since the task isnt classification\n", + "# Define optimizer\n", + "optimizer = Adam(model.parameters(), learning_rate)\n", + "\n", + "# Run Training\n", + "train_losses = []\n", + "val_losses = []\n", + "val_accuracies = []\n", + "\n", + "print('Starting Training...')\n", + "for epoch in range(num_epochs):\n", + " # Train one epoch\n", + " train_loss = train_one_epoch(model, optimizer, criterion, train_loader, device)\n", + "\n", + " # Validate\n", + " val_loss, val_accuracy = validate(model, criterion, test_loader, device)\n", + "\n", + " train_losses.append(train_loss)\n", + " val_losses.append(val_loss)\n", + " val_accuracies.append(val_accuracy)\n", + "\n", + " print(f'Epoch [{epoch+1}/{num_epochs}], Train Loss: {train_loss:.4f}, Val Loss: {val_loss:.4f}, Val Accuracy: {val_accuracy:.4f}')\n", + "\n", + "print('Training Complete!')" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "plt.figure(figsize=(7, 5))\n", + "\n", + "plt.plot(train_losses, label='Train Loss')\n", + "plt.plot(val_losses, label='Validation Loss')\n", + "plt.title('Loss over Epochs')\n", + "plt.xlabel('Epoch')\n", + "plt.ylabel('Loss')\n", + "plt.legend()\n", + "\n", + "plt.tight_layout()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2 (Bonus): Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/442/Q3.ipynb b/submissions_extracted/442/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..82527fffe1306afbd14b324025a3f9349d78b9f2 --- /dev/null +++ b/submissions_extracted/442/Q3.ipynb @@ -0,0 +1,277 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "import pandas as pd\n", + "import torch\n", + "import torch.nn as nn\n", + "from torch.optim import AdamW\n", + "import matplotlib.pyplot as plt\n", + "import torch.nn.functional as F\n", + "from torch.utils.data import DataLoader, TensorDataset\n", + "from sklearn.model_selection import train_test_split\n", + "from sklearn.preprocessing import StandardScaler, LabelEncoder" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "\n", + "\n", + "# Download latest version\n", + "\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q3-exam-data\")\n", + "\n", + "\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "pip install catboost" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "df = pd.read_csv(f\"{path}/Q3_data.csv\")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "df.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "df.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "df = df.fillna(0)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "def check_duplicates(df):\n", + "\n", + " #TODO: get duplicated data using pandas\n", + " duplicates = df.duplicated().sum()\n", + "\n", + " print(f\"Number of Duplicate Samples: {duplicates}\")\n", + " if duplicates > 0:\n", + " print(\"Dropping Duplicates...\")\n", + " df.drop_duplicates(inplace=True)\n", + " print(\"Duplicates Dropped.\")\n", + " else:\n", + " print(\"No Duplicate Samples Found.\")\n", + "\n", + "check_duplicates(df)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "#no catagorical variables\n", + "df.shape" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "from sklearn.preprocessing import StandardScaler\n", + "\n", + "numerical_cols = df.columns.drop(\"Target\") # DON'T SCALE THE TARGET\n", + "\n", + "scaler = StandardScaler()\n", + "df[numerical_cols] = scaler.fit_transform(df[numerical_cols])\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "import seaborn as sns\n", + "\n", + "def check_target_imbalance(df, target_column):\n", + " print(\"Target Distribution:\")\n", + " print(df[target_column].value_counts(normalize=True))\n", + " sns.countplot(x=df[target_column])\n", + " plt.title(\"Target Distribution\")\n", + " plt.show()\n", + "\n", + "check_target_imbalance(df, \"Target\")\n", + "#so imbalanced" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "X = df.drop(\"Target\", axis=1).astype(float)\n", + "y = df['Target'].astype(float)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:\n", + "from sklearn.model_selection import StratifiedKFold\n", + "from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score\n", + "import numpy as np\n", + "\n", + "n_splits = 5 # K=5 Folds\n", + "\n", + "# Stratified 5-Fold Cross-Validation, shuffled\n", + "skf = StratifiedKFold(n_splits=n_splits, shuffle=True, random_state=42)\n", + "\n", + "from catboost import CatBoostClassifier\n", + "f1socres = []\n", + "acscores = []\n", + "\n", + "model = CatBoostClassifier(verbose=0,n_estimators=320,max_depth=4)\n", + "\n", + "\n", + "for fold_idx, (train_index, test_index) in enumerate(skf.split(X, y)):\n", + " print(f\"\\nFold {fold_idx + 1}/{n_splits}\")\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", + " # Train\n", + " model.fit(X_train, y_train)\n", + "\n", + " # Predict\n", + " y_pred = model.predict(X_test)\n", + "\n", + " # Calculate metrics\n", + " f1 = f1_score(y_test, y_pred)\n", + " accurcy = accuracy_score(y_test,y_pred)\n", + "\n", + " # Store results\n", + " f1socres.append(f1)\n", + " acscores.append(accurcy)\n", + "\n", + "print(np.mean(f1socres))\n", + "print(np.mean(acscores))" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "feature_importance = pd.DataFrame({\n", + " 'feature': X.columns,\n", + " 'importance': model.feature_importances_\n", + "}).sort_values('importance', ascending=False)\n", + "plt.figure(figsize=(40, 24))\n", + "plt.barh(feature_importance['feature'], feature_importance['importance'])\n", + "plt.xlabel('Importance')\n", + "plt.title('Feature Importance')\n", + "plt.gca().invert_yaxis()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "print(feature_importance.max()) #feature S_9 is the most important one\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/443/Q1.ipynb b/submissions_extracted/443/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..69dc9b092505b404b6de3dc0900658ac9f58288c --- /dev/null +++ b/submissions_extracted/443/Q1.ipynb @@ -0,0 +1,319 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import pandas as pd\n", + "import numpy as np\n", + "import matplotlib.pyplot as plt\n", + "import seaborn as sns\n", + "import kagglehub\n", + "import os\n", + "from tqdm import tqdm\n", + "\n", + "%matplotlib inline\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q1-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "csv_delivery = os.path.join(path, \"Q1_data.csv\")\n", + "\n", + "df_delivery = pd.read_csv(csv_delivery)\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "\n", + "df_delivery.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "\n", + "df_delivery.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "\n", + "df_delivery.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "\n", + "def check_target_distribution(df, target_column):\n", + " df[target_column].hist(bins=30, edgecolor='black')\n", + "\n", + " plt.title(f\"Target Distribution ({target_column})\")\n", + " plt.xlabel(target_column)\n", + " plt.ylabel(\"Frequency\")\n", + " plt.grid(False)\n", + "\n", + " plt.show()\n", + "\n", + "check_target_distribution(df_delivery, \"Delivery_Time\")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "\n", + "df_delivery = df_delivery.drop(columns = 'Order_ID')\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "\n", + "def check_missing_values(df):\n", + " missing_values = df.isnull().sum()\n", + " print(\"Missing Values per Column:\")\n", + " print(missing_values[missing_values > 0])\n", + " if missing_values.any():\n", + " print(\"\\nHandle Missing Values as needed.\")\n", + " else:\n", + " print(\"\\nNo Missing Values Found.\")\n", + "\n", + "check_missing_values(df_delivery)\n", + "\n", + "df_delivery = df_delivery.dropna()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "\n", + "def check_duplicates(df):\n", + " duplicates = df.duplicated().sum()\n", + " print(f\"Number of Duplicate Samples: {duplicates}\")\n", + " if duplicates > 0:\n", + " print(\"Dropping Duplicates...\")\n", + " df.drop_duplicates(inplace=True)\n", + " print(\"Duplicates Dropped.\")\n", + " else:\n", + " print(\"No Duplicate Samples Found.\")\n", + "\n", + "check_duplicates(df_delivery)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "\n", + "categorical_cols = df_delivery.select_dtypes(include=[\"object\"]).columns\n", + "\n", + "print(\"Categorical Columns:\", list(categorical_cols))\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "\n", + "from sklearn.preprocessing import LabelEncoder\n", + "\n", + "label_encoders = {}\n", + "for col in categorical_cols:\n", + " le = LabelEncoder()\n", + " df_delivery[col] = le.fit_transform(df_delivery[col])\n", + " label_encoders[col] = le\n", + "\n", + "df_delivery" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "df_delivery.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 6: Write your code here:\n", + "\n", + "from sklearn.preprocessing import StandardScaler\n", + "\n", + "numerical_cols = df_delivery.select_dtypes(include=[\"int64\", \"float64\"]).columns.drop(\"Delivery_Time\") # DON'T SCALE THE TARGET\n", + "\n", + "scaler = StandardScaler()\n", + "df_delivery[numerical_cols] = scaler.fit_transform(df_delivery[numerical_cols])\n", + "df_delivery.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "\n", + "X = df_delivery.drop(\"Delivery_Time\", axis=1).astype(float)\n", + "y = df_delivery['Delivery_Time'].astype(float)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:\n", + "\n", + "from sklearn.model_selection import StratifiedKFold\n", + "from sklearn.metrics import mean_absolute_error\n", + "from sklearn.linear_model import LinearRegression\n", + "from sklearn.ensemble import RandomForestRegressor\n", + "\n", + "\n", + "total_mae = 0\n", + "\n", + "n_splits = 5\n", + "skf = StratifiedKFold(n_splits, shuffle=True, random_state=42)\n", + "\n", + "print(\"Stratified K-Fold Cross Validation\\n\" + \"-\"*40)\n", + "\n", + "for fold, (train_idx, test_idx) in enumerate(skf.split(X, y), start=1):\n", + "\n", + " X_train, X_test = X.iloc[train_idx], X.iloc[test_idx]\n", + " y_train, y_test = y.iloc[train_idx], y.iloc[test_idx]\n", + "\n", + " RFR = RandomForestRegressor(n_estimators=200)\n", + " RFR.fit(X_train, y_train)\n", + " y_pred = reg_model.predict(X_test)\n", + "\n", + " train_ratio = (y_train.value_counts(normalize=True) * 100).sort_index()\n", + " test_ratio = (y_test.value_counts(normalize=True) * 100).sort_index()\n", + " mae = mean_absolute_error(y_test, y_pred)\n", + " print(f\"MAE : {mae:.2f}\")\n", + " total_mae += mae\n", + "\n", + "final_mae = total_mae/n_splits\n", + "print(f\"AVERAGE MAE : {final_mae:.2f}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "\n", + "plt.figure(figsize=(6, 4))\n", + "plt.scatter(y_test, y_pred, alpha=0.7)\n", + "plt.plot([min(y_test), max(y_test)], [min(y_test), max(y_test)], 'r--', linewidth=2)\n", + "plt.xlabel(\"Actual Price\")\n", + "plt.ylabel(\"Predicted Price\")\n", + "plt.title(\"Estimated delivery prices\")\n", + "plt.grid(True)\n", + "\n", + "plt.tight_layout()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/443/Q2.ipynb b/submissions_extracted/443/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..1034c09233b63d86ea24ce48bb022d511c47ed28 --- /dev/null +++ b/submissions_extracted/443/Q2.ipynb @@ -0,0 +1,371 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q2-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import os\n", + "import pandas as pd\n", + "import numpy as np\n", + "from PIL import Image\n", + "from sklearn.model_selection import train_test_split\n", + "import torch\n", + "import torch.nn as nn\n", + "from torchvision.datasets import MNIST\n", + "from torch.utils.data import DataLoader, Dataset, TensorDataset, random_split\n", + "from torch.optim import Adam\n", + "from torchvision.transforms.functional import to_tensor\n", + "import torch.nn.functional as F\n", + "import matplotlib.pyplot as plt\n", + "\n", + "\n", + "# Load Labels\n", + "labels_df = pd.read_csv(os.path.join(path, \"labels.csv\"))\n", + "img_dir = os.path.join(path, \"images\")\n", + "\n", + "images = []\n", + "ages = []\n", + "\n", + "# Load Images and Resize\n", + "print(\"Loading images...\")\n", + "for index, row in labels_df.iterrows():\n", + " img_name = row.iloc[0]\n", + " age = row.iloc[1]\n", + " img_path = os.path.join(img_dir, img_name)\n", + "\n", + " if os.path.exists(img_path):\n", + " img = Image.open(img_path).convert('RGB')\n", + " img_array = np.array(img) / 255.0 # Normalize pixel values to [0, 1]\n", + " images.append(img_array)\n", + " ages.append(age)\n", + "\n", + "X = np.array(images)\n", + "y = np.array(ages)\n", + "\n", + "# Transpose image dimensions to match PyTorch format (N, C, H, W)\n", + "X = np.transpose(X, (0, 3, 1, 2))\n", + "\n", + "# Split Data\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n", + "\n", + "print(f\"X_train shape: {X_train.shape}\")\n", + "print(f\"X_test shape: {X_test.shape}\")\n", + "print(f\"y_train shape: {y_train.shape}\")\n", + "print(f\"y_test shape: {y_test.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 1. Convert Numpy arrays to PyTorch Tensors\n", + "from sklearn.preprocessing import StandardScaler\n", + "\n", + "\n", + "\n", + "\n", + "X_train = torch.tensor(X_train, dtype=torch.float32)\n", + "X_test = torch.tensor(X_test, dtype=torch.float32)\n", + "y_train = torch.tensor(y_train, dtype=torch.float32)\n", + "y_test = torch.tensor(y_test, dtype=torch.float32)\n", + "\n", + "\n", + "\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 2. Create TensorDataset objects\n", + "train_dataset = TensorDataset(X_train, y_train)\n", + "test_dataset = TensorDataset(X_test, y_test)\n", + "\n", + "\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 3. Create DataLoaders\n", + "\n", + "train_loader = DataLoader(\n", + " train_dataset,\n", + " batch_size=32,\n", + " shuffle=True,\n", + " num_workers=2\n", + ")\n", + "# DataLoader for test/validation data\n", + "test_loader = DataLoader(\n", + " test_dataset,\n", + " batch_size=32,\n", + " shuffle=False,\n", + " num_workers=2\n", + ")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 4. Print shape of one batch\n", + "\n", + "X_batch, y_batch = next(iter(train_loader))\n", + "print(f\"Training batch input shape: {X_batch.shape}\")\n", + "print(f\"Training batch labels shape: {y_batch.shape}\")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your model class here:\n", + "\n", + "class NN3Layer(nn.Module):\n", + "\n", + " def __init__(self, input_dim, hidden_dim, output_dim):\n", + " super(NN3Layer, self).__init__()\n", + "\n", + " self.layer1 = nn.Linear(input_dim, hidden_dim)\n", + "\n", + " self.layer2 = nn.Linear(hidden_dim, hidden_dim)\n", + "\n", + " self.layer3 = nn.Linear(hidden_dim, hidden_dim)\n", + "\n", + " self.layer4 = nn.Linear(hidden_dim, output_dim)\n", + "\n", + " self.relu = nn.ReLU()\n", + "\n", + " def forward(self, x):\n", + " z1 = self.layer1(x)\n", + " a1 = self.relu(z1)\n", + "\n", + " z2 = self.layer2(a1)\n", + " a2 = self.relu(z2)\n", + "\n", + " z3 = self.layer2(a2)\n", + " a3 = self.relu(z3)\n", + "\n", + " output = self.layer4(a3)\n", + "\n", + " return output" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your training loop here:\n", + "\n", + "def train_one_epoch(model, optimizer, criterion, train_loader, device):\n", + " # Set the model to training mode\n", + " model.train()\n", + "\n", + " running_loss = 0.0\n", + "\n", + " for X_batch, y_batch in train_loader:\n", + " # Move batch to the selected device\n", + " X_batch = X_batch.view(X_batch.size(0), -1).to(device)\n", + " y_batch = y_batch.to(device)\n", + "\n", + " # Forward pass\n", + " outputs = model(X_batch) # shape: (batch_size, 10)\n", + " loss = criterion(outputs, y_batch)\n", + "\n", + " # Backward pass & optimization\n", + " optimizer.zero_grad() # Clear previous gradients\n", + " loss.backward() # Compute gradients\n", + " optimizer.step() # Update model parameters\n", + "\n", + " running_loss += loss.item()\n", + "\n", + " # Average loss over all batches\n", + " avg_loss = running_loss / len(train_loader)\n", + "\n", + " return avg_loss" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your validation loop here:\n", + "\n", + "def validate(model, criterion, test_loader, device):\n", + " # Set the model to evaluation mode\n", + " model.eval()\n", + "\n", + " running_loss = 0.0\n", + " correct = 0\n", + " total = 0\n", + "\n", + " with torch.no_grad():\n", + " for X_batch, y_batch in test_loader:\n", + " # Move data to device\n", + " X_batch = X_batch.view(X_batch.size(0), -1).to(device)\n", + " y_batch = y_batch.to(device)\n", + "\n", + " # Forward pass\n", + " outputs = model(X_batch) # shape: (batch_size, 10)\n", + " loss = criterion(outputs, y_batch)\n", + " running_loss += loss.item()\n", + "\n", + " # Apply Softmax to get probabilities\n", + " probabilities = F.softmax(outputs, dim=1)\n", + "\n", + " # Multiclass predictions\n", + " predicted = torch.argmax(probabilities, dim=1)\n", + "\n", + " # Accuracy calculation\n", + " correct += (predicted == y_batch).sum().item()\n", + " total += y_batch.size(0)\n", + "\n", + " avg_loss = running_loss / len(test_loader)\n", + " accuracy = correct / total\n", + "\n", + " return avg_loss, accuracy" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Define device, model, loss, optimizer:\n", + "\n", + "# Device setup\n", + "device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n", + "\n", + "# Model parameters\n", + "input_dim = 28 * 28 # MNIST images flattened\n", + "hidden_dim = 14 # Design choice\n", + "output_dim = 10 # Digits 0–9\n", + "\n", + "# Instantiate model\n", + "model = NN3Layer(input_dim, hidden_dim, output_dim).to(device)\n", + "\n", + "# Print the model architecture\n", + "print(\"Model Architecture:\\n\")\n", + "print(model)\n", + "\n", + "# Calculate the total number of trainable parameters\n", + "total_params = sum(p.numel() for p in model.parameters() if p.requires_grad)\n", + "print(f\"\\nTotal trainable parameters: {total_params}\")\n", + "\n", + "num_epochs = 10\n", + "learning_rate = 0.001\n", + "\n", + "# Define criterion (loss function) - using CrossEntropyLoss as model now outputs logits\n", + "criterion = nn.CrossEntropyLoss()\n", + "# Define optimizer\n", + "optimizer = Adam(model.parameters(), learning_rate)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Start training for 20 epochs:\n", + "\n", + "train_losses = []\n", + "\n", + "for epoch in range(num_epochs):\n", + " model.train()\n", + " epoch_loss = 0.0\n", + "\n", + " for X_batch, _ in train_loader: # We don't need y labels!\n", + " X_batch = X_batch.to(device)\n", + "\n", + " # Forward pass (forward function)\n", + " X_hat = model(X_batch)\n", + "\n", + " # Compute loss (compare original vs reconstruction)\n", + " loss = criterion(X_hat, X_batch)\n", + "\n", + " # Backward pass\n", + " optimizer.zero_grad()\n", + " loss.backward()\n", + " optimizer.step()\n", + "\n", + " epoch_loss += loss.item()\n", + "\n", + " avg_loss = epoch_loss / len(train_loader)\n", + " train_losses.append(avg_loss)\n", + "\n", + " print(f\"Epoch [{epoch+1:2d}/{num_epochs}] | Loss: {avg_loss:.6f}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2 (Bonus): Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/443/Q3.ipynb b/submissions_extracted/443/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..df3654b658ece5228173838f9f21028e05fbacf8 --- /dev/null +++ b/submissions_extracted/443/Q3.ipynb @@ -0,0 +1,217 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "import torch\n", + "import torch.nn as nn\n", + "from torch.optim import Adam\n", + "from torch.utils.data import DataLoader\n", + "from torchvision.datasets import MNIST\n", + "from torchvision.transforms import ToTensor, Compose, Normalize\n", + "\n", + "from sklearn.decomposition import PCA\n", + "from sklearn.manifold import TSNE\n", + "from sklearn.cluster import KMeans\n", + "\n", + "import matplotlib.pyplot as plt\n", + "import numpy as np\n", + "from collections import Counter\n", + "import pandas as pd\n", + "\n", + "\n", + "\n", + "# Download latest version\n", + "\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q3-exam-data\")\n", + "\n", + "\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "\n", + "df = pd.read_csv(f\"{path}/Q3_data.csv\")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "df.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "\n", + "df.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "\n", + "def check_missing_values(df):\n", + " missing_values = df.isnull().sum()\n", + " print(\"Missing Values per Column:\")\n", + " print(missing_values[missing_values > 0])\n", + " if missing_values.any():\n", + " print(\"\\nHandle Missing Values as needed.\")\n", + " else:\n", + " print(\"\\nNo Missing Values Found.\")\n", + "\n", + "check_missing_values(df)\n", + "\n", + "df = df.dropna()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "def check_duplicates(df):\n", + " duplicates = df.duplicated().sum()\n", + " print(f\"Number of Duplicate Samples: {duplicates}\")\n", + " if duplicates > 0:\n", + " print(\"Dropping Duplicates...\")\n", + " df.drop_duplicates(inplace=True)\n", + " print(\"Duplicates Dropped.\")\n", + " else:\n", + " print(\"No Duplicate Samples Found.\")\n", + "\n", + "check_duplicates(df)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "\n", + "\n", + "categorical_cols = df.select_dtypes(include=[\"object\"]).columns\n", + "\n", + "print(\"Categorical Columns:\", list(categorical_cols))" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "\n", + "from sklearn.preprocessing import LabelEncoder\n", + "\n", + "label_encoders = {}\n", + "for col in categorical_cols:\n", + " le = LabelEncoder()\n", + " df[col] = le.fit_transform(df[col])\n", + " label_encoders[col] = le" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/444/Q1.ipynb b/submissions_extracted/444/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..e33f149c3e5716a926653a654b9f0a3da097657c --- /dev/null +++ b/submissions_extracted/444/Q1.ipynb @@ -0,0 +1,326 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q1-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "import pandas as pd # all the tasks in part one need pandas\n", + "df = pd.read_csv(f\"{path}/Q1_data.csv\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "df.head()#normal method in pandas" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "df.info()#normal method in pandas" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "df.describe()#normal method in pandas" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "import matplotlib.pyplot as plt #import plotlib for plotting\n", + "plt.figure(figsize=(10, 5))#size of figure\n", + "plt.plot(df['delivery_time'].dropna(), bins=30, edgecolor='black')#what to plot\n", + "plt.title('delivery_time Distribution')\n", + "plt.xlabel('delivery_time')\n", + "plt.ylabel('Frequency')\n", + "plt.show()\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "df_clean = df.drop([\"Order_ID\"] , axis = 1)#dropping ID" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "print(\"Missing values:\")\n", + "print(df_clean.isnull().sum()) #seeing how many null values we have\n", + "to_null = ['Weather' , 'Traffic_Level' , 'Time_of_Day'] #colls that will be none\n", + "\n", + "df_clean[to_null] = df_clean[to_null].fillna('none')#making none\n", + "\n", + "df_clean['Courier_Experience_yrs'] = df_clean['Courier_Experience_yrs'].fillna(df['Courier_Experience_yrs'].mean())#filling this collum with the mean\n", + "\n", + "df_clean['Delivery_Time'] = df_clean['Delivery_Time'].fillna(df['Delivery_Time'].mean())#filling this collum with the mean\n", + "\n", + "print(\"Missing values:\")\n", + "print(df_clean.isnull().sum()) #checking coloms" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "print(\"Checking for duplicate rows...\")\n", + "duplicate_rows = df_clean.duplicated().sum()#cheking how many duplikate\n", + "\n", + "if duplicate_rows > 0:\n", + " print(f\"Found {duplicate_rows} duplicate rows. Removing them...\")\n", + " df_clean.drop_duplicates(inplace=True)#removing if there are any\n", + " print(\"Duplicate rows removed.\")\n", + "else:\n", + " print(\"No duplicate rows found.\")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "from sklearn.preprocessing import LabelEncoder\n", + "le = LabelEncoder()\n", + "\n", + "for col in df_clean.select_dtypes(include=[\"object\"]).columns:\n", + " df_clean[col] = le.fit_transform(df_clean[col]) #encoding each string elemnt\n", + "\n", + "#df_clean = onehot_encoder.fit_transform()\n", + "df_clean.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "import numpy as np\n", + "from sklearn.preprocessing import StandardScaler , OneHotEncoder #import scaler\n", + "\n", + "scaler = StandardScaler()\n", + "features = df_clean.columns #getting cols\n", + "\n", + "df_clean[features] = scaler.fit_transform(df_clean[features])#scaling cols\n", + "df_clean" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 6: Write your code here:\n", + "#there is no imbalance since the target is a number (dilivery time)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "X = df_clean.drop(columns=[\"Delivery_Time\"])#splitting the data\n", + "y = df_clean['Delivery_Time']\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:\n", + "from sklearn.model_selection import KFold\n", + "from sklearn.ensemble import RandomForestClassifier\n", + "from sklearn.metrics import mean_absolute_error\n", + "\n", + "kf = KFold(n_splits=5, shuffle=True, random_state=42)# kfold no imbalance\n", + "\n", + "for fold, (train_idx, test_idx) in enumerate(kf.split(X), start=1):\n", + " # indexing for each fold\n", + " X_train, X_test = X.iloc[train_idx], X.iloc[test_idx]\n", + " y_train, y_test = y.iloc[train_idx], y.iloc[test_idx]\n", + "\n", + "model = RandomForestClassifier(n_estimators=100, max_depth=15,class_weight='balanced', random_state=42)# the model randomforset\n", + "\n", + "\n", + "y_pred = model.predict(X_train)\n", + "\n", + "mae = mean_absolute_error(y_test, y_pred)#loss function\n", + "\n", + "print(f\"MAE: ${mae:,.2f}\")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "importances = {}# to save most important feacures\n", + "sklearn_models = {\"Random Forest\": RandomForestClassifier(\n", + " n_estimators=320,\n", + " max_depth=4)}\n", + "importances['Random Forest'] = sklearn_models['Random Forest'].feature_importances_\n", + "\n", + "fig, axes = plt.subplots(1, 3, figsize=(18, 6))\n", + "axes = axes.flatten()\n", + "features = X.columns\n", + "\n", + "for i, (model_name, imp) in enumerate(importances.items()):\n", + " # Sort features by importance for a cleaner plot\n", + " sorted_idx = np.argsort(imp)\n", + "\n", + " ax = axes[i]\n", + " ax.barh(features[sorted_idx], imp[sorted_idx])\n", + " ax.set_title(f\"{model_name} Feature Importance\")\n", + " ax.set_xlabel(\"Importance Score\")\n", + "\n", + "plt.tight_layout()\n", + "plt.show()#plotting the feacures\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "plt.figure(figsize=(8, 6))\n", + "\n", + "# Plot: Predicted vs Actual scatter\n", + "plt.scatter(y_test.numpy(), y_pred.flatten(), alpha=0.5, s=10, c='steelblue')\n", + "\n", + "# Add perfect prediction line\n", + "min_val = min(y_test.min(), y_pred.min())\n", + "max_val = max(y_test.max(), y_pred.max())\n", + "plt.plot([min_val, max_val], [min_val, max_val], 'r--', lw=2, label='Perfect Prediction')\n", + "\n", + "plt.xlabel('dilivery time', fontsize=12)\n", + "plt.ylabel('Predicted dilivery time', fontsize=12)\n", + "plt.title('Predicted vs Actual dilivery time', fontsize=14)\n", + "plt.legend()\n", + "plt.grid(True, alpha=0.3)\n", + "\n", + "plt.tight_layout()\n", + "plt.show()#plotting" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:\n", + "from sklearn.tree import CatBoostRegressor#i don't have time\n", + "models = {\n", + " 'Decision Tree': CatBoostRegressor(random_state=42),\n", + " 'Random Forest': RandomForestClassifier(n_estimators=100, random_state=42),#our two models\n", + "}\n", + "odel_losses = {}\n", + "num_classes = len(np.unique(y_encoded))\n", + "print(\"Starting K-Fold Cross-Validation for each model...\")\n", + "model_losses = {}\n", + "# 4. For each model:\n", + "for model_name, model in models.items():\n", + " print(f\"\\nTraining and evaluating {model_name}...\")\n", + " fold_losses = [] # List to store loss from each fold\n", + "\n", + " for fold, (train_index, val_index) in enumerate(kf.split(X_train)):\n", + " # Split X_train and y_train into training and validation sets for the current fold\n", + " X_train_fold, X_val_fold = X_train.iloc[train_index], X_train.iloc[val_index]\n", + " y_train_fold, y_val_fold = y_train[train_index], y_train[val_index]\n", + "\n", + " # Train the current model\n", + " model.fit(X_train_fold, y_train_fold)\n", + "\n", + " # Generate predictions (probabilities) on the validation set\n", + " y_pred_proba = model.predict_proba(X_val_fold)\n", + "\n", + " # Convert y_val_fold (true labels) into a one-hot encoded format\n", + " y_val_one_hot = one_hot_encode(y_val_fold, num_classes)\n", + "\n", + " # Calculate categorical cross-entropy loss for the current fold\n", + " loss = categorical_cross_entropy(y_val_one_hot, y_pred_proba)\n", + " fold_losses.append(loss)\n", + "\n", + " # Calculate the average loss for the model\n", + " avg_loss = np.mean(fold_losses)\n", + " model_losses[model_name] = avg_loss\n", + "\n", + " # Print the average cross-validation loss for the current model\n", + " print(f\"{model_name} - Average Cross-Validation Loss: {avg_loss:.4f}\")\n", + "\n", + "print(\"\\nAll models trained and evaluated. Stored average losses:\")\n", + "print(model_losses)" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/444/Q2.ipynb b/submissions_extracted/444/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..61dd98f1b420cc4313ad65bca1b4b5d3b8a04c4c --- /dev/null +++ b/submissions_extracted/444/Q2.ipynb @@ -0,0 +1,373 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q2-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import os\n", + "import pandas as pd\n", + "import numpy as np\n", + "from PIL import Image\n", + "from sklearn.model_selection import train_test_split\n", + "\n", + "# Load Labels\n", + "labels_df = pd.read_csv(os.path.join(path, \"labels.csv\"))\n", + "img_dir = os.path.join(path, \"images\")\n", + "\n", + "images = []\n", + "ages = []\n", + "\n", + "# Load Images and Resize\n", + "print(\"Loading images...\")\n", + "for index, row in labels_df.iterrows():\n", + " img_name = row.iloc[0]\n", + " age = row.iloc[1]\n", + " img_path = os.path.join(img_dir, img_name)\n", + "\n", + " if os.path.exists(img_path):\n", + " img = Image.open(img_path).convert('RGB')\n", + " img_array = np.array(img) / 255.0 # Normalize pixel values to [0, 1]\n", + " images.append(img_array)\n", + " ages.append(age)\n", + "\n", + "X = np.array(images)\n", + "y = np.array(ages)\n", + "\n", + "# Transpose image dimensions to match PyTorch format (N, C, H, W)\n", + "X = np.transpose(X, (0, 3, 1, 2))\n", + "\n", + "# Split Data\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n", + "\n", + "print(f\"X_train shape: {X_train.shape}\")\n", + "print(f\"X_test shape: {X_test.shape}\")\n", + "print(f\"y_train shape: {y_train.shape}\")\n", + "print(f\"y_test shape: {y_test.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 1. Convert Numpy arrays to PyTorch Tensors\n", + "import torch#convertimg to tensor normaly\n", + "\n", + "X_train = torch.tensor(X_train, dtype=torch.float32)\n", + "X_test = torch.tensor(X_test, dtype=torch.float32)\n", + "y_train = torch.tensor(y_train, dtype=torch.float32)\n", + "y_test = torch.tensor(y_test, dtype=torch.float32)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 2. Create TensorDataset objects\n", + "from torch.utils.data import TensorDataset\n", + "\n", + "train_dataset = TensorDataset(X_train, y_train)#making data sets\n", + "test_dataset = TensorDataset(X_test, y_test)\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 3. Create DataLoaders\n", + "from torch.utils.data import DataLoader\n", + "\n", + "train_loader = DataLoader(train_dataset, batch_size=32, shuffle=True)#making data loaders\n", + "test_loader = DataLoader(test_dataset, batch_size=32, shuffle=False)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 4. Print shape of one batch\n", + "X_batch, y_batch = next(iter(train_loader))#getting one batch\n", + "print(f\"Training batch input shape: {X_batch.shape}\")#printing it\n", + "print(f\"Training batch labels shape: {y_batch.shape}\")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 5. Display sample images\n", + "import matplotlib.pyplot as plt\n", + "\n", + "for i in range(6):#getting 6 imgs\n", + " plt.subplot(2, 3, i + 1)\n", + " plt.imshow(images[i].squeeze(), cmap='gray')\n", + " plt.title(f\"Label: {y_batch[i].item()}\")\n", + " plt.axis('off')\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your model class here:\n", + "import torch.nn as nn\n", + "\n", + "class NN4Layer(nn.Module):#the 4 layer nn\n", + "\n", + " def __init__(self, input_dim, hidden_dim, output_dim):\n", + " super(NN4Layer, self).__init__()\n", + "\n", + " # First linear layer: input features -> hidden layer\n", + " self.layer1 = nn.Linear(input_dim, hidden_dim)\n", + "\n", + " self.layer2 = nn.Linear(hidden_dim, hidden_dim)#hidden\n", + "\n", + " self.layer3 = nn.Linear(hidden_dim, hidden_dim)#hidden\n", + "\n", + " self.layer4 = nn.Linear(hidden_dim, output_dim)# Output layer: hidden layer for number of classes (logits)\n", + " # ReLU activation for non-linearity\n", + " self.relu = nn.ReLU()\n", + "\n", + "\n", + " def forward(self, x):\n", + " # First hidden layer\n", + " z1 = self.layer1(x)\n", + " a1 = self.relu(z1)\n", + "\n", + " # Second hidden layer\n", + " z2 = self.layer2(a1)\n", + " a2 = self.relu(z2)\n", + "\n", + " # thired layer (raw scores / logits)\n", + " z3 = self.layer3(a2)\n", + " a3 = self.relu(z3)\n", + "\n", + " #output layer\n", + " output = self.layer4(a3) #without relu we want continus values\n", + "\n", + " return output" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your training loop here:\n", + "def train_one_epoch(model, optimizer, criterion, train_loader, device):\n", + " # Set the model to training mode\n", + " model.train()\n", + "\n", + " running_loss = 0.0\n", + "\n", + " for X_batch, y_batch in train_loader:\n", + " # Move batch to the selected device\n", + " X_batch = X_batch.view(X_batch.size(0), -1).to(device)\n", + " y_batch = y_batch.to(device)\n", + "\n", + " # Forward pass\n", + " outputs = model(X_batch) # shape: (batch_size, 10)\n", + " loss = criterion(outputs, y_batch)\n", + "\n", + " # Backward pass & optimization\n", + " optimizer.zero_grad() # Clear previous gradients\n", + " loss.backward() # Compute gradients\n", + " optimizer.step() # Update model parameters\n", + "\n", + " running_loss += loss.item()\n", + "\n", + " # Average loss over all batches\n", + " avg_loss = running_loss / len(train_loader)\n", + "\n", + " return avg_loss" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your validation loop here:\n", + "from sklearn.metrics import mean_squared_error\n", + "def validate(model, criterion, test_loader, device):\n", + " # Set the model to evaluation mode\n", + " model.eval()\n", + "\n", + " running_loss = 0.0\n", + " correct = 0\n", + " total = 0\n", + "\n", + " with torch.no_grad():\n", + " for X_batch, y_batch in test_loader:\n", + " # Move data to device\n", + " X_batch = X_batch.view(X_batch.size(0), -1).to(device)\n", + " y_batch = y_batch.to(device)\n", + "\n", + " # Forward pass\n", + " outputs = model(X_batch) # shape: (batch_size, 10)\n", + " loss = criterion(outputs, y_batch)\n", + " running_loss += loss.item()\n", + "\n", + " # Accuracy calculation\n", + "\n", + " total += y_batch.size(0)\n", + "\n", + " avg_loss = running_loss / len(test_loader)\n", + " accuracy = correct / total\n", + "\n", + " return avg_loss, accuracy\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Define device, model, loss, optimizer:\n", + "\n", + "from torch.optim import AdamW\n", + "\n", + "# Device setup\n", + "device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n", + "\n", + "# Model parameters\n", + "input_dim = 3 * 36 * 36 # faces images flattened\n", + "hidden_dim = 32 # Design choice\n", + "output_dim = 1 # age\n", + "\n", + "# Instantiate model\n", + "model = NN4Layer(input_dim, hidden_dim, output_dim).to(device)\n", + "\n", + "# Print the model architecture\n", + "print(\"Model Architecture:\\n\")\n", + "print(model)\n", + "\n", + "num_epochs = 20\n", + "learning_rate = 0.001\n", + "\n", + "# Define criterion (loss function) - using MSE\n", + "criterion = nn.MSELoss()\n", + "# Define optimizer\n", + "optimizer = AdamW(model.parameters(), learning_rate)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Start training for 20 epochs:\n", + "train_losses = []\n", + "val_losses = []\n", + "val_accuracies = []\n", + "\n", + "print('Starting Training...')\n", + "for epoch in range(num_epochs):\n", + " # Train one epoch\n", + " train_loss = train_one_epoch(model, optimizer, criterion, train_loader, device)\n", + "\n", + " # Validate\n", + " val_loss, val_accuracy = validate(model, criterion, test_loader, device)\n", + "\n", + " train_losses.append(train_loss)\n", + " val_losses.append(val_loss)\n", + " val_accuracies.append(val_accuracy)\n", + "\n", + " print(f'Epoch [{epoch+1}/{num_epochs}], Train Loss: {train_loss:.4f}, Val Loss: {val_loss:.4f}, Val Accuracy: {val_accuracy:.4f}')#printing results\n", + "\n", + "print('Training Complete!')" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "plt.figure(figsize=(7, 5))#plotting results\n", + "\n", + "plt.plot(train_losses, label='Train Loss')#train loss is low\n", + "plt.plot(val_losses, label='Validation Loss')#val loss is low\n", + "plt.title('Loss over Epochs')#my model iss good :D\n", + "plt.xlabel('Epoch')\n", + "plt.ylabel('Loss')\n", + "plt.legend()\n", + "\n", + "plt.tight_layout()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2 (Bonus): Write your code here:\n", + "# Get one batch of images and labels\n", + "images, labels = next(iter(train_loader))\n", + "\n", + "# Display the first 6 images in the batch\n", + "plt.figure(figsize=(8, 4))\n", + "\n", + "for i in range(6):\n", + " plt.subplot(2, 3, i + 1)\n", + "\n", + " # Convert from (C, H, W) to (H, W, C) for matplotlib\n", + " img = images[i].permute(1, 2, 0)\n", + "\n", + " plt.imshow(img)\n", + " plt.title(f\"age: {labels[i].item()}\")\n", + " plt.axis('off')\n", + "\n", + "plt.tight_layout()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/444/Q3.ipynb b/submissions_extracted/444/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..40ef1812d1aa09b83c6187f119794ca879badd34 --- /dev/null +++ b/submissions_extracted/444/Q3.ipynb @@ -0,0 +1,258 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "\n", + "\n", + "# Download latest version\n", + "\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q3-exam-data\")\n", + "\n", + "\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "import pandas as pd # all the tasks in part one need pandas\n", + "df = pd.read_csv(f\"{path}/Q3_data.csv\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "df.head()#normal method in pandas" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "df.info()#normal method in pandas" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "df.describe()#normal method in pandas" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "print(\"Missing values:\")\n", + "print(df.isnull().sum()) #seeing how many null values we have\n", + "\n", + "df_clean = df.dropna()\n", + "\n", + "print(\"Missing values:\")\n", + "print(df_clean.isnull().sum())" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "print(\"Checking for duplicate rows...\")\n", + "duplicate_rows = df_clean.duplicated().sum()#cheking how many duplikate\n", + "\n", + "if duplicate_rows > 0:\n", + " print(f\"Found {duplicate_rows} duplicate rows. Removing them...\")\n", + " df_clean.drop_duplicates(inplace=True)#removing if there are any\n", + " print(\"Duplicate rows removed.\")\n", + "else:\n", + " print(\"No duplicate rows found.\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "from sklearn.preprocessing import LabelEncoder\n", + "le = LabelEncoder()\n", + "\n", + "for col in df_clean.select_dtypes(include=[\"object\"]).columns:\n", + " df_clean[col] = le.fit_transform(df_clean[col])#encoding each string colom\n", + "\n", + "df_clean.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "from sklearn.preprocessing import StandardScaler , OneHotEncoder #import scaler\n", + "\n", + "scaler = StandardScaler()\n", + "numerical_cols = df.select_dtypes(include=[\"number\"]).columns # save the number cols\n", + "\n", + "#datascaled = scaler.fit_transform(df_clean) #do it for the entire data\n", + "df_clean[numerical_cols] = scaler.fit_transform(df_clean[numerical_cols])# scale them" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "#there is no imbalance numbers between 0 and 1" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "X = df_clean.drop(columns=[\"Target\"])#splitting the data\n", + "y = df_clean['Target']" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "!pip install catboost #wasn't installed for some reason" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:\n", + "from catboost import CatBoostClassifier\n", + "from sklearn.model_selection import KFold\n", + "from sklearn.metrics import mean_absolute_error\n", + "\n", + "models = {\"CatBoost\": CatBoostClassifier( #all the models(just one)\n", + " verbose=0,\n", + " n_estimators=200,\n", + " max_depth=4\n", + " )\n", + "}\n", + "\n", + "kf = KFold(n_splits=5, shuffle=True, random_state=42)\n", + "\n", + "for fold, (train_idx, test_idx) in enumerate(kf.split(X), start=1):\n", + " # indexing for each fold\n", + " X_train, X_test = X.iloc[train_idx], X.iloc[test_idx]\n", + " y_train, y_test = y.iloc[train_idx], y.iloc[test_idx]\n", + "\n", + "model = CatBoostClassifier(n_estimators=100, max_depth=15,class_weight='balanced', random_state=42)\n", + "\n", + "\n", + "y_pred = model.predict(X_train)\n", + "\n", + "mae = mean_absolute_error(y_test, y_pred)# mae for loss\n", + "\n", + "print(f\"MAE: ${mae:,.2f}\")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "import matplotlib.pyplot as plt\n", + "importances = {} #the features to save\n", + "sklearn_models = {\"CatBoost\": CatBoostClassifier(\n", + " n_estimators=320,\n", + " max_depth=4)}\n", + "importances['CatBoost'] = sklearn_models['CatBoost'].feature_importances_\n", + "\n", + "fig, axes = plt.subplots(1, 3, figsize=(18, 6))\n", + "axes = axes.flatten()\n", + "features = X.columns\n", + "\n", + "for i, (model_name, imp) in enumerate(importances.items()):\n", + " # Sort features by importance for a cleaner plot\n", + " sorted_idx = np.argsort(imp)\n", + "\n", + " ax = axes[i]\n", + " ax.barh(features[sorted_idx], imp[sorted_idx])\n", + " ax.set_title(f\"{model_name} Feature Importance\")\n", + " ax.set_xlabel(\"Importance Score\")\n", + "\n", + "plt.tight_layout()#plotting\n", + "plt.show()\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "for i in importances: # a simple loop :)\n", + " print(importances[i])" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:\n", + "X =importances[:3]\n" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/445/Q1.ipynb b/submissions_extracted/445/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..468ecf019c6d49b784f2b83f9e41f181ce1ed578 --- /dev/null +++ b/submissions_extracted/445/Q1.ipynb @@ -0,0 +1,265 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q1-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import pandas as pd\n", + "import os\n", + "data_path = os.path.join(path, 'Q1_data.csv')\n", + "df = pd.read_csv(data_path)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "df.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "df.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import matplotlib.pyplot as plt\n", + "plt.figure(figsize=(10, 5))\n", + "plt.hist( df['Delivery_Time'].dropna(),bins=30, color='coral',edgecolor='black')\n", + "plt.title('delivery distribution')\n", + "plt.xlabel('Delivery Time')\n", + "plt.ylabel('frequency')\n", + "plt.xticks(rotation=45)\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "df_clean= df.drop(columns=['Order_ID'])\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "missing_percentage = (df.isnull().sum() )\n", + "print(missing_percentage)\n", + "df_clean = df.dropna(subset=['Weather', 'Traffic_Level ', 'Time_of_Day ','Courier_Experience_yrs'])\n", + "for col in ['Time_of_Day ', 'Courier_Experience_yrs']:\n", + " df_clean[col] = df_clean[col].fillna('unknown')\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "def check_duplicates(df):\n", + " duplicates = df.duplicated().sum()\n", + " print(f\"Number of Duplicate Samples: {duplicates}\")\n", + " if duplicates > 0:\n", + " print(\"Dropping Duplicates...\")\n", + " df.drop_duplicates(inplace=True)\n", + " print(\"Duplicates Dropped.\")\n", + " else:\n", + " print(\"No Duplicate Samples Found.\")\n", + "\n", + "check_duplicates(df)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "from sklearn.preprocessing import OneHotEncoder #import OneHotEncoder\n", + "import pandas as pd\n", + "categorical_cols = df.select_dtypes(include=[\"object\"]).columns\n", + "\n", + "print(\"Categorical Columns:\", list(categorical_cols))\n", + "for col in categorical_cols:\n", + " le = LabelEncoder()\n", + " df_clean[col] = le.fit_transform(df_clean[col].astype(str))\n", + "\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "from sklearn.preprocessing import StandardScaler\n", + "\n", + "numerical_cols = df.select_dtypes(include=[\"int64\", \"float64\"]).columns.drop(\"Delivery_Time\")\n", + "\n", + "scaler = StandardScaler()\n", + "df[numerical_cols] = scaler.fit_transform(df[numerical_cols])\n", + "df.head()\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "from sklearn.model_selection import train_test_split, KFold\n", + "from sklearn.preprocessing import StandardScaler, LabelEncoder\n", + "from sklearn.ensemble import RandomForestRegressor\n", + "from sklearn.metrics import mean_absolute_error\n", + "import numpy as np" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "X = df.drop(\"Delivery_Time\", axis=1).astype(float)\n", + "y = df['Delivery_Time'].astype(float)\n", + "\n", + "model = RandomForestRegressor(n_estimators=100, max_depth=20, random_state=42, n_jobs=-1)\n", + "lr_mae = []\n", + "f = KFold(n_splits=5, shuffle=True, random_state=42)\n", + "\n", + "for fold_idx, (train_index, test_index) in enumerate(f.split(X)):\n", + " print(f\"\\nFold {fold_idx + 1}/{5}\")\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", + " # Train\n", + " model.fit(X_train, y_train)\n", + "\n", + " # Predict\n", + " y_pred = model.predict(X_test)\n", + "\n", + " # Calculate metrics\n", + " mae = mean_absolute_error(y_test, y_pred)\n", + "\n", + "print(\"Model trained!\")\n", + "y_pred = model.predict(X_test)\n", + "\n", + "print(f\"MAE: ${mae:,.2f}\")\n", + "\n", + "average_losses = np.mean(lr_mae, axis=0)\n", + "\n", + "plt.figure(figsize=(10, 6))\n", + "plt.plot(average_losses, label='Average Loss')\n", + "plt.xlabel('Iteration')\n", + "plt.ylabel('MAE Loss')\n", + "plt.title('Linear Regression Training Loss (Averaged Across Folds)')\n", + "plt.legend()\n", + "plt.grid(True, alpha=0.3)\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "feature_importance = pd.DataFrame({\n", + " 'feature': feature_cols,\n", + " 'importance': model.feature_importances_\n", + "}).sort_values('importance', ascending=False)\n", + "\n", + "plt.figure(figsize=(10, 6))\n", + "plt.barh(feature_importance['feature'], feature_importance['importance'])\n", + "plt.xlabel('Importance')\n", + "plt.title('Feature Importance')\n", + "plt.gca().invert_yaxis()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "plt.figure(figsize=(10, 5))\n", + "plt.hist( y_test,bins=30, color='coral',edgecolor='black')\n", + "plt.title('delivery distribution')\n", + "plt.xlabel('Delivery Time')\n", + "plt.ylabel('frequency')\n", + "plt.xticks(rotation=45)\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/445/Q2.ipynb b/submissions_extracted/445/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..1d321d2331de3b3837be177980612fafb32dd2d8 --- /dev/null +++ b/submissions_extracted/445/Q2.ipynb @@ -0,0 +1,423 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q2-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import os\n", + "import pandas as pd\n", + "import numpy as np\n", + "from PIL import Image\n", + "from sklearn.model_selection import train_test_split\n", + "from torchvision.transforms.functional import to_tensor\n", + "\n", + "# Load Labels\n", + "labels_df = pd.read_csv(os.path.join(path, \"labels.csv\"))\n", + "img_dir = os.path.join(path, \"images\")\n", + "\n", + "images = []\n", + "ages = []\n", + "\n", + "# Load Images and Resize\n", + "print(\"Loading images...\")\n", + "for index, row in labels_df.iterrows():\n", + " img_name = row.iloc[0]\n", + " age = row.iloc[1]\n", + " img_path = os.path.join(img_dir, img_name)\n", + "\n", + " if os.path.exists(img_path):\n", + " img = Image.open(img_path).convert('RGB')\n", + " img_array = np.array(img) / 255.0 # Normalize pixel values to [0, 1]\n", + " images.append(img_array)\n", + " ages.append(age)\n", + "\n", + "X = np.array(images)\n", + "y = np.array(ages)\n", + "\n", + "# Transpose image dimensions to match PyTorch format (N, C, H, W)\n", + "X = np.transpose(X, (0, 3, 1, 2))\n", + "\n", + "# Split Data\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n", + "\n", + "print(f\"X_train shape: {X_train.shape}\")\n", + "print(f\"X_test shape: {X_test.shape}\")\n", + "print(f\"y_train shape: {y_train.shape}\")\n", + "print(f\"y_test shape: {y_test.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 1. Convert Numpy arrays to PyTorch Tensors\n", + "import torch\n", + "import torch.nn as nn\n", + "from torch.optim import Adam\n", + "from torch.utils.data import DataLoader\n", + "from torchvision.datasets import MNIST\n", + "from torchvision.transforms import ToTensor, Compose, Normalize\n", + "\n", + "from sklearn.decomposition import PCA\n", + "from sklearn.manifold import TSNE\n", + "from sklearn.cluster import KMeans\n", + "\n", + "import matplotlib.pyplot as plt\n", + "import numpy as np\n", + "from collections import Counter\n", + "\n", + "X_train = torch.tensor(X_train, dtype=torch.float32)\n", + "X_test = torch.tensor(X_test, dtype=torch.float32)\n", + "y_train = torch.tensor(y_train, dtype=torch.float32)\n", + "y_test = torch.tensor(y_test, dtype=torch.float32)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 2. Create TensorDataset objects\n", + "train_dataset = Image(\n", + " root='./datasets', # Dataset storage path\n", + " train=True, # Use training data\n", + " transform=to_tensor, # Convert images to tensors\n", + " download=True # Download if not available\n", + ")\n", + "\n", + "# Testing dataset\n", + "test_dataset = Image(\n", + " root='./datasets', # Dataset storage path\n", + " train=False, # Use test data\n", + " transform=to_tensor, # Convert images to tensors\n", + " download=True # Download if not available\n", + ")\n", + "\n", + "# print one sample from the dataset\n", + "# Each sample consists of an image tensor and its label\n", + "sample_image, sample_label = train_dataset[0]\n", + "\n", + "print(f\"\\n Image shape: {sample_image.shape}\") # (1, 28, 28)\n", + "print(f\"Label: {sample_label}\")\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 3. Create DataLoaders\n", + "train_loader = DataLoader(\n", + " train_dataset,\n", + " batch_size=32,\n", + " shuffle=True,\n", + " num_workers=2\n", + ")\n", + "# DataLoader for test/validation data\n", + "test_loader = DataLoader(\n", + " test_dataset,\n", + " batch_size=32,\n", + " shuffle=False,\n", + " num_workers=2\n", + ")\n", + "\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 4. Print shape of one batch\n", + "X_batch, y_batch = next(iter(train_loader))\n", + "print(f\"Training batch input shape: {X_batch.shape}\")\n", + "print(f\"Training batch labels shape: {y_batch.shape}\")\n", + "\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 5. Display sample images\n", + "\n", + "images, labels = next(iter(train_loader))\n", + "\n", + "\n", + "plt.figure(figsize=(8, 4))\n", + "\n", + "for i in range(6):\n", + " plt.subplot(2, 3, i + 1)\n", + " plt.imshow(images[i].squeeze(), cmap='gray')\n", + " plt.title(f\"Label: {labels[i].item()}\")\n", + " plt.axis('off')\n", + "\n", + "plt.tight_layout()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "class NN4Layer(nn.Module):\n", + "\n", + " def __init__(self, input_dim, hidden_dim, output_dim):\n", + " super(NN4Layer, self).__init__()\n", + "\n", + " # First linear layer: input features -> hidden layer\n", + " self.layer1 = nn.Linear(input_dim, hidden_dim)\n", + "\n", + " # Second linear layer: hidden layer -> hidden layer\n", + " self.layer2 = nn.Linear(hidden_dim, hidden_dim)\n", + " self.layer3 = nn.Linear(hidden_dim, hidden_dim)\n", + "\n", + " # Output layer: hidden layer -> number of classes (logits)\n", + " self.layer4 = nn.Linear(hidden_dim, output_dim)\n", + "\n", + " # ReLU activation for non-linearity\n", + " self.relu = nn.ReLU()\n", + "\n", + " # Defines how input data flows through the network\n", + " def forward(self, x):\n", + " # First hidden layer\n", + " z1 = self.layer1(x)\n", + " a1 = self.relu(z1)\n", + "\n", + " # Second hidden layer\n", + " z2 = self.layer2(a1)\n", + " a2 = self.relu(z2)\n", + "\n", + " a3 = self.layer2(a2)\n", + " z3 = self.relu(a3)\n", + "\n", + " # Output layer (raw scores / logits)\n", + " output = self.layer3(z3) # there is something missing here, remember? :)\n", + "\n", + " return output\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "def train_one_epoch(model, optimizer, criterion, train_loader, device):\n", + " # Set the model to training mode\n", + " model.train()\n", + "\n", + " running_loss = 0.0\n", + "\n", + " for X_batch, y_batch in train_loader:\n", + " # Move batch to the selected device\n", + " X_batch = X_batch.view(X_batch.size(0), -1).to(device)\n", + " y_batch = y_batch.to(device)\n", + "\n", + " # Forward pass\n", + " outputs = model(X_batch) # shape: (batch_size, 10)\n", + " loss = criterion(outputs, y_batch)\n", + "\n", + " # Backward pass & optimization\n", + " optimizer.zero_grad() # Clear previous gradients\n", + " loss.backward() # Compute gradients\n", + " optimizer.step() # Update model parameters\n", + "\n", + " running_loss += loss.item()\n", + "\n", + " # Average loss over all batches\n", + " avg_loss = running_loss / len(train_loader)\n", + "\n", + " return avg_loss" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "def validate(model, criterion, test_loader, device):\n", + " # Set the model to evaluation mode\n", + " model.eval()\n", + "\n", + " running_loss = 0.0\n", + " correct = 0\n", + " total = 0\n", + "\n", + " with torch.no_grad():\n", + " for X_batch, y_batch in test_loader:\n", + " # Move data to device\n", + " X_batch = X_batch.view(X_batch.size(0), -1).to(device)\n", + " y_batch = y_batch.to(device)\n", + "\n", + " # Forward pass\n", + " outputs = model(X_batch) # shape: (batch_size, 10)\n", + " loss = criterion(outputs, y_batch)\n", + " running_loss += loss.item()\n", + "\n", + " # Apply Softmax to get probabilities\n", + " probabilities = F.softmax(outputs, dim=1)\n", + "\n", + " # Multiclass predictions\n", + " predicted = torch.argmax(probabilities, dim=1)\n", + "\n", + " # Accuracy calculation\n", + " correct += (predicted == y_batch).sum().item()\n", + " total += y_batch.size(0)\n", + "\n", + " avg_loss = running_loss / len(test_loader)\n", + " accuracy = correct / total\n", + "\n", + " return avg_loss, accuracy" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n", + "\n", + "\n", + "input_dim = 28 * 28 # MNIST images flattened\n", + "hidden_dim = 14 # Design choice\n", + "output_dim = 10 # Digits 0–9\n", + "\n", + "model = NN4Layer(input_dim, hidden_dim, output_dim).to(device)\n", + "\n", + "print(\"Model Architecture:\\n\")\n", + "print(model)\n", + "\n", + "\n", + "total_params = sum(p.numel() for p in model.parameters() if p.requires_grad)\n", + "print(f\"\\nTotal trainable parameters: {total_params}\")\n", + "num_epochs = 20\n", + "learning_rate = 0.001\n", + "\n", + "criterion = nn.CrossEntropyLoss()\n", + "\n", + "optimizer = Adam(model.parameters(), learning_rate)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "train_losses = []\n", + "val_losses = []\n", + "val_accuracies = []\n", + "\n", + "print('Starting Training...')\n", + "for epoch in range(num_epochs):\n", + " # Train one epoch\n", + " train_loss = train_one_epoch(model, optimizer, criterion, train_loader, device)\n", + "\n", + " # Validate\n", + " val_loss, val_accuracy = validate(model, criterion, test_loader, device)\n", + "\n", + " train_losses.append(train_loss)\n", + " val_losses.append(val_loss)\n", + " val_accuracies.append(val_accuracy)\n", + "\n", + " print(f'Epoch [{epoch+1}/{num_epochs}], Train Loss: {train_loss:.4f}, Val Loss: {val_loss:.4f}, Val Accuracy: {val_accuracy:.4f}')\n", + "\n", + "print('Training Complete!')" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "plt.figure(figsize=(7, 5))\n", + "\n", + "plt.plot(train_losses, label='Train Loss')\n", + "plt.plot(val_losses, label='Validation Loss')\n", + "plt.title('Loss over Epochs')\n", + "plt.xlabel('Epoch')\n", + "plt.ylabel('Loss')\n", + "plt.legend()\n", + "\n", + "plt.tight_layout()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "model.eval()\n", + "# Get one batch from the test DataLoader\n", + "images, labels = next(iter(test_loader))\n", + "\n", + "images = images.to(device)\n", + "labels = labels.to(device)\n", + "\n", + "with torch.no_grad():\n", + " # Flatten images before passing to the model\n", + " outputs = model(images.view(images.size(0), -1))\n", + " predictions = torch.argmax(outputs, dim=1)\n", + "\n", + "images = images.cpu()\n", + "labels = labels.cpu()\n", + "predictions = predictions.cpu()\n", + "\n", + "plt.figure(figsize=(8, 4))\n", + "for i in range(6):\n", + " plt.subplot(2, 3, i + 1)\n", + " plt.imshow(images[i].squeeze(), cmap='gray')\n", + " plt.title(f\"True: {labels[i]} | Pred: {predictions[i]}\")\n", + " plt.axis('off')\n", + "\n", + "plt.tight_layout()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/445/Q3.ipynb b/submissions_extracted/445/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..9e31f6d2e7133d1d14236197109c952bb8aa66b7 --- /dev/null +++ b/submissions_extracted/445/Q3.ipynb @@ -0,0 +1,252 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "\n", + "\n", + "# Download latest version\n", + "\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q3-exam-data\")\n", + "\n", + "\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import pandas as pd\n", + "import os\n", + "data_path = os.path.join(path, 'Q3_data.csv')\n", + "df = pd.read_csv(data_path)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "df.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "df.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "missing_percentage = (df.isnull().sum() )\n", + "print(missing_percentage)\n", + "df_clean = df.dropna(subset=['Weather', 'Traffic_Level ', 'Time_of_Day ','Courier_Experience_yrs'])\n", + "for col in ['Time_of_Day ', 'Courier_Experience_yrs']:\n", + " df_clean[col] = df_clean[col].fillna('unknown')" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "def check_duplicates(df):\n", + " duplicates = df.duplicated().sum()\n", + " print(f\"Number of Duplicate Samples: {duplicates}\")\n", + " if duplicates > 0:\n", + " print(\"Dropping Duplicates...\")\n", + " df.drop_duplicates(inplace=True)\n", + " print(\"Duplicates Dropped.\")\n", + " else:\n", + " print(\"No Duplicate Samples Found.\")\n", + "\n", + "check_duplicates(df)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "categorical_cols = df.select_dtypes(include=[\"object\"]).columns\n", + "\n", + "print(\"Categorical Columns:\", list(categorical_cols))\n", + "from sklearn.preprocessing import LabelEncoder\n", + "\n", + "label_encoders = {}\n", + "for col in categorical_cols:\n", + " le = LabelEncoder()\n", + " df[col] = le.fit_transform(df[col])\n", + " label_encoders[col] = le\n", + "\n", + "df" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "from sklearn.preprocessing import StandardScaler\n", + "\n", + "numerical_cols = df.select_dtypes(include=[\"int64\", \"float64\"]).columns.drop(\"Delivery_Time\")\n", + "\n", + "scaler = StandardScaler()\n", + "df[numerical_cols] = scaler.fit_transform(df[numerical_cols])\n", + "df.head()\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import seaborn as sns\n", + "import matplotlib.pyplot as plt\n", + "def check_target_imbalance(df, target_column):\n", + " print(\"Target Distribution:\")\n", + " print(df[target_column].value_counts(normalize=True))\n", + " sns.countplot(x=df[target_column])\n", + " plt.title(\"Target Distribution\")\n", + " plt.show()\n", + "\n", + "check_target_imbalance(df, \"Target\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "X = df.drop(\"Target\", axis=1).astype(float)\n", + "y = df['Target'].astype(float)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "from sklearn.model_selection import train_test_split, StratifiedKFold\n", + "from sklearn.preprocessing import StandardScaler, LabelEncoder\n", + "from sklearn.ensemble import CatBoostClassifie\n", + "from sklearn.metrics import f1_score, accuracy_score\n", + "import numpy as np\n", + "model = RandomForestRegressor(n_estimators=100, max_depth=20, random_state=42, n_jobs=-1)\n", + "n_splits = 5 # K\n", + "skf = StratifiedKFold(n_splits=n_splits, shuffle=True, random_state=42)\n", + "for fold_idx, (train_index, test_index) in enumerate(skf.split(X, y)):\n", + " print(f\"\\nFold {fold_idx + 1}/{n_splits}\")\n", + "\n", + " # 1. Split data\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", + " # Train\n", + " model.fit(X_train, y_train)\n", + "\n", + " # Predict\n", + " y_pred = model.predict(X_test)\n", + " accuracy = accuracy_score(y_test, y_pred)\n", + "\n", + " f1 = f1_score(y_test, y_pred, zero_division=0)\n", + "\n", + "\n", + "\n", + "print(\"Model trained!\")\n", + "y_pred = model.predict(X_test)\n", + "\n", + "print(f\"MAE: ${mae:,.2f}\")\n", + "\n", + "average_losses = np.mean(lr_mae, axis=0)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "plt.figure(figsize=(7, 5))\n", + "\n", + "plt.plot(train_losses, label='Train Loss')\n", + "plt.plot(val_losses, label='Validation Loss')\n", + "plt.title('Loss over Epochs')\n", + "plt.xlabel('Epoch')\n", + "plt.ylabel('Loss')\n", + "plt.legend()\n", + "\n", + "plt.tight_layout()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "df['golden feature'].value_counts().head(1)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/446/Q1.ipynb b/submissions_extracted/446/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..914e864fd81e89f978d031da7b3ce5e51ec7d17f --- /dev/null +++ b/submissions_extracted/446/Q1.ipynb @@ -0,0 +1,308 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "import pandas as pd\n", + "import numpy as np\n", + "import os\n", + "import matplotlib.pyplot as plt\n", + "\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q1-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "csv_path = os.path.join(path, \"Q1_data.csv\")\n", + "df = pd.read_csv(csv_path)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "df.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "df.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "def check_target_distribution(df, target_column):\n", + " df[target_column].hist(bins=30, edgecolor='black')\n", + "\n", + " plt.title(f\"Target Distribution ({target_column})\")\n", + " plt.xlabel(target_column)\n", + " plt.ylabel(\"Frequency\")\n", + " plt.grid(False)\n", + "\n", + " plt.show()\n", + "\n", + "check_target_distribution(df, \"Delivery_Time\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "df = df.drop(columns=\"Order_ID\", axis=1)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "def check_missing_values(df):\n", + " missing_values = df.isnull().sum()\n", + " print(\"Missing Values per Column:\")\n", + " print(missing_values[missing_values > 0])\n", + " if missing_values.any():\n", + " print(\"\\nHandle Missing Values as needed.\")\n", + " else:\n", + " print(\"\\nNo Missing Values Found.\")\n", + "\n", + "\n", + "\n", + "\n", + "# check_missing_values(df)\n", + "df_clean = df.copy()\n", + "\n", + "df_clean['Weather'] = df_clean['Weather'].fillna(df_clean['Weather'].mode()[0])\n", + "df_clean['Traffic_Level'] = df_clean['Traffic_Level'].fillna(df_clean['Traffic_Level'].mode()[0])\n", + "df_clean['Time_of_Day'] = df_clean['Time_of_Day'].fillna(df_clean['Time_of_Day'].mode()[0])\n", + "df_clean['Courier_Experience_yrs'] = df_clean['Courier_Experience_yrs'].fillna(df_clean['Courier_Experience_yrs'].mean())\n", + "df_clean['Delivery_Time'] = df_clean['Delivery_Time'].fillna(df_clean['Delivery_Time'].mean())\n", + "\n", + "check_missing_values(df_clean)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "def check_duplicates(df):\n", + " duplicates = df.duplicated().sum()\n", + " print(f\"Number of Duplicate Samples: {duplicates}\")\n", + " if duplicates > 0:\n", + " print(\"Dropping Duplicates...\")\n", + " df.drop_duplicates(inplace=True)\n", + " print(\"Duplicates Dropped.\")\n", + " else:\n", + " print(\"No Duplicate Samples Found.\")\n", + "\n", + "check_duplicates(df_clean)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "from sklearn.preprocessing import LabelEncoder\n", + "\n", + "categorical_cols = df_clean.select_dtypes(include=[\"object\"]).columns\n", + "\n", + "label_encoders = {}\n", + "for col in categorical_cols:\n", + " le = LabelEncoder()\n", + " df_clean[col] = le.fit_transform(df_clean[col])\n", + " label_encoders[col] = le\n", + "\n", + "df_clean" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "from sklearn.preprocessing import StandardScaler\n", + "from sklearn.model_selection import train_test_split\n", + "\n", + "feature_cols = ['Distance_km', 'Weather', 'Traffic_Level', 'Time_of_Day',\n", + " 'Vehicle_Type', 'Preparation_Time_min', 'Courier_Experience_yrs']\n", + "\n", + "X = df_clean[feature_cols]\n", + "y = df_clean['Delivery_Time']\n", + "\n", + "\n", + "scaler = StandardScaler()\n", + "X_scaled = scaler.fit_transform(X, y)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 6: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "from sklearn.model_selection import KFold\n", + "from sklearn.ensemble import RandomForestRegressor\n", + "from sklearn.metrics import mean_absolute_error\n", + "\n", + "\n", + "n_splits = 5\n", + "\n", + "kfold = KFold(n_splits=n_splits, shuffle=True, random_state=42)\n", + "model = RandomForestRegressor(n_estimators=100, max_depth=20, random_state=42, n_jobs=-1)\n", + "\n", + "mae_scores = []\n", + "\n", + "for fold_idx, (train_index, test_index) in enumerate(kfold.split(X)):\n", + " print(f\"\\nFold {fold_idx + 1}/{n_splits}\")\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", + " # Train\n", + " model.fit(X_train, y_train)\n", + "\n", + " # Predict\n", + " y_pred = model.predict(X_test)\n", + " mae_scores.append(mean_absolute_error(y_test, y_pred))\n", + "\n", + "\n", + "\n", + "mae_scores = np.array(mae_scores)\n", + "\n", + "avg_loss = np.mean(mae_scores, axis=0)\n", + "\n", + "print(avg_loss)\n", + "\n", + "baseline_pred = np.full_like(y, y.mean())\n", + "\n", + "# Evaluate the baseline\n", + "baseline_mae = mean_absolute_error(y_test, y_pred)\n", + "\n", + "print(f\"Baseline MAE (using mean target): {baseline_mae:.4f}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:\n", + "from sklearn.ensemble import RandomForestRegressor\n", + "from sklearn.metrics import mean_absolute_error\n", + "from sklearn.model_selection import KFold\n", + "\n", + "# All Done Above!\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "# Feature importance\n", + "feature_importance = pd.DataFrame({\n", + " 'feature': feature_cols,\n", + " 'importance': model.feature_importances_\n", + "}).sort_values('importance', ascending=False)\n", + "\n", + "plt.figure(figsize=(10, 6))\n", + "plt.barh(feature_importance['feature'], feature_importance['importance'])\n", + "plt.xlabel('Importance')\n", + "plt.title('Feature Importance')\n", + "plt.gca().invert_yaxis()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/446/Q2.ipynb b/submissions_extracted/446/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..91167a4fb9ae0eba70fc10633c410f3cb2d9f939 --- /dev/null +++ b/submissions_extracted/446/Q2.ipynb @@ -0,0 +1,371 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q2-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import os\n", + "import pandas as pd\n", + "import numpy as np\n", + "from PIL import Image\n", + "from sklearn.model_selection import train_test_split\n", + "\n", + "# Load Labels\n", + "labels_df = pd.read_csv(os.path.join(path, \"labels.csv\"))\n", + "img_dir = os.path.join(path, \"images\")\n", + "\n", + "images = []\n", + "ages = []\n", + "\n", + "# Load Images and Resize\n", + "print(\"Loading images...\")\n", + "for index, row in labels_df.iterrows():\n", + " img_name = row.iloc[0]\n", + " age = row.iloc[1]\n", + " img_path = os.path.join(img_dir, img_name)\n", + "\n", + " if os.path.exists(img_path):\n", + " img = Image.open(img_path).convert('RGB')\n", + " img_array = np.array(img) / 255.0 # Normalize pixel values to [0, 1]\n", + " images.append(img_array)\n", + " ages.append(age)\n", + "\n", + "X = np.array(images)\n", + "y = np.array(ages)\n", + "\n", + "# Transpose image dimensions to match PyTorch format (N, C, H, W)\n", + "X = np.transpose(X, (0, 3, 1, 2))\n", + "\n", + "# Split Data\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n", + "\n", + "print(f\"X_train shape: {X_train.shape}\")\n", + "print(f\"X_test shape: {X_test.shape}\")\n", + "print(f\"y_train shape: {y_train.shape}\")\n", + "print(f\"y_test shape: {y_test.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 1. Convert Numpy arrays to PyTorch Tensors\n", + "from sklearn.preprocessing import StandardScaler\n", + "import torch\n", + "from torch.utils.data import TensorDataset\n", + "from torch.utils.data import DataLoader\n", + "\n", + "\n", + "\n", + "# transform to tensors\n", + "X_train = torch.tensor(X_train, dtype=torch.float32)\n", + "X_test = torch.tensor(X_test, dtype=torch.float32)\n", + "y_train = torch.tensor(y_train, dtype=torch.float32)\n", + "y_test = torch.tensor(y_test, dtype=torch.float32)\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 2. Create TensorDataset objects\n", + "train_dataset = TensorDataset(X_train, y_train)\n", + "test_dataset = TensorDataset(X_test, y_test)\n", + "\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 3. Create DataLoaders\n", + "from torch.utils.data import DataLoader\n", + "\n", + "\n", + "# DataLoader for training data\n", + "train_loader = DataLoader(train_dataset, batch_size=32, shuffle=True, num_workers=2)\n", + "# DataLoader for test data\n", + "test_loader = DataLoader(test_dataset, batch_size=32, shuffle=False, num_workers=2)\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 4. Print shape of one batch\n", + "sample_image, sample_label = train_dataset[0]\n", + "print(f\"Image shape: {sample_image.shape}\")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 5. Display sample images\n", + "import matplotlib.pyplot as plt\n", + "\n", + "\n", + "images, labels = next(iter(train_loader))\n", + "\n", + "# Display the first 6 images in the batch\n", + "plt.figure(figsize=(8, 4))\n", + "\n", + "for i in range(6):\n", + " plt.subplot(2, 3, i + 1)\n", + "\n", + " # Convert from (C, H, W) to (H, W, C) for matplotlib\n", + " img = images[i].permute(1, 2, 0)\n", + "\n", + " plt.imshow(img)\n", + " plt.title(f\"Label: {labels[i].item()}\")\n", + " plt.axis('off')\n", + "\n", + "plt.tight_layout()\n", + "plt.show()\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your model class here:\n", + "import torch.nn as nn\n", + "import torch.nn.functional as F\n", + "from torch.optim import AdamW\n", + "\n", + "class NN4Layer(nn.Module):\n", + "\n", + " def __init__(self, input_dim, hidden_dim, output_dim):\n", + " super(NN4Layer, self).__init__()\n", + "\n", + " self.layer1 = nn.Linear(input_dim, hidden_dim)\n", + " self.layer2 = nn.Linear(hidden_dim, hidden_dim)\n", + " self.layer3 = nn.Linear(hidden_dim, hidden_dim)\n", + " self.layer4 = nn.Linear(hidden_dim, output_dim)\n", + "\n", + " # activation function for non-linearity\n", + " self.relu = nn.ReLU()\n", + "\n", + " # Defines how input data flows through the network\n", + " def forward(self, x):\n", + " z1 = self.layer1(x)\n", + " a1 = self.relu(z1)\n", + "\n", + " z2 = self.layer2(a1)\n", + " a2 = self.relu(z2)\n", + "\n", + " z3 = self.layer3(a2)\n", + " a3 = self.relu(z3)\n", + "\n", + " z4 = self.layer4(a3)\n", + "\n", + " return z4" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your training loop here:\n", + "def train_one_epoch(model, optimizer, criterion, train_loader, device):\n", + " # Set the model to training mode\n", + " model.train()\n", + "\n", + " running_loss = 0.0\n", + "\n", + " for X_batch, y_batch in train_loader:\n", + " # Move batch to the selected device\n", + " X_batch = X_batch.view(X_batch.size(0), -1).to(device)\n", + " y_batch = y_batch.to(device)\n", + "\n", + " # Forward pass\n", + " outputs = model(X_batch)\n", + " loss = criterion(outputs, y_batch)\n", + "\n", + " # Backward pass & optimization\n", + " optimizer.zero_grad() # Clear previous gradients\n", + " loss.backward() # Compute gradients\n", + " optimizer.step() # Update model parameters\n", + "\n", + " running_loss += loss.item()\n", + "\n", + " # Average loss over all batches\n", + " avg_loss = running_loss / len(train_loader)\n", + "\n", + " return avg_loss" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your validation loop here:\n", + "def validate(model, criterion, test_loader, device):\n", + " # Set the model to evaluation mode\n", + " model.eval()\n", + "\n", + " running_loss = 0.0\n", + " correct = 0\n", + " total = 0\n", + "\n", + " with torch.no_grad():\n", + " for X_batch, y_batch in test_loader:\n", + " # Move data to device\n", + " X_batch = X_batch.view(X_batch.size(0), -1).to(device)\n", + " y_batch = y_batch.to(device)\n", + "\n", + " # Forward pass\n", + " outputs = model(X_batch)\n", + "\n", + " loss = criterion(outputs, y_batch)\n", + " running_loss += loss.item()\n", + "\n", + " probabilities = F.softmax(outputs, dim=1)\n", + "\n", + " predicted = torch.argmax(probabilities, dim=1)\n", + "\n", + " # Accuracy calculation\n", + " correct += (predicted == y_batch).sum().item()\n", + " total += y_batch.size(0)\n", + "\n", + " avg_loss = running_loss / len(test_loader)\n", + " accuracy = correct / total\n", + "\n", + " return avg_loss, accuracy" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Define device, model, loss, optimizer:\n", + "# Device setup\n", + "device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n", + "\n", + "# Model parameters\n", + "input_dim = 3 * 36 * 36\n", + "\n", + "hidden_dim = 64 # Design choice\n", + "output_dim = 10\n", + "\n", + "model = NN4Layer(input_dim, hidden_dim, output_dim).to(device)\n", + "\n", + "print(\"Model Architecture:\\n\")\n", + "print(model)\n", + "\n", + "num_epochs = 20\n", + "learning_rate = 0.001\n", + "\n", + "criterion = nn.CrossEntropyLoss()\n", + "optimizer = AdamW(model.parameters(), learning_rate)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Start training for 20 epochs:\n", + "# Run Training\n", + "train_losses = []\n", + "val_losses = []\n", + "val_accuracies = []\n", + "\n", + "print('Starting Training...')\n", + "for epoch in range(num_epochs):\n", + " # Train one epoch\n", + " train_loss = train_one_epoch(model, optimizer, criterion, train_loader, device)\n", + "\n", + " # Validate\n", + " val_loss, val_accuracy = validate(model, criterion, test_loader, device)\n", + "\n", + " train_losses.append(train_loss)\n", + " val_losses.append(val_loss)\n", + " val_accuracies.append(val_accuracy)\n", + "\n", + " print(f'Epoch [{epoch+1}/{num_epochs}], Train Loss: {train_loss:.4f}, Val Loss: {val_loss:.4f}, Val Accuracy: {val_accuracy:.4f}')\n", + "\n", + "print('Training Complete!')" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "# Plotting results\n", + "plt.figure(figsize=(7, 5))\n", + "\n", + "plt.plot(train_losses, label='Train Loss')\n", + "plt.plot(val_losses, label='Validation Loss')\n", + "plt.title('Loss over Epochs')\n", + "plt.xlabel('Epoch')\n", + "plt.ylabel('Loss')\n", + "plt.legend()\n", + "\n", + "plt.tight_layout()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2 (Bonus): Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/446/Q3.ipynb b/submissions_extracted/446/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..2fe305005c22e401262d825044bc84c646e5c434 --- /dev/null +++ b/submissions_extracted/446/Q3.ipynb @@ -0,0 +1,309 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "import os\n", + "import pandas as pd\n", + "import matplotlib.pyplot as plt\n", + "\n", + "\n", + "%pip install kagglehub catboost xgboost tqdm -q\n", + "\n", + "\n", + "# Download latest version\n", + "\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q3-exam-data\")\n", + "\n", + "\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "csv_path = os.path.join(path, \"Q3_data.csv\")\n", + "df = pd.read_csv(csv_path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "df.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "df.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# # Task 1: Write your code here:\n", + "import numpy as np\n", + "\n", + "\n", + "df_clean = df.copy()\n", + "\n", + "feature_cols = []\n", + "\n", + "def delete_missings(df):\n", + " for i in df:\n", + " df[str(i)] = df[str(i)].fillna(df[str(i)].mean())\n", + " if str(i) != \"Target\":\n", + " feature_cols.append(i)\n", + "\n", + " # for i in df:\n", + " # if sum(df[str(i)]) == 0:\n", + " # df.drop(columns=[str(i)])\n", + "\n", + "delete_missings(df_clean)\n", + "print(df_clean.isnull().sum())\n", + "print(type(feature_cols))\n", + "\n", + "\n", + "# Cleaned!\n", + "\n", + "# I could have also deleted columns that have zeros, but I forgot and I can't use google to know :)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "def check_duplicates(df):\n", + " duplicates = df.duplicated().sum()\n", + " print(f\"Number of Duplicate Samples: {duplicates}\")\n", + " if duplicates > 0:\n", + " print(\"Dropping Duplicates...\")\n", + " df.drop_duplicates(inplace=True)\n", + " print(\"Duplicates Dropped.\")\n", + " else:\n", + " print(\"No Duplicate Samples Found.\")\n", + "\n", + "check_duplicates(df_clean)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "\n", + "from sklearn.preprocessing import LabelEncoder\n", + "\n", + "categorical_cols = df_clean.select_dtypes(include=[\"object\"]).columns\n", + "\n", + "label_encoders = {}\n", + "for col in categorical_cols:\n", + " le = LabelEncoder()\n", + " df_clean[col] = le.fit_transform(df_clean[col])\n", + " label_encoders[col] = le\n", + "\n", + "df_clean" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "from sklearn.preprocessing import StandardScaler\n", + "from sklearn.model_selection import train_test_split\n", + "\n", + "X = df_clean[feature_cols]\n", + "y = df_clean['Target']\n", + "\n", + "\n", + "scaler = StandardScaler()\n", + "X_scaled = scaler.fit_transform(X, y)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "\n", + "def check_target_distribution(df, target_column):\n", + " df[target_column].hist(bins=30, edgecolor='black')\n", + "\n", + " plt.title(f\"Target Distribution ({target_column})\")\n", + " plt.xlabel(target_column)\n", + " plt.ylabel(\"Frequency\")\n", + " plt.grid(False)\n", + "\n", + " plt.show()\n", + "\n", + "check_target_distribution(df, \"Target\")\n", + "\n", + "# Not balanced (before)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "# Task 1: Write your code here:\n", + "from sklearn.model_selection import KFold\n", + "from sklearn.metrics import accuracy_score, f1_score\n", + "import numpy as np\n", + "from catboost import CatBoostClassifier\n", + "\n", + "\n", + "n_splits = 5\n", + "\n", + "kfold = KFold(n_splits=n_splits, shuffle=True, random_state=42)\n", + "model = CatBoostClassifier(\n", + " verbose=0,\n", + " n_estimators=320,\n", + " max_depth=4\n", + " )\n", + "\n", + "accuracy_scores = []\n", + "f1_scores = []\n", + "\n", + "for fold_idx, (train_index, test_index) in enumerate(kfold.split(X)):\n", + " print(f\"\\nFold {fold_idx + 1}/{n_splits}\")\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", + " # Train\n", + " model.fit(X_train, y_train)\n", + "\n", + " # Predict\n", + " y_pred = model.predict(X_test)\n", + "\n", + " accuracy = accuracy_score(y_test, y_pred)\n", + " f1 = f1_score(y_test, y_pred, zero_division=0)\n", + "\n", + "\n", + "\n", + "accuracy_scores = np.array(accuracy_scores)\n", + "f1_scores = np.array(f1_scores)\n", + "print(f1_scores)\n", + "print(accuracy_scores)\n", + "\n", + "avg_loss = np.mean(f1_scores, axis=0)\n", + "\n", + "print(avg_loss)\n", + "\n", + "baseline_pred = np.full_like(y, y.mean())\n", + "\n", + "# Evaluate the baseline\n", + "baseline_mae = f1_score(y_test, y_pred)\n", + "\n", + "print(f\"Baseline F1 (using f1 score): {baseline_mae:.4f}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:\n", + "\n", + "# All Done Above" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "\n", + "# Feature importance\n", + "feature_importance = pd.DataFrame({\n", + " 'feature': feature_cols,\n", + " 'importance': model.feature_importances_\n", + "}).sort_values('importance', ascending=False)\n", + "\n", + "plt.figure(figsize=(100, 60))\n", + "plt.barh(feature_importance['feature'], feature_importance['importance'])\n", + "plt.xlabel('Importance')\n", + "plt.title('Feature Importance')\n", + "plt.gca().invert_yaxis()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "\n", + "# The Golden Feature is P2!!" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/447/Q1.ipynb b/submissions_extracted/447/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..1d1f3673e3a2265f9fc760530912bff0f691f920 --- /dev/null +++ b/submissions_extracted/447/Q1.ipynb @@ -0,0 +1,302 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q1-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "#importing libraries\n", + "import os\n", + "import pandas as pd\n", + "import numpy as np\n", + "\n", + "#load data\n", + "csv_path = os.path.join(path, \"Q1_data.csv\")\n", + "df = pd.read_csv(csv_path)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "# Print first 5 rows\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "df.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "df.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "\n", + "#import plt library\n", + "import matplotlib.pyplot as plt\n", + "\n", + "\n", + "df['Delivery_Time'].hist(bins=30, edgecolor='black')\n", + "plt.title(f\"Target Distribution ({'Delivery_Time'})\")\n", + "plt.xlabel('Delivery_Time')\n", + "plt.ylabel(\"Frequency\")\n", + "plt.grid(False)\n", + "\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "df = df.drop(['Order_ID'], axis=1)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "\n", + "#first we check for missing values per column\n", + "def check_missing_values(df):\n", + " missing_values = df.isnull().sum()\n", + " print(\"Missing Values per Column:\")\n", + " print(missing_values[missing_values > 0])\n", + " if missing_values.any():\n", + " print(\"\\nthere are missing values\")\n", + " else:\n", + " print(\"\\nNo Missing Values Found.\")\n", + "\n", + "check_missing_values(df)\n", + "\n", + "\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "#subtask 2\n", + "# they are : [Weather, Traffic_Level, Time_of_Day, Courier_Experience_yrs]\n", + "df['Courier_Experience_yrs'] = df['Courier_Experience_yrs'].fillna(df['Courier_Experience_yrs'].median())\n", + "df['Delivery_Time'] = df['Delivery_Time'].fillna(df['Delivery_Time'].median())\n", + "df['Weather'] = df['Weather'].fillna(df['Weather'].median())\n", + "df['Traffic_Level'] = df['Traffic_Level'].fillna(df['Traffic_Level'].median())\n", + "df['Time_of_Day'] = df['Time_of_Day'].fillna(df['Time_of_Day'].median())\n", + "check_missing_values(df)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "\n", + "#check dublicates\n", + "duplicates = df.duplicated().sum()\n", + "print(f\"Duplicates: {duplicates}\")\n", + "\n", + "#remove them\n", + "df.drop_duplicates(inplace=True)\n", + "df.info()\n", + "\n", + "\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "from sklearn.preprocessing import LabelEncoder\n", + "label_encoder = LabelEncoder() # Instantiate LabelEncoder\n", + "\n", + "df['Weather'] = label_encoder.fit_transform(df['Weather'])\n", + "df['Traffic_Level'] = label_encoder.fit_transform(df['Traffic_Level'])\n", + "df['Time_of_Day'] = label_encoder.fit_transform(df['Time_of_Day'])\n", + "df['Vehicle_Type'] = label_encoder.fit_transform(df['Vehicle_Type'])" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "from sklearn.preprocessing import MinMaxScaler\n", + "\n", + "features = df.columns.drop(\"Delivery_Time\") # we don't scale the target\n", + "\n", + "scaler = MinMaxScaler()\n", + "df[features] = scaler.fit_transform(df[features])\n", + "df.head()\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 6: Write your code here:\n", + "df['Delivery_Time'].hist()\n", + "#data appears to be imbalancced" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "from sklearn.model_selection import StratifiedKFold, train_test_split\n", + "X = df.drop(['Delivery_Time'], axis=1)\n", + "y = df['Delivery_Time']" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:\n", + "from sklearn.model_selection import KFold\n", + "from sklearn.ensemble import RandomForestRegressor\n", + "from sklearn.metrics import mean_squared_error as mean_absolute_error\n", + "\n", + "#initialize the model\n", + "model = RandomForestRegressor(n_estimators=100, max_depth=5, random_state=42)\n", + "\n", + "#initialize k-fold\n", + "kf = KFold(n_splits=5, shuffle=True, random_state=42)\n", + "\n", + "\n", + "# Iterate through folds\n", + "for fold, (train_idx, test_idx) in enumerate(kf.split(X), start=1):\n", + " # indexing for each fold\n", + " X_train, X_test = X.iloc[train_idx], X.iloc[test_idx]\n", + " y_train, y_test = y.iloc[train_idx], y.iloc[test_idx]\n", + "\n", + " model.fit(X_train, y_train) #fit\n", + " y_pred = model.predict(X_test) #prediction\n", + " mae = mean_absolute_error(y_test, y_pred) # absolute erro\n", + " print(\"Random Forest MAE:\", mae)\n", + "#1 hour left... guess those errors are going to stay\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "# Feature columns\n", + "feature_cols = ['Distance_km'\t,'Weather'\t,'Traffic_Level',\t'Time_of_Day'\t,'Vehicle_Type',\t'Preparation_Time_min'\t,'Courier_Experience_yrs'\t]\n", + "\n", + "feature_importance = pd.DataFrame({\n", + " 'feature': feature_cols,\n", + " 'importance': model.feature_importances_\n", + "}).sort_values('importance', ascending=False)\n", + "\n", + "plt.figure(figsize=(10, 6))\n", + "plt.barh(feature_importance['feature'], feature_importance['importance'])\n", + "plt.xlabel('Importance')\n", + "plt.title('Feature Importance')\n", + "plt.gca().invert_yaxis()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "plt.figure(figsize=(10, 5))\n", + "plt.hist(y_pred, bins=50, edgecolor='black')\n", + "plt.title('predicted delivery time Histogram')\n", + "plt.xlabel('delivery time')\n", + "plt.ylabel('Frequency')\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/447/Q2.ipynb b/submissions_extracted/447/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..338be70b1f3cfbe55801c56b07b0c8ccc5567e0a --- /dev/null +++ b/submissions_extracted/447/Q2.ipynb @@ -0,0 +1,380 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q2-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import os\n", + "import pandas as pd\n", + "import numpy as np\n", + "from PIL import Image\n", + "from sklearn.model_selection import train_test_split\n", + "\n", + "# Load Labels\n", + "labels_df = pd.read_csv(os.path.join(path, \"labels.csv\"))\n", + "img_dir = os.path.join(path, \"images\")\n", + "\n", + "images = []\n", + "ages = []\n", + "\n", + "# Load Images and Resize\n", + "print(\"Loading images...\")\n", + "for index, row in labels_df.iterrows():\n", + " img_name = row.iloc[0]\n", + " age = row.iloc[1]\n", + " img_path = os.path.join(img_dir, img_name)\n", + "\n", + " if os.path.exists(img_path):\n", + " img = Image.open(img_path).convert('RGB')\n", + " img_array = np.array(img) / 255.0 # Normalize pixel values to [0, 1]\n", + " images.append(img_array)\n", + " ages.append(age)\n", + "\n", + "X = np.array(images)\n", + "y = np.array(ages)\n", + "\n", + "# Transpose image dimensions to match PyTorch format (N, C, H, W)\n", + "X = np.transpose(X, (0, 3, 1, 2))\n", + "\n", + "# Split Data\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n", + "\n", + "print(f\"X_train shape: {X_train.shape}\")\n", + "print(f\"X_test shape: {X_test.shape}\")\n", + "print(f\"y_train shape: {y_train.shape}\")\n", + "print(f\"y_test shape: {y_test.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 1. Convert Numpy arrays to PyTorch Tensors\n", + "#import the library\n", + "import torch\n", + "#transform\n", + "X_train = torch.tensor(X_train, dtype=torch.float32)\n", + "X_test = torch.tensor(X_test, dtype=torch.float32)\n", + "y_train = torch.tensor(y_train, dtype=torch.float32)\n", + "y_test = torch.tensor(y_test, dtype=torch.float32)\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 2. Create TensorDataset objects\n", + "#import library\n", + "from torch.utils.data import TensorDataset\n", + "#create datasets\n", + "train_dataset = TensorDataset(X_train, y_train)\n", + "test_dataset = TensorDataset(X_test, y_test)\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 3. Create DataLoaders\n", + "#import libraries\n", + "from torch.utils.data import DataLoader\n", + "#create dataloaders\n", + "train_loader = DataLoader(\n", + " train_dataset,\n", + " batch_size=32,\n", + " shuffle=True,\n", + " num_workers=2\n", + ")\n", + "# DataLoader for test/validation data\n", + "test_loader = DataLoader(\n", + " test_dataset,\n", + " batch_size=32,\n", + " shuffle=False,\n", + " num_workers=2\n", + ")\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 4. Print shape of one batch\n", + "# Get the first batch from the training DataLoader\n", + "X_batch, y_batch = next(iter(train_loader))\n", + "#print it\n", + "print(f\"Training batch input shape: {X_batch.shape}\")\n", + "print(f\"Training batch labels shape: {y_batch.shape}\")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 5. Display sample images\n", + "#import plotter\n", + "import matplotlib.pyplot as plt\n", + "# Get one batch of images and labels\n", + "images, labels = next(iter(train_loader))\n", + "\n", + "# Display the first 6 images in the batch\n", + "plt.figure(figsize=(8, 4))\n", + "\n", + "for i in range(6):\n", + " plt.subplot(2, 3, i + 1)\n", + " plt.imshow(images[i].squeeze(), cmap='gray')\n", + " plt.title(f\"Label: {labels[i].item()}\")\n", + " plt.axis('off')\n", + "\n", + "plt.tight_layout()\n", + "plt.show()\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your model class here:\n", + "#import all libraries\n", + "import torch.nn as nn #nn\n", + "from torch.optim import Adam #optimizer\n", + "import matplotlib.pyplot as plt #plotter\n", + "#the class\n", + "class NN4Layer(nn.Module):\n", + "\n", + " def __init__(self, input_dim, hidden_dim, output_dim):\n", + " super(NN4Layer, self).__init__()\n", + "\n", + " # First linear layer: input features -> hidden layer\n", + " self.layer1 = nn.Linear(input_dim, hidden_dim)\n", + "\n", + " # Second linear layer: hidden layer -> hidden layer\n", + " self.layer2 = nn.Linear(hidden_dim, hidden_dim)\n", + "\n", + " # Third linear layer: hidden layer -> hidden layer\n", + " self.layer3 = nn.Linear(hidden_dim, hidden_dim)\n", + "\n", + " # Output layer: hidden layer -> number of classes (logits)\n", + " self.layer4 = nn.Linear(hidden_dim, output_dim)\n", + "\n", + " # ReLU activation for non-linearity\n", + " self.relu = nn.ReLU()\n", + "\n", + "#forward pass\n", + " def forward(self, x):\n", + " # First hidden layer\n", + " a1 = self.relu(self.layer1(x))\n", + "\n", + " # Second hidden layer\n", + " a2 = self.relu(self.layer2(a1))\n", + "\n", + " # Third hidden layer\n", + " a3 = self.relu(self.layer3(a2))\n", + "\n", + " # Output layer (raw scores / logits)\n", + " output = self.layer4(a3) # we said we'll use softmax, where is it? ¯\\(ツ)/¯\n", + "\n", + " return output" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your training loop here:\n", + "def train_one_epoch(model, optimizer, criterion, train_loader, device):\n", + " # Set the model to training mode\n", + " model.train()\n", + "\n", + " running_loss = 0.0\n", + "\n", + " for X_batch, y_batch in train_loader:\n", + " # Move batch to the selected device\n", + " X_batch = X_batch.to(device)\n", + " y_batch = y_batch.view(-1, 1).to(device)\n", + "\n", + " # Forward pass\n", + " outputs = model(X_batch)\n", + " loss = criterion(outputs, y_batch)\n", + "\n", + " # Backward pass & optimization\n", + " optimizer.zero_grad() # Clear previous gradients\n", + " loss.backward() # Compute gradients\n", + " optimizer.step() # Update model parameters\n", + "\n", + " running_loss += loss.item()\n", + "\n", + " # Average loss over all batches\n", + " avg_loss = running_loss / len(train_loader)\n", + "\n", + " return avg_loss\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your validation loop here:\n", + "def validate(model, criterion, test_loader, device):\n", + " # Set the model to evaluation mode\n", + " model.eval()\n", + "\n", + " running_loss = 0.0\n", + " correct = 0\n", + " total = 0\n", + "\n", + " with torch.no_grad(): # Disable gradient computation\n", + " for X_batch, y_batch in test_loader:\n", + " # Move batch to the selected device\n", + " X_batch = X_batch.to(device)\n", + " y_batch = y_batch.view(-1, 1).to(device)\n", + "\n", + " # Forward pass\n", + " outputs = model(X_batch)\n", + " loss = criterion(outputs, y_batch)\n", + " running_loss += loss.item()\n", + "\n", + " # Binary predictions\n", + " predicted = (outputs > 0.5).float()\n", + "\n", + " # Accuracy calculation\n", + " correct += (predicted == y_batch).sum().item()\n", + " total += y_batch.size(0)\n", + "\n", + " avg_loss = running_loss / len(test_loader)\n", + " accuracy = correct / total\n", + "\n", + " return avg_loss, accuracy" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Define device, model, loss, optimizer:\n", + "#device\n", + "device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\n", + "#model parameters\n", + "input_dim = X_train.shape[1]\n", + "hidden_dim = 10\n", + "output_dim = 1\n", + "#model\n", + "model =NN4Layer(input_dim, hidden_dim,output_dim ).to(device)\n", + "#loss\n", + "criterion = nn.BCELoss()\n", + "#optimizer\n", + "learning_rate = 0.001\n", + "optimizer = Adam(model.parameters(), lr=learning_rate)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Start training for 20 epochs:\n", + "num_epochs = 20\n", + "# loss initialize\n", + "train_losses = []\n", + "val_losses = []\n", + "val_accuracies = []\n", + "#run training\n", + "\n", + "print('Starting Training...')\n", + "for epoch in range(num_epochs):\n", + " # Train one epoch\n", + " train_loss = train_one_epoch(model, optimizer, criterion, train_loader, device)\n", + "\n", + " # Validate\n", + " val_loss, val_accuracy = validate(model, criterion, test_loader, device)\n", + "\n", + " train_losses.append(train_loss)\n", + " val_losses.append(val_loss)\n", + " val_accuracies.append(val_accuracy)\n", + "\n", + " print(f'Epoch [{epoch+1}/{num_epochs}], Train Loss: {train_loss:.4f}, Val Loss: {val_loss:.4f}, Val Accuracy: {val_accuracy:.4f}')\n", + "\n", + "print('Training Complete!')" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "# Plotting results\n", + "plt.figure(figsize=(7, 5))\n", + "\n", + "plt.plot(train_losses, label='Train Loss')\n", + "plt.plot(val_losses, label='Validation Loss')\n", + "plt.title('Loss over Epochs')\n", + "plt.xlabel('Epoch')\n", + "plt.ylabel('Loss')\n", + "plt.legend()\n", + "\n", + "plt.tight_layout()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2 (Bonus): Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/447/Q3.ipynb b/submissions_extracted/447/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..c81df46464ddd6e05f5c4e03546ae5a1650cf53d --- /dev/null +++ b/submissions_extracted/447/Q3.ipynb @@ -0,0 +1,189 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "\n", + "\n", + "# Download latest version\n", + "\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q3-exam-data\")\n", + "\n", + "\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "#importing libraries\n", + "import os\n", + "import pandas as pd\n", + "import numpy as np\n", + "\n", + "#load data\n", + "csv_path = os.path.join(path, \"Q3_data.csv\")\n", + "df = pd.read_csv(csv_path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "df.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "df.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "def check_missing_values(df):\n", + " missing_values = df.isnull().sum()\n", + " print(\"Missing Values per Column:\")\n", + " print(missing_values[missing_values > 0])\n", + " if missing_values.any():\n", + " print(\"\\nthere are a lot of missing values\")\n", + " else:\n", + " print(\"\\nNo Missing Values Found.\")\n", + "\n", + "check_missing_values(df)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "#check dublicates\n", + "duplicates = df.duplicated().sum()\n", + "print(f\"Duplicates: {duplicates}\")\n", + "\n", + "#remove them\n", + "df.drop_duplicates(inplace=True)\n", + "df.info()\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "from sklearn.preprocessing import LabelEncoder" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/448/Q1.ipynb b/submissions_extracted/448/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..f7dad5e597a09b683285148bf647a908b188e5ea --- /dev/null +++ b/submissions_extracted/448/Q1.ipynb @@ -0,0 +1,275 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import numpy as np\n", + "import pandas as pd\n", + "import matplotlib.pyplot as plt\n", + "import os\n", + "import kagglehub\n", + "\n", + "from sklearn.model_selection import train_test_split, KFold\n", + "from sklearn.preprocessing import StandardScaler, LabelEncoder\n", + "from sklearn.ensemble import RandomForestRegressor\n", + "from sklearn.metrics import mean_absolute_error, mean_squared_error\n", + "\n", + "import warnings\n", + "warnings.filterwarnings('ignore')" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q1-exam-data\")\n", + "print(\"Path to dataset files:\", path)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "#reading the data\n", + "delivery_path = os.path.join(path, 'Q1_data.csv')\n", + "df_delivery = pd.read_csv(delivery_path)\n", + "print(f\"Dataset shape: {df_delivery}\")\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "#inspecting the first few rows of the data\n", + "df_delivery.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "#displaying the info\n", + "df_delivery.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "df_delivery.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "plt.figure(figsize=(10, 5))\n", + "plt.hist(df_delivery['Delivery_Time'].dropna(), bins=30, edgecolor='black')\n", + "plt.title('Delivery Time Distribution')\n", + "plt.xlabel('Delivery Time')\n", + "plt.ylabel('Count')\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "#dropping the column Order_ID using the drop function\n", + "df_delivery.columns.drop(\"Order_ID\")\n", + "\n", + "\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "#Checking for missing values and handling them\n", + "print(\"\\nMissing Values (df_delivery.isnull().sum()):\")\n", + "print(df_delivery.isnull().sum())\n", + "df_delivery.isnull().sum().fillna('unknown')\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "#checking for duplicates and handling them\n", + "def check_duplicates(df_delivery):\n", + " duplicates = df_delivery.duplicated().sum()\n", + " print(f\"Number of Duplicate Samples: {duplicates}\")\n", + " if duplicates > 0:\n", + " print(\"Dropping Duplicates...\")\n", + " df_delivery.drop_duplicates(inplace=True)\n", + " print(\"Duplicates Dropped.\")\n", + " else:\n", + " print(\"No Duplicate Samples Found.\")\n", + "\n", + "check_duplicates(df_delivery)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "categorical_cols = df_delivery.select_dtypes(include=[\"object\"]).columns\n", + "\n", + "print(\"Categorical Columns:\", list(categorical_cols))\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "standard_scaler = StandardScaler() # Instantiate StandardScaler\n", + "data_standard_scaled = standard_scaler.fit_transform(df_delivery) # Apply fit_transform\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 6: Write your code here:\n", + "def check_target_imbalance(df_delivery, target_column):\n", + " print(\"Target Distribution:\")\n", + "\n", + " df_delivery[target_column].hist()\n", + " plt.show()\n", + "\n", + "check_target_imbalance(df_delivery, \"Traffic_Level\")\n", + "#it is not imbalanced" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "delivery_cols = ['Distance_km', 'Weather', 'Traffic_Level', 'Time_of_Day', 'Vehicle_Type']\n", + "X = df_delivery[delivery_cols]\n", + "y = df_delivery['delivery_time']" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:\n", + "from sklearn.model_selection import KFold\n", + "\n", + "X = [delivery_cols]\n", + "y = [\"delivery_time\"]\n", + "\n", + "\n", + "# Use previously generated random data (example: regression data)\n", + "X, y = X.copy(), y.copy()\n", + "\n", + "# Define K-Fold Cross Validation\n", + "kf = KFold(n_splits=5, shuffle=True, random_state=42)\n", + "\n", + "# Iterate through folds\n", + "for fold, (train_idx, test_idx) in enumerate(kf.split(X), start=1):\n", + " # indexing for each fold\n", + " X_train, X_test = X.iloc[train_idx], X.iloc[test_idx]\n", + " y_train, y_test = y.iloc[train_idx], y.iloc[test_idx]\n", + " # print shapes\n", + " print(f\"Fold {fold}\")\n", + " print(\" X_train shape:\", X_train.shape)\n", + " print(\" X_test shape :\", X_test.shape)\n", + " print(\" y_train shape:\", y_train.shape)\n", + " print(\" y_test shape :\", y_test.shape)\n", + " print(\"-\" * 30)\n", + "\n", + "\n", + "\n", + "\n", + "" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/448/Q2.ipynb b/submissions_extracted/448/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..ab7f8cad3f496876cbcda88fd06f48c6aa2480fe --- /dev/null +++ b/submissions_extracted/448/Q2.ipynb @@ -0,0 +1,355 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "import pandas as pd\n", + "import torch\n", + "import torch.nn as nn\n", + "from torch.optim import AdamW\n", + "import matplotlib.pyplot as plt\n", + "import torch.nn.functional as F\n", + "from torch.utils.data import DataLoader, TensorDataset\n", + "from sklearn.model_selection import train_test_split\n", + "from sklearn.preprocessing import StandardScaler, LabelEncoder" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q2-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import os\n", + "import pandas as pd\n", + "import numpy as np\n", + "from PIL import Image\n", + "from sklearn.model_selection import train_test_split\n", + "\n", + "# Load Labels\n", + "labels_df = pd.read_csv(os.path.join(path, \"labels.csv\"))\n", + "img_dir = os.path.join(path, \"images\")\n", + "\n", + "images = []\n", + "ages = []\n", + "\n", + "# Load Images and Resize\n", + "print(\"Loading images...\")\n", + "for index, row in labels_df.iterrows():\n", + " img_name = row.iloc[0]\n", + " age = row.iloc[1]\n", + " img_path = os.path.join(img_dir, img_name)\n", + "\n", + " if os.path.exists(img_path):\n", + " img = Image.open(img_path).convert('RGB')\n", + " img_array = np.array(img) / 255.0 # Normalize pixel values to [0, 1]\n", + " images.append(img_array)\n", + " ages.append(age)\n", + "\n", + "X = np.array(images)\n", + "y = np.array(ages)\n", + "\n", + "# Transpose image dimensions to match PyTorch format (N, C, H, W)\n", + "X = np.transpose(X, (0, 3, 1, 2))\n", + "\n", + "# Split Data\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n", + "\n", + "print(f\"X_train shape: {X_train.shape}\")\n", + "print(f\"X_test shape: {X_test.shape}\")\n", + "print(f\"y_train shape: {y_train.shape}\")\n", + "print(f\"y_test shape: {y_test.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 1. Convert Numpy arrays to PyTorch Tensors\n", + "\n", + "X_train = torch.tensor(X_train, dtype=torch.float32)\n", + "X_test = torch.tensor(X_test, dtype=torch.float32)\n", + "y_train = torch.tensor(y_train, dtype=torch.float32)\n", + "y_test = torch.tensor(y_test, dtype=torch.float32)\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 2. Create TensorDataset objects\n", + "\n", + "\n", + "train_dataset = TensorDataset(X_train, y_train)\n", + "test_dataset = TensorDataset(X_test, y_test)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 3. Create DataLoaders\n", + "\n", + "\n", + "train_loader = DataLoader(train_dataset, batch_size=32, shuffle=True)\n", + "test_loader = DataLoader(test_dataset, batch_size=32, shuffle=False)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 4. Print shape of one batch\n", + "print(f\"Training batch input shape: {X_train.shape}\")\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 5. Display sample images\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your model class here:\n", + "class NN4Layer(nn.Module):\n", + "\n", + " def __init__(self, input_dim, hidden_dim, output_dim):\n", + " super(NN4Layer, self).__init__()\n", + "\n", + " # First linear layer: input features -> hidden layer\n", + " self.layer1 = nn.Linear(input_dim, hidden_dim)\n", + "\n", + " # Second linear layer: hidden layer -> hidden layer\n", + " self.layer2 = nn.Linear(hidden_dim, hidden_dim)\n", + "\n", + " # Third linear layer: hidden layer -> hidden layer\n", + " self.layer3 = nn.Linear(hidden_dim, hidden_dim)\n", + "\n", + " # Output layer: hidden layer -> number of classes (logits)\n", + " self.layer4 = nn.Linear(hidden_dim, output_dim)\n", + "\n", + " # ReLU activation for non-linearity\n", + " self.relu = nn.ReLU()\n", + "\n", + " # Defines how input data flows through the network\n", + " def forward(self, x):\n", + " # First hidden layer\n", + " a1 = self.relu(self.layer1(x))\n", + "\n", + " # Second hidden layer\n", + " a2 = self.relu(self.layer2(a1))\n", + "\n", + " # Third hidden layer\n", + " a3 = self.relu(self.layer3(a2))\n", + "\n", + " # Output layer (raw scores / logits)\n", + " output = self.layer4(a3) # we said we'll use softmax, where is it? ¯\\(ツ)/¯\n", + "\n", + " return output\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your training loop here:\n", + "def train_one_epoch(model, optimizer, criterion, train_loader, device):\n", + " # Set the model to training mode\n", + " model.train()\n", + "\n", + " running_loss = 0.0\n", + "\n", + " for X_batch, y_batch in train_loader:\n", + " # Move batch to the selected device\n", + " X_batch = X_batch.to(device)\n", + " y_batch = y_batch.view(-1, 1).to(device)\n", + "\n", + " # Forward pass\n", + " outputs = model(X_batch)\n", + " loss = criterion(outputs, y_batch)\n", + "\n", + " # Backward pass & optimization\n", + " optimizer.zero_grad() # Clear previous gradients\n", + " loss.backward() # Compute gradients\n", + " optimizer.step() # Update model parameters\n", + "\n", + " running_loss += loss.item()\n", + "\n", + " # Average loss over all batches\n", + " avg_loss = running_loss / len(train_loader)\n", + "\n", + " return avg_loss" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your validation loop here:\n", + "def validate(model, criterion, test_loader, device):\n", + " # Set the model to evaluation mode\n", + " model.eval()\n", + "\n", + " running_loss = 0.0\n", + " correct = 0\n", + " total = 0\n", + "\n", + " with torch.no_grad(): # Disable gradient computation\n", + " for X_batch, y_batch in test_loader:\n", + " # Move batch to the selected device\n", + " X_batch = X_batch.to(device)\n", + " y_batch = y_batch.view(-1, 1).to(device)\n", + "\n", + " # Forward pass\n", + " outputs = model(X_batch)\n", + " loss = criterion(outputs, y_batch)\n", + " running_loss += loss.item()\n", + "\n", + " # Binary predictions\n", + " predicted = (outputs > 0.5).float()\n", + "\n", + " # Accuracy calculation\n", + " correct += (predicted == y_batch).sum().item()\n", + " total += y_batch.size(0)\n", + "\n", + " avg_loss = running_loss / len(test_loader)\n", + " accuracy = correct / total\n", + "\n", + " return avg_loss, accuracy\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "from torch.optim import AdamW\n", + "# Task 4: Define device, model, loss, optimizer:\n", + "device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n", + "\n", + "# Model parameters\n", + "input_dim = X_train.shape[1] # Number of tabular features\n", + "hidden_dim = 14 # Design choice\n", + "output_dim = 4 # Weather classes: Rainy, Sunny, Cloudy, Snowy\n", + "\n", + "# Instantiate model\n", + "model = NN4Layer(input_dim, hidden_dim, output_dim).to(device)\n", + "\n", + "# Print the model architecture\n", + "print(\"Model:\\n\")\n", + "print(model)\n", + "\n", + "num_epochs = 20\n", + "learning_rate = 0.001\n", + "\n", + "# Defining loss\n", + "criterion = nn.CrossEntropyLoss()\n", + "\n", + "# Defining optimizer\n", + "optimizer = AdamW(model.parameters(), learning_rate)\n", + "\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Start training for 20 epochs:\n", + "\n", + "for epoch in range(num_epochs):\n", + " train_loss = train_one_epoch(model, optimizer, criterion, train_loader, device)\n", + " val_loss, val_accuracy = validate(model, criterion, test_loader, device)\n", + "\n", + " train_losses.append(train_loss)\n", + " val_losses.append(val_loss)\n", + " val_accuracies.append(val_accuracy)\n", + "\n", + " print(f'Epoch [{epoch+1}/{num_epochs}], Train Loss: {train_loss:.4f}, Val Loss: {val_loss:.4f}, Val Accuracy: {val_accuracy:.4f}')\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "plt.figure(figsize=(7, 5))\n", + "\n", + "plt.plot(train_losses, label='Train Loss')\n", + "plt.plot(val_losses, label='Validation Loss')\n", + "plt.title('Loss over Epochs')\n", + "plt.xlabel('Epoch')\n", + "plt.ylabel('Loss')\n", + "plt.legend()\n", + "\n", + "plt.tight_layout()\n", + "plt.show()\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2 (Bonus): Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/448/Q3.ipynb b/submissions_extracted/448/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..3cb18dfa6d58f05cf852f7304f7efe1df2f14ba5 --- /dev/null +++ b/submissions_extracted/448/Q3.ipynb @@ -0,0 +1,294 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import pandas as pd\n", + "import numpy as np\n", + "import matplotlib.pyplot as plt\n", + "import seaborn as sns\n", + "import kagglehub\n", + "import os\n", + "from tqdm import tqdm\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "\n", + "\n", + "# Download latest version\n", + "\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q3-exam-data\")\n", + "\n", + "\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "csv_path = os.path.join(path, \"Q3_data.csv\")\n", + "\n", + "df = pd.read_csv(csv_path)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "df.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "df.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "def check_missing_values(df):\n", + "\n", + " # Get missing values using pandas\n", + " missing_values = df.isnull().sum()\n", + "\n", + " print(\"Missing Values per Column:\")\n", + " print(missing_values[missing_values > 0])\n", + "\n", + " if missing_values.any():\n", + " print(\"\\nHandle Missing Values as needed.\")\n", + " else:\n", + " print(\"\\nNo Missing Values Found.\")\n", + "\n", + "check_missing_values(df)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "#handling missing values\n", + "df.isnull().sum().fillna('unknown')" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "print(\"Checking for duplicate rows...\")\n", + "duplicate_rows = df.duplicated().sum()\n", + "if duplicate_rows > 0:\n", + " print(f\"Found {duplicate_rows} duplicate rows. Removing them...\")\n", + " df.drop_duplicates(inplace=True)\n", + " print(\"Duplicate rows removed.\")\n", + "else:\n", + " print(\"No duplicate rows found.\")\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "categorical_cols = df.select_dtypes(include=[\"object\"]).columns\n", + "\n", + "print(\"Categorical Columns:\", list(categorical_cols))\n", + "#there are no categorical columns" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "from sklearn.preprocessing import StandardScaler\n", + "numerical_cols = df.select_dtypes(include=[\"number\"])\n", + "standard_scaler = StandardScaler() # Instantiate StandardScaler\n", + "data_standard_scaled = standard_scaler.fit_transform(numerical_cols)\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "\n", + "plt.figure(figsize=(6, 4))\n", + "sns.countplot(data=df, x='B_1')\n", + "plt.title('Distribution of Target Variable (B_1)')\n", + "plt.xlabel('B_1')\n", + "plt.ylabel('Distribution')\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "X = df.drop('Target', axis=1)\n", + "y = df['Target']" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:\n", + "from sklearn.model_selection import StratifiedKFold\n", + "from sklearn.model_selection import train_test_split, StratifiedKFold, cross_val_score\n", + "from sklearn.preprocessing import StandardScaler, LabelEncoder\n", + "from sklearn.ensemble import RandomForestClassifier\n", + "from sklearn.metrics import classification_report, confusion_matrix, accuracy_score\n", + "from sklearn.model_selection import KFold\n", + "\n", + "\n", + "\n", + "X, y = X.copy(), y.copy()\n", + "\n", + "# Show full dataset class distribution\n", + "full_ratio = (y.value_counts(normalize=True) * 100).sort_index()\n", + "print(\"Full Dataset Class Distribution\")\n", + "print(\" y class percentages:\", {k: f\"{v:.2f}%\" for k, v in full_ratio.items()})\n", + "print(\"-\" * 40)\n", + "\n", + "# Define Stratified K-Fold\n", + "skf = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)\n", + "\n", + "print(\"Stratified K-Fold Cross Validation\\n\" + \"-\"*40)\n", + "\n", + "for fold, (train_idx, test_idx) in enumerate(skf.split(X, y), start=1):\n", + " # indexing for each fold\n", + " X_train, X_test = X.iloc[train_idx], X.iloc[test_idx]\n", + " y_train, y_test = y.iloc[train_idx], y.iloc[test_idx]\n", + "\n", + " print(f\"Fold {fold}\")\n", + " print(\" X_train shape:\", X_train.shape)\n", + " print(\" X_test shape :\", X_test.shape)\n", + " print(\" y_train shape:\", y_train.shape)\n", + " print(\" y_test shape :\", y_test.shape)\n", + "\n", + " # showing class distribution\n", + " train_ratio = (y_train.value_counts(normalize=True) * 100).sort_index()\n", + " test_ratio = (y_test.value_counts(normalize=True) * 100).sort_index()\n", + "\n", + " print(\" y_train class percentages:\", {k: f\"{v:.2f}%\" for k, v in train_ratio.items()})\n", + " print(\" y_test class percentages :\", {k: f\"{v:.2f}%\" for k, v in test_ratio.items()})\n", + "\n", + " print(\"-\" * 40)\n", + "\n", + "\n", + "from catboost import CatBoostClassifier\n", + "\n", + "%pip install kagglehub catboost lightgbm tqdm -q\n", + "\n", + "skf = StratifiedKFold(n_splits=n_splits, shuffle=True, random_state=42)\n", + "models = {\"CatBoost\": CatBoostClassifier(\n", + " verbose=0,\n", + " n_estimators=200,\n", + " max_depth=4\n", + " )\n", + "}\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/449/Q1.ipynb b/submissions_extracted/449/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..050c19e5c9feeb30558090e4f3e2668f8ce3c22d --- /dev/null +++ b/submissions_extracted/449/Q1.ipynb @@ -0,0 +1,407 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q1-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "import os\n", + "import pandas as pd\n", + "Q1_data = os.path.join(path, 'Q1_data.csv')\n", + "df_Q1_data = pd.read_csv(Q1_data)\n", + "\n", + "print(f\"Dataset shape: {df_Q1_data.shape}\")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "df_Q1_data.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "df_Q1_data.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "df_Q1_data.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:plt.figure(figsize=(10, 5))\n", + "import matplotlib.pyplot as plt\n", + "\n", + "plt.hist(df_Q1_data['Delivery_Time'].dropna(), bins=50, edgecolor='black')\n", + "plt.title('Delivery Time Distribution')\n", + "plt.xlabel('Delivery Time')\n", + "plt.ylabel('Frequency')\n", + "plt.figure(figsize=(10, 5))\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "df_Q1_data = df_Q1_data.drop(columns=['Order_ID'])\n", + "\n", + "df_Q1_data.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "missing_percentage = (df_Q1_data.isnull().sum() / len(df_Q1_data)) * 100\n", + "missing_data = pd.DataFrame({\n", + " 'Column': missing_percentage.index,\n", + " 'Missing_Percentage': missing_percentage.values\n", + "})\n", + "missing_data = missing_data[missing_data['Missing_Percentage'] > 0].sort_values('Missing_Percentage', ascending=False)\n", + "\n", + "print(\"Missing Data Analysis:\")\n", + "missing_data.head(10)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "df_Q1_data['Delivery_Time'] = df_Q1_data['Delivery_Time'].fillna(df_Q1_data['Delivery_Time'].mean())\n", + "\n", + "df_Q1_data.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "missing_percentage = (df_Q1_data.isnull().sum() / len(df_Q1_data)) * 100\n", + "missing_data = pd.DataFrame({\n", + " 'Column': missing_percentage.index,\n", + " 'Missing_Percentage': missing_percentage.values\n", + "})\n", + "missing_data = missing_data[missing_data['Missing_Percentage'] > 0].sort_values('Missing_Percentage', ascending=False)\n", + "\n", + "print(\"Missing Data Analysis:\")\n", + "missing_data.head(10)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "df_Q1_data['Weather'] = df_Q1_data['Weather'].fillna(df_Q1_data['Weather'].mode()[0])\n", + "df_Q1_data['Traffic_Level'] = df_Q1_data['Traffic_Level'].fillna(df_Q1_data['Traffic_Level'].mode()[0])\n", + "df_Q1_data['Time_of_Day'] = df_Q1_data['Time_of_Day'].fillna(df_Q1_data['Time_of_Day'].mode()[0])\n", + "df_Q1_data = df_Q1_data.drop(columns=['Courier_Experience_yrs'])\n", + "\n", + "missing_percentage = (df_Q1_data.isnull().sum() / len(df_Q1_data)) * 100\n", + "missing_data = pd.DataFrame({\n", + " 'Column': missing_percentage.index,\n", + " 'Missing_Percentage': missing_percentage.values\n", + "})\n", + "missing_data = missing_data[missing_data['Missing_Percentage'] > 0].sort_values('Missing_Percentage', ascending=False)\n", + "\n", + "print(\"Missing Data Analysis:\")\n", + "missing_data.head(10)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "def check_duplicates(df):\n", + " duplicates = df.duplicated().sum()\n", + " print(f\"Number of Duplicate Samples: {duplicates}\")\n", + " if duplicates > 0:\n", + " print(\"Dropping Duplicates...\")\n", + " df.drop_duplicates(inplace=True)\n", + " print(\"Duplicates Dropped.\")\n", + " else:\n", + " print(\"No Duplicate Samples Found.\")\n", + "\n", + "check_duplicates(df_Q1_data)\n", + "\n", + "df_Q1_data.drop_duplicates(inplace=True)\n", + "\n", + "check_duplicates(df_Q1_data)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "from sklearn.preprocessing import OneHotEncoder #import OneHotEncoder\n", + "\n", + "categories = [\"Weather\",\t\"Traffic_Level\",\t\"Time_of_Day\"\t,\"Vehicle_Type\"]\n", + "print('data before encoding:\\n', categories) #show before encoding\n", + "\n", + "from sklearn.preprocessing import LabelEncoder\n", + "le = LabelEncoder()\n", + "\n", + "# Encode the target column\n", + "for col in categories:\n", + " df_Q1_data[col] = le.fit_transform(df_Q1_data[col])\n", + "\n", + "df_Q1_data.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "from sklearn.model_selection import train_test_split\n", + "from sklearn.preprocessing import StandardScaler\n", + "\n", + "feature_cols = ['Distance_km', 'Weather', 'Traffic_Level', 'Time_of_Day',\n", + " 'Vehicle_Type', 'Preparation_Time_min', ]\n", + "X = df_Q1_data[feature_cols]\n", + "y = df_Q1_data['Delivery_Time']\n", + "\n", + "# Train-test split (80% train, 20% test)\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n", + "print(f\"Train: {X_train.shape}, Test: {X_test.shape}\")\n", + "\n", + "scaler = StandardScaler()\n", + "X_train_scaled = scaler.fit_transform(X_train)\n", + "X_test_scaled = scaler.transform(X_test)\n", + "\n", + "print(f\"\\nScaled ranges - Min: {X_train_scaled.min():.2f}, Max: {X_train_scaled.max():.2f}\")\n", + "pd.DataFrame(X_train_scaled, columns=X_train.columns).head(3)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 6: Write your code here:\n", + "def check_target_imbalance(df, target_column):\n", + " print(\"Target Distribution:\")\n", + "\n", + " df[target_column].hist() # Yeah you can just do this :)\n", + " plt.show()\n", + "\n", + "check_target_imbalance(df_Q1_data, \"Delivery_Time\")\n", + "\n", + "print(\"Rule of thumb: If class distributions are not equal, then our data is imbalanced\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "from sklearn.model_selection import KFold\n", + "from sklearn.ensemble import RandomForestRegressor\n", + "from sklearn.metrics import mean_squared_error as sklearn_mse, mean_absolute_error, r2_score\n", + "import numpy as np\n", + "\n", + "n_splits = 5 # K=5 Folds\n", + "\n", + "# 5-Fold Cross-Validation, shuffled\n", + "kf = KFold(n_splits=n_splits, shuffle=True, random_state=42)\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:\n", + "models = {\n", + " \"Random Forest Regressor\": RandomForestRegressor(n_estimators=200)\n", + "\n", + "}\n", + "\n", + "all_results = {}\n", + "\n", + "for name in models:\n", + " all_results[name] = {'mse': [], 'rmse': [], 'r2': []}\n", + "\n", + "for fold_idx, (train_index, test_index) in enumerate(kf.split(X)):\n", + " print(f\"\\nFold {fold_idx + 1}/{n_splits}\")\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", + " for model_name, model in models.items():\n", + " print(f\"Training {model_name}...\")\n", + "\n", + " # Train\n", + " model.fit(X_train, y_train)\n", + "\n", + " # Predict\n", + " y_pred = model.predict(X_test)\n", + "\n", + " # Calculate metrics\n", + " mse = sklearn_mse(y_test, y_pred)\n", + " rmse = np.sqrt(mse)\n", + " r2 = r2_score(y_test, y_pred)\n", + "\n", + " # Store results\n", + " all_results[model_name][\"mse\"].append(mse)\n", + " all_results[model_name][\"rmse\"].append(rmse)\n", + " all_results[model_name][\"r2\"].append(r2)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "feature_importance = pd.DataFrame({\n", + " 'feature': feature_cols,\n", + " 'importance': model.feature_importances_\n", + "}).sort_values('importance', ascending=False)\n", + "\n", + "plt.figure(figsize=(10, 6))\n", + "plt.barh(feature_importance['feature'], feature_importance['importance'])\n", + "plt.xlabel('Importance')\n", + "plt.title('Feature Importance')\n", + "plt.gca().invert_yaxis()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "def plot_y_pred(y_pred):\n", + " print(\"Target Distribution:\")\n", + "\n", + " y_pred.hist() # Yeah you can just do this :)\n", + " plt.show()\n", + "\n", + "plot_y_pred(y_pred)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:\n", + "from sklearn.svm import SVR\n", + "from sklearn.tree import DecisionTreeRegressor\n", + "from sklearn.ensemble import RandomForestRegressor\n", + "models = {\n", + " \"Support Vector Machine\": SVR(kernel='rbf'),\n", + " \"Decision Tree Regressor\": DecisionTreeRegressor(max_depth=10),\n", + "\n", + "}\n", + "\n", + "all_results = {}\n", + "\n", + "for name in models:\n", + " all_results[name] = {'mae': [], 'mse': [], 'r2': []}\n", + "\n", + "for fold_idx, (train_index, test_index) in enumerate(kf.split(X)):\n", + " print(f\"\\nFold {fold_idx + 1}/{n_splits}\")\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", + " for model_name, model in models.items():\n", + " print(f\"Training {model_name}...\")\n", + "\n", + " # Train\n", + " model.fit(X_train, y_train)\n", + "\n", + " # Predict\n", + " y_pred = model.predict(X_test)\n", + "\n", + " # Calculate metrics\n", + " mse = sklearn_mse(y_test, y_pred)\n", + " mae = mean_absolute_error(y_test, y_pred)\n", + " r2 = r2_score(y_test, y_pred)\n", + "\n", + " # Store results\n", + " all_results[model_name][\"mae\"].append(mae)\n", + " all_results[model_name][\"mse\"].append(mse)\n", + " all_results[model_name][\"r2\"].append(r2)" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/449/Q3.ipynb b/submissions_extracted/449/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..b480c86f7cd06c79c3b89c28766f556aecfc0c59 --- /dev/null +++ b/submissions_extracted/449/Q3.ipynb @@ -0,0 +1,388 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "\n", + "\n", + "# Download latest version\n", + "\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q3-exam-data\")\n", + "\n", + "\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "import os\n", + "import pandas as pd\n", + "Q3_data = os.path.join(path, 'Q3_data.csv')\n", + "df_Q3_data = pd.read_csv(Q3_data)\n", + "\n", + "print(f\"Dataset shape: {df_Q3_data.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "df_Q3_data.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "df_Q3_data.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "df_Q3_data.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "missing_percentage = (df_Q3_data.isnull().sum() / len(df_Q3_data)) * 100\n", + "missing_data = pd.DataFrame({\n", + " 'Column': missing_percentage.index,\n", + " 'Missing_Percentage': missing_percentage.values\n", + "})\n", + "missing_data = missing_data[missing_data['Missing_Percentage'] > 0].sort_values('Missing_Percentage', ascending=False)\n", + "\n", + "print(\"Missing Data Analysis:\")\n", + "missing_data.head(10)\n", + "\n", + "catogaries = [\"D_87\",\"D_88\",\"B_39\",\"D_110\", \"D_111\",\"D_108\",\"B_42\",\"D_73\",\"D_135\",\"D_136\"]\n", + "for col in missing_data.columns():\n", + " df_Q3_data = df_Q3_data.drop(columns=[col])\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "missing_data.head(10)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "catogaries = [\"D_87\",\"D_88\",\"B_39\",\"D_110\", \"D_111\",\"D_108\",\"B_42\",\"D_73\",\"D_135\",\"D_136\"]\n", + "for col in catogaries:\n", + " df_Q3_data = df_Q3_data.drop(columns=[col])" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "def check_duplicates(df):\n", + " duplicates = df.duplicated().sum()\n", + " print(f\"Number of Duplicate Samples: {duplicates}\")\n", + " if duplicates > 0:\n", + " print(\"Dropping Duplicates...\")\n", + " df.drop_duplicates(inplace=True)\n", + " print(\"Duplicates Dropped.\")\n", + " else:\n", + " print(\"No Duplicate Samples Found.\")\n", + "\n", + "check_duplicates(df_Q3_data)\n", + "\n", + "df_Q3_data.drop_duplicates(inplace=True)\n", + "\n", + "check_duplicates(df_Q3_data)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "df_cat = df_Q3_data.astype(object)\n", + "\n", + "df_cat.head().sum()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "cols = df_Q3_data.\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "from sklearn.model_selection import train_test_split\n", + "from sklearn.preprocessing import StandardScaler\n", + "\n", + "feature_cols = [\"P_2\",\t\"D_39\",\t\"B_1\",\t\"B_2\",\t\"R_1\",\t\"S_3\",\t\"D_41\",\t\"B_3\",\t\"D_42\",\t\"D_43\",\t\"D_44\",\t\"B_4\",\t\"D_45\",\t\"B_5\",\t\"R_2\",\t\"D_46\",\n", + "\"D_47\",\t\"D_48\",\t\"B_6\",\t\"B_7\",\t\"B_8\",\t\"D_50\",\t\"D_51\",\t\"B_9\",\t\"R_3\",\t\"D_52\",\t\"P_3\",\t\"B_10\",\t\"D_53\",\t\"S_5\",\n", + "\"B_11\",\t\"S_6\",\t\"D_54\",\t\"R_4\",\t\"S_7\",\t\"B_12\",\t\"S_8\",\t\"D_55\",\t\"D_56\",\t\"B_13\",\t\"R_5\",\t\"D_58\",\t\"S_9\",\t\"B_14\",\t\"D_59\",\n", + "\"D_60\",\t\"D_61\",\t\"B_15\",\t\"S_11\",\t\"D_62\",\t\"D_63\",\t\"D_64\",\t\"D_65\",\t\"B_16\",\t\"B_17\",\t\"B_18\",\t\"B_19\",\n", + "\"B_20\",\t\"D_68\",\t\"S_12\",\t\"R_6\",\t\"S_13\",\t\"B_21\",\t\"D_69\",\t\"B_22\",\t\"D_70\",\t\"D_71\",\t\"D_72\",\t\"S_15\",\t\"B_23\",\n", + "\"P_4\",\t\"D_74\",\t\"D_75\",\t\"D_76\",\t\"B_24\",\t\"R_7\",\t\"D_77\",\t\"B_25\",\t\"B_26\",\t\"D_78\",\t\"D_79\",\t\"R_8\",\t\"S_16\",\n", + "\"D_80\",\t\"R_10\",\t\"R_11\",\t\"B_27\",\t\"D_81\",\t\"D_82\",\t\"S_17\",\t\"R_12\",\t\"B_28\",\t\"R_13\",\t\"D_83\",\t\"R_14\",\t\"R_15\",\n", + "\"D_84\",\t\"R_16\",\t\"B_30\",\t\"S_18\",\t\"D_86\",\t\"R_17\",\t\"R_18\",\t\"B_31\",\t\"S_19\",\t\"R_19\",\n", + "\"B_32\",\t\"S_20\",\t\"R_20\",\t\"R_21\",\t\"B_33\",\t\"D_89\",\t\"R_22\",\t\"R_23\",\t\"D_91\",\t\"D_92\",\t\"D_93\",\t\"D_94\",\t\"R_24\",\n", + "\"R_25\",\t\"D_96\",\t\"S_22\",\t\"S_23\",\t\"S_24\",\t\"S_25\",\t\"S_26\",\t\"D_102\",\t\"D_103\",\t\"D_104\",\t\"D_105\",\t\"D_107\",\n", + "\"B_36\",\t\"B_37\",\t\"R_27\",\t\"B_38\",\t\"D_109\",\t\"D_112\",\t\"B_40\",\t\"S_27\",\n", + "\"D_113\",\t\"D_114\",\t\"D_115\",\t\"D_116\",\t\"D_117\",\t\"D_118\",\t\"D_119\",\t\"D_120\",\t\"D_121\",\t\"D_122\",\t\"D_123\",\t\"D_124\",\t\"D_125\",\n", + "\"D_126\",\t\"D_127\",\t\"D_128\",\t\"D_129\",\t\"B_41\",\t\"D_130\",\t\"D_131\",\t\"D_133\",\t\"R_28\",\n", + "\"D_139\",\t\"D_140\",\t\"D_141\",\t\"D_142\",\t\"D_143\",\t\"D_144\",\t\"D_145\" ]\n", + "X = df_Q3_data[feature_cols]\n", + "y = df_Q3_data['Target']\n", + "\n", + "# Train-test split (80% train, 20% test)\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n", + "print(f\"Train: {X_train.shape}, Test: {X_test.shape}\")\n", + "\n", + "scaler = StandardScaler()\n", + "X_train_scaled = scaler.fit_transform(X_train)\n", + "X_test_scaled = scaler.transform(X_test)\n", + "\n", + "print(f\"\\nScaled ranges - Min: {X_train_scaled.min():.2f}, Max: {X_train_scaled.max():.2f}\")\n", + "pd.DataFrame(X_train_scaled, columns=X_train.columns).head(3)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "missing_percentage = (X.isnull().sum() / len(X)) * 100\n", + "missing_data = pd.DataFrame({\n", + " 'Column': missing_percentage.index,\n", + " 'Missing_Percentage': missing_percentage.values\n", + "})\n", + "missing_data = missing_data[missing_data['Missing_Percentage'] > 0].sort_values('Missing_Percentage', ascending=False)\n", + "\n", + "print(\"Missing Data Analysis:\")\n", + "missing_data.head(10)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "import matplotlib.pyplot as plt\n", + "\n", + "def check_target_imbalance(df, target_column):\n", + " print(\"Target Distribution:\")\n", + "\n", + " df[target_column].hist() # Yeah you can just do this :)\n", + " plt.show()\n", + "\n", + "check_target_imbalance(df_Q3_data, \"Target\")\n", + "\n", + "print(\"Rule of thumb: If class distributions are not equal, then our data is imbalanced\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "pip install catboost" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "from sklearn.neighbors import KNeighborsClassifier\n", + "from sklearn.svm import SVC\n", + "from sklearn.tree import DecisionTreeClassifier\n", + "from sklearn.ensemble import RandomForestClassifier\n", + "from xgboost import XGBClassifier\n", + "from catboost import CatBoostClassifier\n", + "import numpy as np\n", + "\n", + "sklearn_models = {\n", + " \"K-Nearest Neighbors\": KNeighborsClassifier(\n", + " n_neighbors=3, # Number of neighbors to consider\n", + " ),\n", + " \"Support Vector Machine\": SVC(\n", + " kernel='rbf', # 'linear', 'poly', 'rbf', 'sigmoid'\n", + " C=0.75 # Regularization parameter\n", + " ),\n", + " \"Decision Tree\": DecisionTreeClassifier(\n", + " max_depth=3 # Maximum depth of tree (prevents overfitting)\n", + " ),\n", + " \"Random Forest\": RandomForestClassifier(\n", + " n_estimators=320, # Number of trees\n", + " max_depth=4\n", + " ),\n", + " \"XGBoost\": XGBClassifier(\n", + " verbosity=0,\n", + " n_estimators=300, # Number of boosting rounds\n", + " max_depth=5,\n", + " learning_rate=0.05 # Step size shrinkage\n", + " ),\n", + " \"CatBoost\": CatBoostClassifier(\n", + " verbose=0,\n", + " n_estimators=320,\n", + " max_depth=4\n", + " )\n", + "}\n", + "\n", + "all_results = {}\n", + "\n", + "for name in sklearn_models:\n", + " all_results[name] = {'accuracy': [], 'precision': [], 'recall': [], 'f1': []}" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:\n", + "from sklearn.model_selection import StratifiedKFold\n", + "from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score\n", + "n_splits = 5 # K\n", + "\n", + "# Stratified 5-Fold Cross-Validation, shuffled\n", + "skf = StratifiedKFold(n_splits=n_splits, shuffle=True, random_state=42)\n", + "\n", + "for fold_idx, (train_index, test_index) in enumerate(skf.split(X, y)):\n", + " print(f\"\\nFold {fold_idx + 1}/{n_splits}\")\n", + "\n", + " # 1. Split data\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", + " # 2. Train & Validate sklearn models\n", + " for model_name, model in sklearn_models.items():\n", + " print(f\"Training {model_name}...\")\n", + " model.fit(X_train, y_train) # train\n", + " y_pred = model.predict(X_test) # validate\n", + "\n", + " # 3. Save metrics for that model in this fold\n", + " accuracy = accuracy_score(y_test, y_pred)\n", + " precision = precision_score(y_test, y_pred, zero_division=0)\n", + " recall = recall_score(y_test, y_pred, zero_division=0)\n", + " f1 = f1_score(y_test, y_pred, zero_division=0)\n", + "\n", + " all_results[model_name]['accuracy'].append(accuracy)\n", + " all_results[model_name]['precision'].append(precision)\n", + " all_results[model_name]['recall'].append(recall)\n", + " all_results[model_name]['f1'].append(f1)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "importances = {}\n", + "\n", + "importances['Random Forest'] = sklearn_models['Random Forest'].feature_importances_\n", + "importances['XGBoost'] = sklearn_models['XGBoost'].feature_importances_\n", + "importances['CatBoost'] = sklearn_models['CatBoost'].feature_importances_\n", + "\n", + "# Create a 1x3 plot\n", + "fig, axes = plt.subplots(1, 3, figsize=(18, 6))\n", + "axes = axes.flatten()\n", + "features = X.columns\n", + "\n", + "for i, (model_name, imp) in enumerate(importances.items()):\n", + " # Sort features by importance for a cleaner plot\n", + " sorted_idx = np.argsort(imp)\n", + "\n", + " ax = axes[i]\n", + " ax.barh(features[sorted_idx], imp[sorted_idx])\n", + " ax.set_title(f\"{model_name} Feature Importance\")\n", + " ax.set_xlabel(\"Importance Score\")\n", + "\n", + "plt.tight_layout()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/45/Q1.ipynb b/submissions_extracted/45/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..22595e1d6f151f9f8083ad9078e40ae429a7bb56 --- /dev/null +++ b/submissions_extracted/45/Q1.ipynb @@ -0,0 +1,332 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q1-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)\n", + "\n", + "import pandas as pd\n", + "import numpy as np\n", + "import matplotlib.pyplot as plt\n", + "import seaborn as sns\n", + "\n", + "from sklearn.preprocessing import LabelEncoder, StandardScaler\n", + "from sklearn.model_selection import KFold\n", + "from sklearn.metrics import f1_score\n", + "from sklearn.linear_model import LogisticRegression\n", + "from sklearn.dummy import DummyClassifier\n", + "from sklearn.ensemble import VotingClassifier, RandomForestClassifier\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "df = pd.read_csv(\"/kaggle/input/q1-exam-data/Q1_data.csv\")\n", + "\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "df.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "missing = df.isnull().sum()\n", + "print(\"\\nMissing Values:\")\n", + "print(missing[missing > 0])" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "print(f\"Before: {df_clean.shape}\")\n", + "df_clean = df_clean.dropna(subset=['Courier_Experience_yrs', ''])\n", + "print(f\"After dropping missing Courier_Experience_yrs: {df_clean.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "for col in ['Courier_Experience_yrs','Delivery_Time']:\n", + " df_clean[col] = df_clean[col].fillna('unknown')" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "df.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "plt.figure(figsize=(10, 5))\n", + "plt.hist(df['Traffic_Level'].dropna(), bins=50, edgecolor='black')\n", + "plt.title('delivery_time')\n", + "plt.xlabel('Distance_km ')\n", + "plt.ylabel('Delivery_Time ')\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "cols = ['Distance_km', 'Preparation_Time_min', 'Courier_Experience_yrs', 'Delivery_Time',\n", + " 'Weather', 'Vehicle_Type', 'Traffic_Level', 'Time_of_Day']\n", + "\n", + "df_clean = df [cols].copy()\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "\n", + "\n", + "# Task 2: Write your code here:\n", + "print(f\"Before: {df_clean.shape}\")\n", + "\n", + "for col in ['Distance_km', 'Preparation_Time_min', 'Courier_Experience_yrs', 'Delivery_Time',\n", + " 'Weather', 'Vehicle_Type', 'Traffic_Level', 'Time_of_Day']:\n", + " df_clean[col] = df_clean[col].fillna('unknown')\n", + "\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "def check_duplicates(df):\n", + " duplicates = df.duplicated().sum()\n", + " print(f\"Duplicate Samples: {duplicates}\")\n", + "\n", + " if duplicates > 0:\n", + " df.drop_duplicates(inplace=True)\n", + " print(\"Duplicates Dropped.\")\n", + "\n", + "check_duplicates(df)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "categorical_cols = df.select_dtypes(include=[\"object\"]).columns\n", + "print(\"Categorical Columns:\", list(categorical_cols))\n", + "\n", + "from sklearn.preprocessing import LabelEncoder\n", + "\n", + "label_encoders = {}\n", + "\n", + "for col in categorical_cols:\n", + " le = LabelEncoder()\n", + " df[col] = le.fit_transform(df[col])\n", + " label_encoders[col] = le\n", + "\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "df.describe()\n", + "\n", + "from sklearn.preprocessing import StandardScaler\n", + "\n", + "\n", + "numerical_cols = (\n", + " df.select_dtypes(include=[\"int64\", \"float64\"])\n", + " .columns\n", + " .drop(\"Delivery_Time\")\n", + ")\n", + "\n", + "scaler = StandardScaler()\n", + "df[numerical_cols] = scaler.fit_transform(df[numerical_cols])\n", + "\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 6: Write your code here:\n", + "def check_target_imbalance(df, Delivery_Time):\n", + " print(\"Target Distribution:\")\n", + " print(df[Delivery_Time].value_counts(normalize=True))\n", + "\n", + " sns.countplot(x=df[Delivery_Time])\n", + " plt.title(\"Target Distribution\")\n", + " plt.show()\n", + "\n", + "check_target_imbalance(df, \"Delivery_Time\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "X = df.drop(\"Delivery_Time\", axis=1).astype(float)\n", + "y = df[\"Delivery_Time\"].astype(float)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:\n", + "from sklearn.model_selection import StratifiedKFold\n", + "from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score\n", + "\n", + "n_splits = 5\n", + "skf = StratifiedKFold(\n", + " n_splits=n_splits,\n", + " shuffle=True,\n", + " random_state=42\n", + ")\n", + "\n", + "lr_losses, lr_accuracy, lr_precision, lr_recall, lr_f1 = [], [], [], [], []\n", + "\n", + "for fold_idx, (train_index, test_index) in enumerate(skf.split(X, y)):\n", + " print(f\"\\nFold {fold_idx + 1}/{n_splits}\")\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", + " theta, losses = gradient_descent(\n", + " X_train.values,\n", + " y_train.values,\n", + " learning_rate=0.5,\n", + " n_iters=500\n", + " )\n", + "\n", + " y_pred_proba = sigmoid(np.dot(X_test, theta))\n", + " y_pred = (y_pred_proba >= 0.5).astype(int)\n", + "\n", + " lr_losses.append(losses)\n", + " lr_accuracy.append(accuracy_score(y_test, y_pred))\n", + " lr_precision.append(precision_score(y_test, y_pred, zero_division=0))\n", + " lr_recall.append(recall_score(y_test, y_pred, zero_division=0))\n", + " lr_f1.append(f1_score(y_test, y_pred, zero_division=0))" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "y.isn" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file