diff --git a/submissions_extracted/218/Q1.ipynb b/submissions_extracted/218/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..dac9ab6e76eecc67d601b4e654562f1e2911698c --- /dev/null +++ b/submissions_extracted/218/Q1.ipynb @@ -0,0 +1,299 @@ +{ + "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", + "from sklearn.metrics import mean_absolute_error, mean_squared_error\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", + "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\"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", + "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:\n", + "plt.figure(figsize=(10, 5))\n", + "plt.hist(df_Q1_data['Delivery_Time'].dropna(), bins=50, 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_clean= df_Q1_data.dropna(subset=['Order_ID']).copy()" + ], + "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_Q1_data)" + ], + "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_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", + "# Do we have categorical columns?\n", + "import torch\n", + "categorical_cols = df_Q1_data.select_dtypes(include=[\"object\"]).columns\n", + "\n", + "print(\"Categorical Columns:\", list(categorical_cols))\n", + "\n", + "from sklearn.preprocessing import OneHotEncoder #import OneHotEncoder\n", + "\n", + "print('data before encoding:\\n', categorical_cols) #show before encoding\n", + "\n", + "onehot_encoder = OneHotEncoder(sparse_output=False)\n", + "\n", + "categorical_cols.reshape(-1, 1)\n", + "data_onehot_encoded = onehot_encoder.fit_transform(categorical_cols)\n", + "\n", + "print('\\nData after encoding:\\n', data_onehot_encoded)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "from sklearn.preprocessing import StandardScaler #import StandardScaler\n", + "standard_scaler = StandardScaler()\n", + "data_standard_scaled = standard_scaler.fit_transform(df_Q1_data) # Apply fit_transform\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", + "plt.figure(figsize=(10, 5))\n", + "plt.hist(df_Q1_data['Delivery_Time'],bins=30, edgecolor='black')\n", + "plt.title('Data distribution')\n", + "plt.xlabel('Data')\n", + "plt.ylabel('Frequency')\n", + "plt.show()\n", + "\n", + "print(\"data right skewed\")" + ], + "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 = ['Order_ID','Distance_km','Preparation_Time_min','Courier_Experience_yrs']\n", + "X = df_clean[feature_cols]\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", + "\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", + " # Train Random Forest Regressor\n", + "from sklearn.ensemble import RandomForestRegressor\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", + "from sklearn.metrics import mean_absolute_error, mean_squared_error\n", + "mae_scores = []\n", + "mae_scores.append(mean_absolute_error(y_train, y_test))\n", + "mae_scores = np.array(mae_scores)\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", + "plt.figure(figsize=(10, 5))\n", + "plt.hist(df_Q1_data['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 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/218/Q2.ipynb b/submissions_extracted/218/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..aa69a26056e2403b3d10009033abc160eb335ffe --- /dev/null +++ b/submissions_extracted/218/Q2.ipynb @@ -0,0 +1,297 @@ +{ + "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 torch\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)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 2. Create TensorDataset objects\n", + "from torch.utils.data import DataLoader, TensorDataset\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}\")" + ], + "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 NN4Layer(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", + " # third 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", + " # third hidden layer\n", + " a3 = self.relu(self.layer3(a2))\n", + "\n", + " # Output layer (regression output)\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.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:" + ], + "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/218/Q3.ipynb b/submissions_extracted/218/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..548649f033d2ef9398fec6512534a36ca2864111 --- /dev/null +++ b/submissions_extracted/218/Q3.ipynb @@ -0,0 +1,216 @@ +{ + "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", + "\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.metrics import mean_absolute_error, mean_squared_error\n", + "import warnings\n", + "warnings.filterwarnings('ignore')\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", + "print(f\"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", + "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", + "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_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_Q3_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", + "#no categroical vars" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "# Define features and target\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 5: Write your code here:\n", + "plt.figure(figsize=(10, 5))\n", + "plt.hist(df_Q3_data['Target'],bins=30, edgecolor='black')\n", + "plt.title('Target')\n", + "plt.xlabel('Data')\n", + "plt.ylabel('Frequency')\n", + "plt.show()\n", + "\n", + "print(\"imbalanced\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "\n", + "# Define features (X) and target (y)\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...,\t'D_137'\t,'D_138',\t'D_139'\t,'D_140'\t,'D_141'\t,'D_142',\t'D_143','D_144','D_145']\n", + "X = Q3_data_clean[feature_cols]\n", + "y = Q3_data_clean['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/219/Q1.ipynb b/submissions_extracted/219/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..144b82afafc7e235ce40ae6efc2fdacc7e696e72 --- /dev/null +++ b/submissions_extracted/219/Q1.ipynb @@ -0,0 +1,281 @@ +{ + "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", + "\n", + "dt = pd.read_csv(os.path.join(path,'Q1_data.csv'))" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "dt.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "dt.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "dt.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "from matplotlib import pyplot as plt\n", + "\n", + "# Year distribution\n", + "plt.figure(figsize=(10, 5))\n", + "plt.hist(dt['Delivery_Time'].dropna(), bins=30, edgecolor='black', color='orange')\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": [ + "dt = dt.drop('Order_ID',axis=1)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "dt = dt.dropna(subset=['Delivery_Time','Traffic_Level','Time_of_Day','Weather'])\n", + "dt['Courier_Experience_yrs'] = dt['Courier_Experience_yrs'].fillna( int(dt['Courier_Experience_yrs'].mean()) )\n", + "dt.isna().sum()\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "dt = dt.drop_duplicates()\n", + "print(dt.duplicated().sum())\n", + "\n", + "dt" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "from sklearn.preprocessing import LabelEncoder\n", + "\n", + "lb = LabelEncoder()\n", + "\n", + "dt['Weather'] = lb.fit_transform( dt['Weather'] )\n", + "dt['Traffic_Level'] = lb.fit_transform( dt['Traffic_Level'] )\n", + "dt['Time_of_Day'] = lb.fit_transform( dt['Time_of_Day'] )\n", + "dt['Vehicle_Type'] = lb.fit_transform( dt['Vehicle_Type'] )\n", + "\n", + "dt" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "from sklearn.preprocessing import StandardScaler\n", + "\n", + "X,y = dt.drop('Delivery_Time',axis=1), dt['Delivery_Time']\n", + "\n", + "std = StandardScaler()\n", + "X = std.fit_transform(X)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# There are no imbalance in the data\n", + "# The data is well distributed and a linear model was trained on it (not categorical)." + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "from sklearn.model_selection import train_test_split\n", + "\n", + "X_train,X_test,y_train,y_test = train_test_split(X,y)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "from sklearn.metrics import mean_absolute_error, mean_squared_error\n", + "from sklearn.model_selection import KFold\n", + "from sklearn.ensemble import RandomForestRegressor\n", + "\n", + "model = RandomForestRegressor()\n", + "\n", + "kfold = KFold(n_splits=5, shuffle=True, random_state=42)\n", + "\n", + "mae_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} Minutes\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Feature importance\n", + "feature_importance = pd.DataFrame({\n", + " 'feature': ['Distance_km', 'Weather', 'Traffic_Level', 'Time_of_Day',\n", + " '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": [ + "plt.scatter(model.predict(X_test),y_test, color='red')\n", + "plt.plot([10,120],[10,120],color='green')\n", + "plt.xlabel('Acual Y')\n", + "plt.ylabel('Predicted Y')\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "from IPython.display import clear_output\n", + "%pip install catboost -q\n", + "clear_output()\n", + "\n", + "from sklearn.metrics import mean_absolute_error\n", + "from sklearn.model_selection import KFold\n", + "from sklearn.ensemble import RandomForestRegressor\n", + "from catboost import CatBoostRegressor\n", + "\n", + "import numpy as np\n", + "\n", + "rf_model = RandomForestRegressor(random_state=42)\n", + "\n", + "cb_model = CatBoostRegressor(random_state=42, verbose=0)\n", + "\n", + "kfold = KFold(n_splits=5, shuffle=True, random_state=42)\n", + "\n", + "mae_scores_averaged = []\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", + " rf_model.fit(X_fold_train, y_fold_train)\n", + " cb_model.fit(X_fold_train, y_fold_train)\n", + "\n", + " rf_preds = rf_model.predict(X_fold_val)\n", + " cb_preds = cb_model.predict(X_fold_val)\n", + "\n", + " averaged_predictions = (rf_preds + cb_preds) / 2\n", + "\n", + " fold_mae = mean_absolute_error(y_fold_val, averaged_predictions)\n", + " mae_scores_averaged.append(fold_mae)\n", + "\n", + "print(f\"[+] Averaged Models MAE: {np.mean(mae_scores_averaged)}\")" + ], + "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/219/Q2.ipynb b/submissions_extracted/219/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..2c0117df85b9d33d79445a0a8308c4ba4e25a9d0 --- /dev/null +++ b/submissions_extracted/219/Q2.ipynb @@ -0,0 +1,269 @@ +{ + "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", + "\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": [ + "from torch.utils.data import TensorDataset\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": [ + "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)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "for images, labels in train_loader:\n", + " print(images.shape)\n", + " print(labels.shape)\n", + " break" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import matplotlib.pyplot as plt\n", + "\n", + "fig, axs = plt.subplots(1, 5, figsize=(15, 3))\n", + "for i in range(5):\n", + " img = images[i].permute(1, 2, 0).numpy()\n", + " axs[i].imshow(img)\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import torch.nn as nn\n", + "\n", + "class AgePredictor(nn.Module):\n", + " def __init__(self):\n", + " super(AgePredictor, self).__init__()\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", + "\n", + " def forward(self, x):\n", + " x = x.view(-1,3*36*36)\n", + " x = torch.relu(self.fc1(x))\n", + " x = torch.relu(self.fc2(x))\n", + " x = torch.relu(self.fc3(x))\n", + " x = self.fc4(x)\n", + " return x" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "def train(model, loader, optimizer, criterion, device):\n", + " model.train()\n", + " total_loss = 0\n", + " for images, labels in loader:\n", + " images, labels = images.to(device), labels.to(device)\n", + " optimizer.zero_grad()\n", + " outputs = model(images)\n", + " loss = criterion(outputs.squeeze(), labels)\n", + " loss.backward()\n", + " optimizer.step()\n", + " total_loss += loss.item()\n", + " return total_loss / len(loader)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "def validate(model, loader, criterion, device):\n", + " model.eval()\n", + " total_loss = 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 = criterion(outputs.squeeze(), labels)\n", + " total_loss += loss.item()\n", + " return total_loss / len(loader)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\n", + "model = AgePredictor().to(device)\n", + "criterion = nn.MSELoss()\n", + "optimizer = torch.optim.Adam(model.parameters(), lr=0.001)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "train_losses = []\n", + "val_losses = []\n", + "for epoch in range(20):\n", + " train_loss = train(model, train_loader, optimizer, criterion, device)\n", + " val_loss = validate(model, test_loader, criterion, device)\n", + " train_losses.append(train_loss)\n", + " val_losses.append(val_loss)\n", + " print(f\"Epoch {epoch+1}: Train Loss {train_loss:.4f}, Val Loss {val_loss:.4f}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "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.legend()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "model.eval()\n", + "with torch.no_grad():\n", + " for images, labels in test_loader:\n", + " images = images.to(device)\n", + " preds = model(images).squeeze().cpu().numpy()\n", + " labels = labels.numpy()\n", + " break\n", + "\n", + "fig, axs = plt.subplots(1, 5, figsize=(15, 3))\n", + "for i in range(5):\n", + " img = images[i].permute(1, 2, 0).cpu().numpy()\n", + " axs[i].imshow(img)\n", + " axs[i].set_title(f\"Pred: {preds[i]:.1f}, Actual: {labels[i]}\")\n", + " axs[i].axis('off')\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/219/Q3.ipynb b/submissions_extracted/219/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..68e23dd31e0932740b7996549f396e071d22a37f --- /dev/null +++ b/submissions_extracted/219/Q3.ipynb @@ -0,0 +1,223 @@ +{ + "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", + "\n", + "df = pd.read_csv(os.path.join(path, 'Q3_data.csv'))" + ], + "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": [ + "for col in df.columns:\n", + " df[col] = df[col].fillna( df[col].mean() )\n", + "\n", + "df" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "print(df.duplicated().sum())\n", + "df = df.drop_duplicates()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "df.select_dtypes(include=['object']).columns\n", + "\n", + "# There isn't any" + ], + "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(\"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": [ + "from sklearn.model_selection import train_test_split\n", + "\n", + "X,y = df.drop('Target',axis=1), df['Target']\n", + "\n", + "# split ratio (80% train, 20% test)\n", + "X_train, X_test, y_train, y_test = train_test_split(\n", + " X,\n", + " 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" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "from IPython.display import clear_output\n", + "%pip install catboost -q\n", + "clear_output()\n", + "\n", + "from sklearn.metrics import f1_score,accuracy_score\n", + "from sklearn.model_selection import KFold\n", + "from sklearn.ensemble import RandomForestRegressor\n", + "from catboost import CatBoostClassifier\n", + "\n", + "import numpy as np\n", + "\n", + "\n", + "cb_model = CatBoostClassifier(random_state=42, verbose=0)\n", + "\n", + "kfold = KFold(n_splits=5, shuffle=True, random_state=42)\n", + "\n", + "f1_scores_averaged = []\n", + "acc_scores_averaged = []\n", + "\n", + "for train_idx, val_idx in kfold.split(X_train):\n", + " X_fold_train, X_fold_val = X_train.iloc[train_idx], X_train.iloc[val_idx]\n", + " y_fold_train, y_fold_val = y_train.iloc[train_idx], y_train.iloc[val_idx]\n", + "\n", + " cb_model.fit(X_fold_train, y_fold_train)\n", + "\n", + " cb_preds = cb_model.predict(X_fold_val)\n", + "\n", + " f1_scores_averaged.append(f1_score(y_fold_val, cb_preds))\n", + " acc_scores_averaged.append(accuracy_score(y_fold_val, cb_preds))\n", + "\n", + "print(f\"[+] CatBoost \\nAvg F1: {np.mean(f1_scores_averaged)}\\nAvg Accuracy: {np.mean(acc_scores_averaged)}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import matplotlib.pyplot as plt\n", + "\n", + "# Feature importance\n", + "feature_importance = pd.DataFrame({\n", + " 'feature': df.drop('Target',axis=1).columns,\n", + " 'importance': cb_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", + "\n", + "# Something Strange Xd :)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "golden_strange_weird_feature_idx = list(cb_model.feature_importances_).index(max(cb_model.feature_importances_))\n", + "print('The weird feature is :',df.drop('Target',axis=1).columns[0])" + ], + "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/22/Q2.ipynb b/submissions_extracted/22/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..298b30772d46472e2d7480a30de3c74906f79e59 --- /dev/null +++ b/submissions_extracted/22/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 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 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" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 2. Create TensorDataset objects\n", + "\n", + "# Training dataset\n", + "train_dataset = CIFAR10(root='./datasets', train=True, transform=to_tensor, download=True)\n", + "# Testing dataset\n", + "test_dataset = CIFAR10(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": [ + "# 3. Create DataLoaders\n", + "\n", + "# DataLoader for training\n", + " datatrain_loader = DataLoader( train_dataset, batch_size=32, shuffle=True, num_workers=2)\n", + " # DataLoader for test\n", + " datatest_loader = DataLoader( test_dataset, batch_size=32, shuffle=False, num_workers=2)\n", + " # Get the first batch from the training\n", + " DataLoaderX_batch, y_batch = next(iter(train_loader))print(f\"Training batch input shape: {X_batch.shape}\")print(f\"Training batch labels shape: {y_batch.shape}\")\n", + "\n", + "\n", + "keyboard_arrow_down\n", + "\n", + "more_horiz\n", + " Training batch input shape: torch.Size([32, 3, 32, 32])\n", + "Training batch labels shape: torch.Size([32])\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))print(f\"Training batch input shape: {X_batch.shape}\")print(f\"Training batch labels shape: {y_batch.shape}\")\n", + "\n", + "\n", + "keyboard_arrow_down\n", + "\n", + "more_horiz\n", + " Training batch input shape: torch.Size([32, 3, 32, 32])\n", + "Training batch labels shape: torch.Size([32])\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", + " # 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", + " # activation function for non-linearity\n", + " self.relu = nn.ReLU()\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 = 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" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Define device, model, loss, optimizer:\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 1: Write your code here:\n", + "\n", + "Plotting resultsplt.figure(figsize=(7, 5))plt.plot(train_losses, label='Train Loss')plt.plot(val_losses, label='Validation Loss')plt.title('Loss over Epochs')plt.xlabel('Epoch')plt.ylabel('Loss')plt.legend()plt.tight_layout()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": [ + "# Task 5: Start training for 20 epochs:\n", + "print (ANON)\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/220/Q1.ipynb b/submissions_extracted/220/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..2c8c41ecff74c87bb4523047ee7a7434b7882a6f --- /dev/null +++ b/submissions_extracted/220/Q1.ipynb @@ -0,0 +1,341 @@ +{ + "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": [ + "!pip install catboost" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "import os\n", + "import pandas as pd\n", + "import numpy as np\n", + "from sklearn.model_selection import KFold\n", + "from sklearn.preprocessing import StandardScaler, MinMaxScaler, LabelEncoder, OneHotEncoder\n", + "\n", + "from sklearn.ensemble import RandomForestRegressor\n", + "from sklearn.metrics import mean_absolute_error\n", + "from catboost import CatBoostClassifier\n", + "\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", + "plt.figure(figsize=(10, 5))\n", + "plt.hist(df['Delivery_Time'], bins=30, 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", + "df = df.drop(columns=\"Order_ID\", axis=1)\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "# Checking the missing values\n", + "# print(\"Missing values per column:\")\n", + "# print(df.isnull().sum())\n", + "# print(f\"\\nTotal missing: {df.isnull().sum().sum()}\")\n", + "\n", + "\n", + "# We need to copy the data before cleaning\n", + "df_clean = df.copy()\n", + "\n", + "# I will drop the missing values in Weather, Traffic Level, Time_of_Day, and Courier_experience_yrs\n", + "cols_to_drop = ['Weather', 'Traffic_Level', 'Time_of_Day','Courier_Experience_yrs']\n", + "df_clean = df_clean.dropna(subset=cols_to_drop)\n", + "\n", + "\n", + "# I will fill the missing target values with the mean:\n", + "df_clean['Delivery_Time'] = df_clean['Delivery_Time'].fillna(df_clean['Delivery_Time'].mean())\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "\n", + "print(f\"Duplicates: {df_clean.duplicated().sum()}\")\n", + "\n", + "# We have 489 duplicates\n", + "df_clean.drop_duplicates(inplace=True)" + ], + "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", + "categorical_cols = categorical_cols.drop('Traffic_Level')\n", + "\n", + "# Traffic Level is ordinal and so label encoder is needed\n", + "le = LabelEncoder()\n", + "df_clean['Traffic_Level'] = le.fit_transform(df_clean['Traffic_Level'])\n", + "\n", + "# One hot encoding for nominal columns\n", + "df_clean = pd.get_dummies(df_clean, columns=categorical_cols, drop_first=True, dtype=int)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "X = df_clean.drop('Delivery_Time', axis=1).astype(float)\n", + "y = df_clean['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", + "# Prediction task doesn't have classes or imbalance" + ], + "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']" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:\n", + "\n", + "scores = []\n", + "\n", + "kf = KFold(n_splits=5, shuffle=True, random_state=42)\n", + "\n", + "for fold, (train_idx, val_idx) in enumerate(kf.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", + " print(f\"Fold {fold+1}: Train={len(train_idx)}, Val={len(val_idx)}\")\n", + "\n", + " model = RandomForestRegressor(n_estimators=100, max_depth=10, random_state=42)\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", + " scores.append(mae)\n", + "\n", + "\n", + "score = sum(scores)/len(scores)\n", + "\n", + "print(f\"The average score of all folds is: {score}\")\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=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 2: Write your code here:\n", + "plt.hist(y_pred)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:\n", + "\n", + "# Defining the models\n", + "sklearn_models = {\n", + " \"RandomForest\": RandomForestRegressor(\n", + " n_estimators=100,\n", + " max_depth=10,\n", + " random_state=42)\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": [ + "n_splits = 5\n", + "\n", + "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", + " random_f = sklearn_models[\"RandomForest\"]\n", + " catboost = sklearn_models[\"CatBoost\"]\n", + "\n", + " random_f.fit(X_train, y_train)\n", + " catboost.fit(X_train, y_train)\n", + "\n", + " y_pred_random = model.predict(X_test)\n", + " y_pred_catboost = model.predict(X_test)\n", + "\n", + " y_pred_avg = (y_pred_random + y_pred_catboost) / 2\n", + "\n", + " mae = mean_absolute_error(y_test, y_pred_avg)\n", + "\n", + " scores.append(mae)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "print(sum(scores) / len(scores))" + ], + "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/220/Q2.ipynb b/submissions_extracted/220/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..6769e76631935ea6db961a9a3921095b393e2a5d --- /dev/null +++ b/submissions_extracted/220/Q2.ipynb @@ -0,0 +1,392 @@ +{ + "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": [ + "# Imports\n", + "import torch\n", + "import torch.nn as nn\n", + "from torch.optim import Adam, SGD, AdamW\n", + "from torch.utils.data import DataLoader, TensorDataset\n", + "\n", + "import matplotlib.pyplot as plt" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 1. Convert Numpy arrays to PyTorch Tensors\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", + "\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", + "\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][0], cmap='BrBG')\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):\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", + " # Second linear layer: hidden layer -> hidden layer\n", + " self.layer3 = nn.Linear(hidden_dim, hidden_dim)\n", + "\n", + " # Output layer: layer: hidden -> output\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", + " # Second hidden layer\n", + " z3 = self.layer3(a2)\n", + " a3 = self.relu(z3)\n", + "\n", + " # Output layer Raw number for prediction\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).to(device)\n", + "\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.view(-1, 1).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", + "\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", + "\n", + "# Model parameters\n", + "input_dim = 3 * 36 * 36\n", + "hidden_dim = 16 # Design choice\n", + "\n", + "# Instantiate model\n", + "model = NN4Layer(input_dim=input_dim, hidden_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": [ + "# Task 5: Start training for 20 epochs:\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "# Got stuck here with a float TypeError. Part 3 (Plots) is implemented\n", + "\n", + "\n", + "\n", + "\n", + "\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", + "\n", + "\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", + "\n", + "print('Training Complete!')\n", + "\n" + ], + "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/220/Q3.ipynb b/submissions_extracted/220/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..51b887327d457cb88c04a2139b287b2ff5fa908a --- /dev/null +++ b/submissions_extracted/220/Q3.ipynb @@ -0,0 +1,354 @@ +{ + "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": [ + "# Imports\n", + "\n", + "import pandas as pd\n", + "import numpy as np\n", + "from sklearn.model_selection import StratifiedKFold\n", + "from sklearn.preprocessing import StandardScaler, LabelEncoder, OneHotEncoder\n", + "import matplotlib.pyplot as plt\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", + "df_raw = pd.read_csv(\"/kaggle/input/q3-exam-data/Q3_data.csv\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "df_raw.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "df_raw.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "df_raw.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "\n", + "# Checking missing values\n", + "\n", + "# print(\"Missing values per column:\")\n", + "# print(df_raw.isnull().sum())\n", + "# print(f\"\\nTotal missing: {df_raw.isnull().sum().sum()}\")\n", + "\n", + "df = df_raw.copy()\n", + "\n", + "cols = df.columns.drop('Target')\n", + "\n", + "df[cols] = df[cols].fillna(df[cols].mean())" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "print(f\"Duplicates: {df.duplicated().sum()}\")\n", + "\n", + "# No duplicates" + ], + "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", + "print(\"Categorical columns:\", list(categorical_cols))\n", + "\n", + "# There are no categorical columns" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "X = df[cols]\n", + "\n", + "scaler = StandardScaler()\n", + "X_scaled = scaler.fit_transform(X)" + ], + "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'], bins=2, edgecolor='black')\n", + "plt.title('Target Distribution')\n", + "plt.xlabel('Target')\n", + "plt.ylabel('Frequency')\n", + "plt.show()\n", + "\n", + "\n", + "# There is an imbalance, this Stratification is advised" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "X = df[cols]\n", + "y = df['Target']\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "X" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Installing Catboost\n", + "!pip install catboost" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:\n", + "from catboost import CatBoostClassifier\n", + "\n", + "n_splits=5\n", + "\n", + "# To store scores\n", + "accuracy_all = []\n", + "f1_all = []\n", + "\n", + "skf = StratifiedKFold(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", + " model = CatBoostClassifier(n_estimators=320, max_depth=4)\n", + " model.fit(X_train, y_train) # train\n", + " y_pred = model.predict(X_test) # validate\n", + "\n", + " # Calculate evaluation metrics\n", + " accuracy = accuracy_score(y_test, y_pred)\n", + " f1 = f1_score(y_test, y_pred, zero_division=0)\n", + "\n", + " # Store results\n", + " accuracy_all.append(accuracy)\n", + " f1_all.append(f1)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "accuracy_avg = sum(accuracy_all) / len(accuracy_all)\n", + "f1_avg = sum(f1_all) / len(f1_all)\n", + "\n", + "print(f\"Average accuracy is: {accuracy_avg}\")\n", + "print(f\"Average f1 is: {f1_avg}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "\n", + "logistic_importance = list(zip(X.columns, model.feature_importances_))\n", + "sorted_logistic_importance = sorted(logistic_importance, key=lambda x: abs(x[1]), reverse=True)\n", + "sorted_logistic_importance = sorted_logistic_importance[:10] # Choosing the highest 10 features\n", + "\n", + "\n", + "# Extract sorted features and their coefficients\n", + "features, coefficients = zip(*sorted_logistic_importance)\n", + "\n", + "\n", + "\n", + "# Plot feature importances\n", + "plt.figure(figsize=(10, 6))\n", + "plt.barh(features, np.abs(coefficients), color='darkblue')\n", + "plt.xlabel('Coefficient Value')\n", + "plt.ylabel('Features')\n", + "plt.title('Logistic Regression 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(\" The most important feature is: P_2\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:\n", + "\n", + "\n", + "\n", + "\n", + "# Everything worked here except transforming the single feature column into a working array\n", + "\n", + "\n", + "# Error here\n", + "new_X = df['P_2']\n", + "\n", + "X_scaled = scaler.fit_transform(new_X)\n", + "\n", + "\n", + "# Task 2,3,4,5: Write your code here:\n", + "from catboost import CatBoostClassifier\n", + "\n", + "n_splits=5\n", + "\n", + "# To store scores\n", + "accuracy_all_merged = []\n", + "f1_all_merged = []\n", + "\n", + "skf = StratifiedKFold(n_splits, shuffle=True, random_state=42 )\n", + "\n", + "for fold_idx, (train_index, test_index) in enumerate(skf.split(new_X, y)):\n", + " print(f\"\\nFold {fold_idx + 1}/{n_splits}\")\n", + "\n", + " X_train, X_test = new_X.iloc[train_index], new_X.iloc[test_index]\n", + " y_train, y_test = y.iloc[train_index], y.iloc[test_index]\n", + "\n", + " model = CatBoostClassifier(n_estimators=320, max_depth=4)\n", + " model.fit(X_train, y_train) # train\n", + " y_pred = model.predict(X_test) # validate\n", + "\n", + " # Calculate evaluation metrics\n", + " accuracy = accuracy_score(y_test, y_pred)\n", + " f1 = f1_score(y_test, y_pred, zero_division=0)\n", + "\n", + " # Store results\n", + " accuracy_all_merged.append(accuracy)\n", + " f1_all_merged.append(f1)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "accuracy_avg_merged = sum(accuracy_all_merged) / len(accuracy_all_merged)\n", + "f1_avg_merged = sum(f1_all_merged) / len(f1_all_merged)\n", + "\n", + "print(f\"Average accuracy is: {accuracy_avg_merged}\")\n", + "print(f\"Average f1 is: {f1_avg_merged}\")" + ], + "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/221/Q1.ipynb b/submissions_extracted/221/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..92f7b044dd18213fc070a4ac34b4a62708f51119 --- /dev/null +++ b/submissions_extracted/221/Q1.ipynb @@ -0,0 +1,382 @@ +{ + "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 seaborn as sns" + ], + "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)" + ], + "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": [ + "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)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "df.head()" + ], + "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 rows where\n", + "print(f\"Before: {df.shape}\")\n", + "df = df.dropna(subset=['Weather', 'Traffic_Level', 'Time_of_Day', 'Courier_Experience_yrs'])\n", + "print(f\"After dropping missings: {df.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "df['Delivery_Time'] = df['Delivery_Time'].fillna(df['Delivery_Time'].median())" + ], + "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", + "\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": [], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "#Shouldn't we do this after splitting?!\n", + "scaler = StandardScaler()\n", + "scaled = scaler.fit_transform(df)\n", + "\n", + "print(\"Original:\\n\", df)\n", + "print(\"\\nScaled (mean≈0, std≈1):\\n\", scaled)\n", + "print(\"\\nMeans:\", scaled.mean(axis=0))\n", + "print(\"Stds:\", scaled.std(axis=0))" + ], + "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']" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "X.describe()" + ], + "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 sklearn_mse, mean_absolute_error, r2_score\n", + "\n", + "n_splits = 5\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": [ + "from tqdm import tqdm\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" + ], + "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": [ + "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:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: 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 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/221/Q2.ipynb b/submissions_extracted/221/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..e8ee069749d52a43d5bfabba039074bbfd69a57b --- /dev/null +++ b/submissions_extracted/221/Q2.ipynb @@ -0,0 +1,361 @@ +{ + "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.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": [ + "# 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", + "first_sample, _ = train_dataset[0]\n", + "print(f\"Shape of one sample: {first_sample.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", + "\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", + " # 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.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", + "from torch.optim import AdamW\n", + "\n", + "device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n", + "\n", + "input_dim = 3*36*36 # Number of features\n", + "\n", + "hidden_dim = 128 # Design choice\n", + "\n", + "model = NN4Layer(input_dim, hidden_dim,1).to(device)\n", + "\n", + "num_epochs = 20\n", + "\n", + "learning_rate = 0.001\n", + "\n", + "criterion = nn.MSELoss()\n", + "\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": [ + "# Print the model architecture\n", + "print(\"Model Architecture:\\n\")\n", + "print(model)" + ], + "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/221/Q3.ipynb b/submissions_extracted/221/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..ce8e96ef5acc2ed6ce1e4c8ed4bdb04009aeca2b --- /dev/null +++ b/submissions_extracted/221/Q3.ipynb @@ -0,0 +1,284 @@ +{ + "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 seaborn as sns\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()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "missing_percentage = (df.isna().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(50)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "missing = missing_data['Column'].head(50)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "missing = missing.to_list" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "df = df.drop(df[cols], axis=1)" + ], + "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", + "scaler = StandardScaler()\n", + "scaled = scaler.fit_transform(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", + " 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": [ + "!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", + "\n", + "model = CatBoostClassifier(\n", + " verbose=0,\n", + " n_estimators=320,\n", + " max_depth=4\n", + " )\n", + "\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}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "cols = X.columns.to_list" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "print(cols)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Feature importance\n", + "feature_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(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/222/Q1.ipynb b/submissions_extracted/222/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..5b474bb9a0da0573cf706b0272714c98c61fd9d2 --- /dev/null +++ b/submissions_extracted/222/Q1.ipynb @@ -0,0 +1,310 @@ +{ + "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", + "\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", + "# Load the dataset\n", + "q1_path = os.path.join(path, 'Q1_data.csv')\n", + "df_q1 = pd.read_csv(q1_path)\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "print(f\"Dataset shape: {df_q1.shape}\")\n", + "df_q1.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.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.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_q1['Delivery_Time'].dropna(), bins=30, edgecolor='black')\n", + "plt.title('delivery_time dist')\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", + "dfq1_cleaned =df_q1.drop(columns=['Order_ID']).copy()\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "# Missing values\n", + "missing_percentage = (dfq1_cleaned.isnull().sum() / len(dfq1_cleaned)) * 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", + "#i will just drop missing rows since we have enough data.\n", + "df_clean=dfq1_cleaned.dropna(subset=['Delivery_Time']).copy()\n", + "df_clean=df_clean.dropna(subset=['Weather']).copy()\n", + "df_clean=df_clean.dropna(subset=['Traffic_Level']).copy()\n", + "df_clean=df_clean.dropna(subset=['Time_of_Day']).copy()\n", + "df_clean=df_clean.dropna(subset=['Courier_Experience_yrs']).copy()\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "print(\"Missing values:\") #should be none after all of this\n", + "print(df_clean.isnull().sum())" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "from sklearn.preprocessing import OneHotEncoder #import OneHotEncoder\n", + "onehot_encoder = OneHotEncoder(sparse_output=False)\n", + "categ=['Weather','Traffic_Level','Time_of_Day', 'Vehicle_Type']\n", + "le = LabelEncoder()\n", + "df_clean['Weather'] = le.fit_transform(df_clean['Weather'])\n", + "df_clean['Traffic_Level'] = le.fit_transform(df_clean['Traffic_Level'])\n", + "df_clean['Time_of_Day'] = le.fit_transform(df_clean['Time_of_Day'])\n", + "df_clean['Vehicle_Type'] = le.fit_transform(df_clean['Vehicle_Type'])\n", + "df_clean.info() #should be no objects now" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "scaler = StandardScaler()\n", + "cols=['Distance_km','Weather','Traffic_Level','Time_of_Day','Vehicle_Type','Preparation_Time_min','Courier_Experience_yrs','Delivery_Time']\n", + "df_clean[cols]= scaler.fit_transform(df_clean[cols])\n", + "\n", + "df_clean.info()\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 6: Write your code here: LOOKS IMBALANCED TO ME\n", + "plt.figure(figsize=(10, 5))\n", + "plt.hist(df_q1['Delivery_Time'].dropna(), bins=50, edgecolor='black')\n", + "plt.title('delivery_time dist')\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", + "X =df_clean.drop(\"Delivery_Time\", axis=1).astype(float)\n", + "y= df_clean['Delivery_Time'].astype(float)\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:\n", + "\n", + "from sklearn.ensemble import RandomForestRegressor\n", + "from sklearn.metrics import classification_report, confusion_matrix, accuracy_score\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", + "# Train RandomForestRegressor\n", + "model = RandomForestRegressor(n_estimators=100, max_depth=15, random_state=42)\n", + "\n", + "model.fit(X_train, y_train)\n", + "\n", + "\n", + "y_pred = model.predict(X_test)\n", + "mae = mean_absolute_error(y_test, y_pred)\n", + "\n", + "print(mae)\n", + "\n", + "#-------------------\n", + "#from sklearn.model_selection import StratifiedKFold\n", + "\n", + "#skf = StratifiedKFold(n_splits=3, shuffle=True, random_state=42)\n", + "#scores = []\n", + "\n", + "#for fold, (train_idx, test_idx) in enumerate(skf.split(X, y), start=1):\n", + "\n", + " # X_f_train, X_f_val = X_train[train_idx], X_train[test_idx]\n", + " # y_f_train, y_f_val = y_train.iloc[train_idx], y_train.iloc[test_idx]\n", + "\n", + " # model.fit(X_f_train, y_f_train)\n", + " #fold_acc = accuracy_score(y_f_val, model.predict(X_f_val))\n", + " #scores.append(fold_acc)\n", + "\n", + "#print(f\"Final Average Accuracy: {np.mean(scores):.2f}\")\n", + "\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", + "\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('delivery time')\n", + "plt.xlabel(' d 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/222/Q2.ipynb b/submissions_extracted/222/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..5d0e56e6eee5cd3deaed1dc309ab49409cf7a082 --- /dev/null +++ b/submissions_extracted/222/Q2.ipynb @@ -0,0 +1,367 @@ +{ + "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 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.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", + "# 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", + "\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": [ + "# 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))\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", + "\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your model class here:\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", + " # Second 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.layer3(a2))\n", + "\n", + " # Output layer (regression output)\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.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", + "# 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", + "# 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", + "\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", + "# Hyperparameters (feel free to experiment!)\n", + "num_epochs = 20\n", + "learning_rate = 0.001\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!')" + ], + "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 (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/222/Q3.ipynb b/submissions_extracted/222/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..ad4b5e52e56baddd2e04d1d704c0e64ad86a36b4 --- /dev/null +++ b/submissions_extracted/222/Q3.ipynb @@ -0,0 +1,296 @@ +{ + "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", + "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", + "path = os.path.join(path, 'Q3_data.csv')\n", + "df= pd.read_csv(path)\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "\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", + "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", + "\n", + "df_clean =df.drop(columns=missing_data.Column).copy()\n", + "print(\"Missing values:\") #should be none after all of this\n", + "print(df_clean.isnull().sum())\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\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,)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "df_clean.info() #no objects as u see" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "\n", + "from sklearn.preprocessing import StandardScaler, LabelEncoder\n", + "\n", + "scaler = StandardScaler()\n", + "df_scaled=scaler.fit_transform(df_clean)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 1. Is the target imbalanced?\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", + "check_target_imbalance(df, \"Target\")\n", + "\n", + "print(\"Target is imbalanced\")#target is imbalanced" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "\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", + "%pip install kagglehub catboost xgboost tqdm -q\n", + "\n", + "from catboost import CatBoostClassifier\n", + "from sklearn.model_selection import StratifiedKFold\n", + "from sklearn.metrics import accuracy_score, f1_score\n", + "\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n", + "\n", + "models = {\n", + " \"CatBoost\": CatBoostClassifier(\n", + " verbose=0,\n", + " n_estimators=200,\n", + " max_depth=4\n", + " )\n", + "}\n", + "\n", + "results = {}\n", + "\n", + "for model_name in models:\n", + " results[model_name] = {'accuracy': [], 'precision': [], 'recall': [], 'f1': []}\n", + "\n", + "skf = StratifiedKFold(n_splits=5, 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}/{5}\")\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", + "\n", + "feature_cols=df_clean.columns\n", + "\n", + "print(feature_cols)\n", + "\n", + "\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", + "\n", + "print(feature_col)" + ], + "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/223/Q1.ipynb b/submissions_extracted/223/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..76841737e222c80e38f9fd37e6fe2da2712862be --- /dev/null +++ b/submissions_extracted/223/Q1.ipynb @@ -0,0 +1,382 @@ +{ + "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 StratifiedKFold\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 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 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", + "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": [ + "# 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)" + ], + "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": [ + "df.shape" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "df = df.dropna()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "df.shape" + ], + "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", + "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=[\"number\"]).columns.drop(\"Delivery_Time\")\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, 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", + "feature_cols = ['Distance_km','Weather', 'Traffic_Level', 'Time_of_Day','Vehicle_Type', 'Preparation_Time_min', 'Courier_Experience_yrs' ]\n", + "X = df[feature_cols]\n", + "y = df['Delivery_Time']" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:\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", + "#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", + "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", + "#Evaluate using MAE (Mean Absolute Error) ONLY\n", + "y_pred = model.predict(X_test)\n", + "mae = mean_absolute_error(y_test, y_pred)\n", + "#Print the averaged score across all folds\n", + "print(f\"MAE: ${mae:,.2f}\")\n", + "\n" + ], + "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.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 Bonus: Write your code here:\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", + " model = RandomForestRegressor(n_estimators=100, max_depth=20, random_state=42, n_jobs=-1)\n", + "\n", + " model.fit(X_train, y_train)\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": [], + "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/223/Q2.ipynb b/submissions_extracted/223/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..b272ceb7a7fc8632c203fec1d7b96e07ac515db3 --- /dev/null +++ b/submissions_extracted/223/Q2.ipynb @@ -0,0 +1,431 @@ +{ + "cells": [ + { + "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", + "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", + "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", + "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", + "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", + "\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", + "\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", + " 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": [ + "# 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", + "\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", + "# Device setup\n", + "device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n", + "print(\"Running Model on:\", device)\n", + "\n", + "# Model parameters\n", + "input_dim = X_train.shape[1] # Number of tabular features\n", + "hidden_dim = 14 # Design choice (Number of nuerons in each layer)\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", + "\n", + "# Calculate the total number of trainable parameters (why?)\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", + "# 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:\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": [] + }, + { + "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/223/Q3.ipynb b/submissions_extracted/223/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..8dff7f9ae6bd85142a354f9cb028c4b2eb11246b --- /dev/null +++ b/submissions_extracted/223/Q3.ipynb @@ -0,0 +1,322 @@ +{ + "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 StratifiedKFold\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 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 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", + "df = pd.read_csv('/kaggle/input/q3-exam-data/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", + "# 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)\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" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "df.head()" + ], + "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\") # DON'T SCALE THE TARGET\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 = df.columns.drop('Target')\n", + "X = df[feature_cols]\n", + "y = df['Target']" + ], + "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", + "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", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "from catboost import CatBoostClassifier" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "from sklearn.neighbors import KNeighborsClassifier\n", + "import sklearn\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 sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score, confusion_matrix\n", + "\n", + "\n", + "model = XGBClassifier(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", + "#Evaluate using MAE (Mean Absolute Error) ONLY\n", + "y_pred = model.predict(X_test)\n", + "mae = mean_absolute_error(y_test, y_pred)\n", + "#Print the averaged score across all folds\n", + "print(f\"MAE: ${mae:,.2f}\")\n", + "# Calculate metrics\n", + "accuracy = accuracy_score(y_test, y_pred)\n", + "precision = precision_score(y_test, y_pred)\n", + "recall = recall_score(y_test, y_pred)\n", + "f1 = f1_score(y_test, y_pred)\n", + "\n", + "print(\"Accuracy :\", accuracy)\n", + "print(\"Precision:\", precision)\n", + "print(\"Recall :\", recall)\n", + "print(\"F1 Score :\", f1)\n" + ], + "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()\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/224/Q1.ipynb b/submissions_extracted/224/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..0a4428210de7601f8ea71281a5783cd3f1611a0a --- /dev/null +++ b/submissions_extracted/224/Q1.ipynb @@ -0,0 +1,375 @@ +{ + "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", + "from sklearn.preprocessing import OneHotEncoder #import OneHotEncoder\n", + "from sklearn.ensemble import RandomForestRegressor\n", + "from sklearn.linear_model import LogisticRegression\n", + "from sklearn.metrics import f1_score\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", + "import warnings\n", + "warnings.filterwarnings('ignore')\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", + "\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" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "# Load the CSV file\n", + "Q1_data_path = os.path.join(path, 'Q1_data.csv')\n", + "df_Q1data = pd.read_csv(Q1_data_path)\n", + "\n", + "print(f\"Shape: {df_Q1data.shape}\")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "df_Q1data.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "df_Q1data.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "df_Q1data.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_Q1data['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_Q1data = df_Q1data.drop(['Order_ID'], axis=1)\n", + "\n", + "\n", + "\n" + ], + "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_Q1data)\n", + "\n", + "df_Q1data = df_Q1data.fillna(df_Q1data.mean())" + ], + "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_Q1data)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "\n", + "categorical_cols = df_Q1data.select_dtypes(include=[\"object\"]).columns\n", + "\n", + "print(\"Categorical Columns:\", list(categorical_cols))\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_Q1data[col] = le.fit_transform(df_Q1data[col])\n", + "\n", + "df_Q1data.head()\n", + "\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "\n", + "\n", + "numerical_cols = df_Q1data.select_dtypes(include=[\"number\"]).columns.drop(\"Delivery_Time\")\n", + "\n", + "scaler = StandardScaler()\n", + "\n", + "# Apply fit_transform to scale the numerical columns\n", + "df_Q1data[numerical_cols] = scaler.fit_transform(df_Q1data[numerical_cols])\n", + "\n", + "df_Q1data.head()\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 6: Write your code here:\n", + " # Is the target imbalanced? no\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_Q1data, \"Delivery_Time\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "X = df_Q1data.drop(\"Delivery_Time\", axis=1).astype(float)\n", + "y = df_Q1data['Delivery_Time']\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:\n", + "\n", + "# use 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", + "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", + "y_pred = model.predict(X_train)\n", + "\n", + "mae = mean_absolute_error(y_test, y_pred)\n", + "\n", + "print(f\"MAE: ${mae:,.2f}\")\n", + "print(f\"MAE: ${mae.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']\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", + "plt.figure(figsize=(10, 6))\n", + "plt.hist(y_pred, bins=30, edgecolor='black')\n", + "plt.title('Distribution of Predictions')\n", + "plt.xlabel('Predicted Delivery_Time')\n", + "plt.ylabel('Count')\n", + "plt.show()" + ], + "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 catboost import CatBoostRegressor" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "models = {\n", + " \"Random Forest Regressor\": RandomForestRegressor(n_estimators=200),\n", + " \"CatBoost\": CatBoostRegressor(verbose=0)\n", + "}" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "all_results = {}\n", + "\n", + "for name in models:\n", + " all_results[name] = {'mae': [], '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", + " mae = mean_absolute_error(y_test, y_pred)\n", + " all_results[model_name][\"mae\"].append(mae)\n", + " all_results[model_name][\"rmse\"].append(rmse)\n", + " all_results[model_name][\"r2\"].append(r2)\n", + "\n", + "\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/224/Q3.ipynb b/submissions_extracted/224/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..bcb3c7fc23d371f7465be833876c8834266e72ac --- /dev/null +++ b/submissions_extracted/224/Q3.ipynb @@ -0,0 +1,286 @@ +{ + "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", + "from sklearn.preprocessing import OneHotEncoder #import OneHotEncoder\n", + "from sklearn.ensemble import RandomForestRegressor\n", + "from sklearn.linear_model import LogisticRegression\n", + "from sklearn.metrics import f1_score\n", + "from sklearn.metrics import classification_report, confusion_matrix, accuracy_score\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", + "import warnings\n", + "warnings.filterwarnings('ignore')\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", + "\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", + "Q3_data_path = os.path.join(path, 'Q3_data.csv')\n", + "df_Q3data = pd.read_csv(Q3_data_path)\n", + "\n", + "print(f\"Shape: {df_Q3data.shape}\")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "df_Q3data.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "df_Q3data.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "df_Q3data.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_Q3data)\n", + "\n", + "# Drop unnecessary columns\n", + "# df_Q3data = df_Q3data.drop(['P_2', 'S_3','D_142'], axis=1) # salary النل مثير وحذفناه\n", + "# df_Q3data.head()" + ], + "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_Q3data)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "\n", + "categorical_cols = df_Q3data.select_dtypes(include=[\"object\"]).columns\n", + "\n", + "print(\"Categorical Columns:\", list(categorical_cols))\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_Q3data[col] = le.fit_transform(df_Q3data[col])\n", + "\n", + "df_Q3data.head()\n", + "\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "\n", + "numerical_cols = df_Q3data.select_dtypes(include=[\"number\"]).columns.drop(\"Target\")\n", + "\n", + "scaler = StandardScaler()\n", + "\n", + "# Apply fit_transform to scale the numerical columns\n", + "df_Q3data[numerical_cols] = scaler.fit_transform(df_Q3data[numerical_cols])\n", + "\n", + "df_Q3data.head()\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 6: Write your code here:\n", + " # Is the target imbalanced? no\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_Q3data, \"Target\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "X = df_Q3data.drop(\"Target\", axis=1).astype(float)\n", + "y = df_Q3data['Target']\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:\n", + "\n", + "# Import base linear model for classification (Logistic Regression)\n", + "from catboost import CatBoostClassifier\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", + "model = CatBoostClassifier(verbose=0, n_estimators=320,max_depth=4) # instantiate\n", + "model.fit(X_train, y_train) # fit\n", + "y_pred = model.predict(X_test) # predict\n", + "\n", + "\n", + "print(f\"Accuracy: {accuracy_score(y_test, y_pred):.4f}\\n\")\n", + "f1 = f1_score(y_test, y_pred)\n", + "print(\"Accuracy :\", accuracy)\n", + "print(\"F1 Score :\", f1)\n", + "print(f\"Average: ${f1.mean():,.2f}\")\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,\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/225/Q1.ipynb b/submissions_extracted/225/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..ed65aefe3093dfa56b76bc1391718168c246d34f --- /dev/null +++ b/submissions_extracted/225/Q1.ipynb @@ -0,0 +1,348 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import pandas as pd\n", + "import os\n", + "import numpy as np\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/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 Q1_data.csv using read_csv()\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: Inspect the first few rows using head()\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Display dataset information using info()\n", + "df.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Show statistical description using describe()\n", + "df.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: 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", + " 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\")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Drop the 'Order_ID' column from the data\n", + "df = df.drop(columns=\"Order_ID\", axis=1)\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Handle missing values appropriately\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", + "\n", + "\n", + " if missing_values.any():\n", + " print(\"\\nHandle Missing Values as needed.\")\n", + " df.fillna(df.mean(numeric_only=True), inplace=True)\n", + " df.fillna(df.mode, inplace=True)\n", + "\n", + " else:\n", + " print(\"\\nNo Missing Values Found.\")\n", + "\n", + "check_missing_values(df)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: 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", + "\n", + " if duplicates > 0:\n", + " print(\"Dropping Duplicates...\")\n", + " df.drop_duplicates(inplace=True)\n", + " print(\"Duplicates Dropped.\")\n", + "\n", + " else:\n", + " print(\"No Duplicate Samples Found.\")\n", + "check_duplicates(df)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "categories = df.select_dtypes(include=[\"object\"]).columns\n", + "#print(\"Categorical Columns:\", list(categories))\n", + "categories" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Encode categorical variables if needed (Bonus if used One Hot Encoding)\n", + "\n", + "from sklearn.preprocessing import OneHotEncoder\n", + "\n", + "print('data before encoding:\\n', df) #show before encoding\n", + "\n", + "onehot_encoder = OneHotEncoder(sparse_output=False) # Instantiate\n", + "\n", + "#df.head()\n", + "data_onehot_encoded = onehot_encoder.fit_transform(categories)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "print('\\nData after encoding:\\n', data_onehot_encoded)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Apply feature scaling for all features (Use StandardScaler)\n", + "from sklearn.preprocessing import StandardScaler\n", + "print('data before scaling:\\n', df)\n", + "\n", + "standard_scaler = StandardScaler()\n", + "data_standard_scaled = standard_scaler.fit_transform(df)\n", + "print('\\nData after scaling:\\n', data_standard_scaled)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 6: Check for target imbalance and state if it is imbalanced or not (keep this cell empty if not needed)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Split the dataset into features (X) and target (y)\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": [ + "from sklearn.ensemble import RandomForestRegressor\n", + "from sklearn.model_selection import KFold" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "model = RandomForestRegressor(n_estimators=200,\n", + "max_depth=10)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Use the correct split: KFold OR StratifiedKFold\n", + "\n", + "n_splits = 5 # K=5 Folds\n", + "\n", + "kf = KFold(n_splits=n_splits, shuffle=True, random_state=42)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Train a RandomForest model\n", + "\n", + "for fold_idx, (train_index, test_index) in enumerate(kf.split(X, y)):\n", + " print(f\"\\nFold {fold_idx + 1}/{n_splits}\")\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", + " print(f\"Training a RandomForest model...\")\n", + " # Fit the model on train data\n", + " model.fit(X_train, y_train)\n", + " # Use the model to predict the test data\n", + "\n", + " y_pred = model.predict(X_test)\n", + " # Calculate evaluation metrics\n", + "\n", + " accuracy = accuracy_score(y_test, y_pred)\n", + " f1 = f1_score(y_test, y_pred, average='macro') # for multiclass f1 score,\n", + " results[model_name]['accuracy'].append(accuracy)\n", + " results[model_name]['f1'].append(f1)\n", + "\n", + "\n", + "\n", + "# Task 4: Evaluate using MAE (Mean Absolute Error) ONLY\n", + "\n", + "\n", + "\n", + "# Task 5: Print the averaged score across all folds" + ], + "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/225/Q2.ipynb b/submissions_extracted/225/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..40204e1a92ec684269b4840f5e09a1c5a551ea23 --- /dev/null +++ b/submissions_extracted/225/Q2.ipynb @@ -0,0 +1,359 @@ +{ + "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", + "\n", + "csv_path = os.path.join(path, \"labels.csv\")\n", + "df = pd.read_csv(csv_path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import torch\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": [ + "from torch.utils.data import TensorDataset\n", + "from torch.utils.data import DataLoader" + ], + "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", + "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", + "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", + "#X_batch[0]\n", + "sample_image = X_batch[0]\n", + "\n", + "print(f\"\\n Image shape: {sample_image.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import torch.nn as nn" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "class NN4Layer(nn.Module):\n", + " def __init__(self, input_dim):\n", + " super(NN4Layer, self).__init__()\n", + "\n", + " # output activation function\n", + " self.sigmoid = nn.Linear()\n", + "\n", + " # forward pass\n", + " def forward(self, x):\n", + " z = self.layer_1(x)\n", + " a = self.sigmoid(z) # linear\n", + " return a" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "input_dim = 4\n", + "hidden_dim = 3 # number of input features\n", + "\n", + "# number of hidden neurons\n", + "model = NN4Layer(input_dim, hidden_dim)\n", + "\n", + "# Print the model architecture\n", + "print(\"Model Architecture:\\n\")\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_gra ######\n", + "print(f\"\\nTotal trainable parameters: {total_params}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: 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", + " 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", + "\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", + " running_loss += loss.item()\n", + "\n", + "# Average loss over all batches\n", + " avg_loss = running_loss / len(train_loader)\n", + " return avg_loss" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Create a validation loop function\n", + "\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", + "\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", + "\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 1: Create a model class with 4 linear layers\n", + "\n", + "# Create a linear layer: 3 input features -> 1 output\n", + "linear = nn.Linear(in_features=3, out_features=1)\n", + "linear = nn.Linear(in_features=3, out_features=1)\n", + "linear = nn.Linear(in_features=3, out_features=1)\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", + "# Forward through the layer\n", + "y = linear(x)\n", + "print(\"Input shape:\", x.shape) # torch.Size([4, 3])\n", + "print(\"Output shape:\", y.shape) # torch.Size([4, 1])\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 and track training and validation losses\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:" + ], + "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/225/Q3.ipynb b/submissions_extracted/225/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..b264d195f31a239833930e4ae183ce79e0b3bd61 --- /dev/null +++ b/submissions_extracted/225/Q3.ipynb @@ -0,0 +1,476 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "import os\n", + "import pandas as pd\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", + "\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: Inspect the first few rows using head()\n", + "\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Display dataset information using info()\n", + "df.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Show statistical description using describe()\n", + "df.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Handle missing values appropriately\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", + "\n", + "\n", + " if missing_values.any():\n", + " print(\"\\nHandle Missing Values as needed.\")\n", + " df.fillna(df.mean(numeric_only=True), inplace=True)\n", + " #df.fillna(df.mode, inplace=True)\n", + "\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: 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", + "\n", + " if duplicates > 0:\n", + " print(\"Dropping Duplicates...\")\n", + " df.drop_duplicates(inplace=True)\n", + " print(\"Duplicates Dropped.\")\n", + "\n", + " else:\n", + " print(\"No Duplicate Samples Found.\")\n", + "check_duplicates(df)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Encode categorical variables if needed\n", + "\n", + "categories = df.select_dtypes(include=[\"object\"]).columns\n", + "#print(\"Categorical Columns:\", list(categories))\n", + "categories\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "#features = df.select_dtypes(include=[\"float64\"]).columns\n", + "#print(\"Categorical Columns:\", list(categories))\n", + "#features\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Apply feature scaling to numerical features (Use StandardScaler)\n", + "\n", + "from sklearn.preprocessing import StandardScaler\n", + "\n", + "features = df.columns.drop(\"Target\")\n", + "scaler = StandardScaler()\n", + "\n", + "df[features] = scaler.fit_transform(df[features])\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Check for target imbalance and state if it is imbalanced or not\n", + "import matplotlib.pyplot as plt\n", + "\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, \"Target\")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Split the dataset into features (X) and target (y)\n", + "\n", + "X = df.drop(\"Target\", axis=1).astype(float)\n", + "y = df['Target'].astype(float)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "y" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Use the correct split: KFold OR StratifiedKFold\n", + "from sklearn.model_selection import KFold\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" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "%pip install kagglehub catboost lightgbm tqdm -q" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "from catboost import CatBoostRegressor\n", + "models = {\"CatBoost\": CatBoostRegressor(verbose=0)}" + ], + "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 tqdm import tqdm" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "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)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "def categorical_cross_entropy(y, y_hat):\n", + " epsilon = 1e-15\n", + " y_hat = np.clip(y_hat, epsilon, 1 - epsilon)\n", + " loss = -np.mean(np.sum(y * np.log(y_hat), axis=1))\n", + " return loss" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "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", + " # 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", + " # In this row (i), set the specific class column to 1\n", + " one_hot[i, class_label] = 1\n", + " return one_hot" + ], + "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", + " theta = np.zeros((n, num_classes))\n", + "# One-hot encode the labels\n", + " y_onehot = one_hot_encode(y, num_classes)\n", + " losses = []\n", + " for _ in tqdm(range(n_iters), desc=\"Training CatBoostClassifier model\"):\n", + " # Calculate the logits z\n", + " z = np.dot(X, theta)\n", + " # Get class probabilities using softmax\n", + " y_pred = softmax(z)\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", + " # Update weights\n", + " theta -= lr * gradient\n", + " # Track loss\n", + " loss = categorical_cross_entropy(y_onehot, y_pred)\n", + " losses.append(loss)\n", + " return theta, losses" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "for fold_idx, (train_index, test_index) in enumerate(kf.split(X, y)):\n", + " print(f\"\\nFold {fold_idx + 1}/{n_splits}\")\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", + " # Train using gradient descent with learning rate = 0.5\n", + " theta, losses = gradient_descent(X_train, y_train, lr=0.5, num_classes=2)\n", + " # Calculate z & class probabilities for X_test\n", + " z = np.dot(X_test, theta)\n", + " y_pred_proba = softmax(z)\n", + " # Pick the predicted classes with the highest probability\n", + " y_pred = np.argmax(y_pred_proba, axis=1)\n", + " accuracy = accuracy_score(y_test, y_pred)\n", + " f1 = f1_score(y_test, y_pred, average='macro') # for multiclass f1 score, y\n", + " # Store results\n", + " re['loss'].append(losses)\n", + " re['acc'].append(accuracy)\n", + " re['f1'].append(f1)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "re = {}\n", + "for model_name in models:\n", + " re[model_name] = {'accuracy': [], 'f1':[]}" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "for fold_idx, (train_index, test_index) in enumerate(kf.split(X, y)):\n", + "\n", + " print(f\"\\nFold {fold_idx + 1}/{n_splits}\")\n", + " # Get the train & test split for this fold\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(X_train, y_train, lr=0.5, num_classes=4)\n", + " # Calculate z & class probabilities for X_test\n", + " z = np.dot(X_test, theta)\n", + " y_pred_proba = softmax(z)\n", + " # Pick the predicted classes with the highest probability\n", + " y_pred = np.argmax(y_pred_proba, axis=1)\n", + "\n", + " # Train & Validate Models\n", + " for model_name, model in models.items():\n", + " print(f\"Training {model_name}...\")\n", + " # Fit the model on train data\n", + " model.fit(X_train, y_train)\n", + " # Use the model to predict the test data\n", + " y_pred = model.predict(X_test)\n", + " # Calculate evaluation metrics\n", + " accuracy = accuracy_score(y_test, y_pred)\n", + " #f1 = f1_score(y_test, y_pred, average='micro') # for multiclass f1 score,\n", + " results[model_name]['accuracy'].append(accuracy)\n", + " #results[model_name]['f1'].append(f1)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:\n", + "\n", + "for fold_idx, (train_index, test_index) in enumerate(kf.split(X)):\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", + "for model_name, model in models.items():\n", + " print(f\"Training {model_name}...\")\n", + " # Train\n", + " model.fit(X_train, y_train)\n", + " # Predict\n", + " y_pred = model.predict(X_test)\n", + "\n", + "\n", + " # Calculate metrics\n", + " accuracy = accuracy_score(y_test, y_pred)\n", + " f1 = f1_score(y_test, y_pred, average='macro')\n", + "\n", + " results['acc'].append(accuracy)\n", + " results['f1'].append(f1)" + ], + "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/226/Q1.ipynb b/submissions_extracted/226/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..326e84278e58ee4752310733eb4caa742c1a46b3 --- /dev/null +++ b/submissions_extracted/226/Q1.ipynb @@ -0,0 +1,314 @@ +{ + "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", + "from sklearn.preprocessing import StandardScaler, LabelEncoder\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(\"Time\")\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", + "data_col = [\"Order_ID\",\t\"Distance_km\",\t\"Preparation_Time_min\",\t\"Courier_Experience_yrs\",\t\"Delivery_Time\"]\n", + "df_clean = df.drop(\"Order_ID\", axis=1).copy()\n", + "print(f\"Shape after cleaning: {df_clean.shape}\")\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", + "\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", + "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: Apply feature scaling for all features (Use StandardScaler)\n", + "from sklearn.preprocessing import StandardScaler #import StandardScaler\n", + "print(\"Before scaling:\")\n", + "df\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 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", + "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": [ + "from sklearn.ensemble import RandomForestRegressor\n", + "from sklearn.model_selection import KFold" + ], + "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 f1_score\n", + "models = {\"Random Forest Classifier\": RandomForestClassifier(n_estimators=100)}\n", + "\n", + "for model in models.values():\n", + " scores_accuracy = []\n", + " scores_precision = []\n", + " scores_recall = []\n", + " scores_f1 = []\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", + "\n", + " # Calculate metrics\n", + " scores_f1.append(f1_score(y_Test, y_pred, average='weighted'))\n", + "\n", + " # Print the results\n", + " print(f\"F1-Score: {np.mean(scores_f1):.4f}\")\n", + " print(\"\\n\")\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", + "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" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "importance = pd.DataFrame({\n", + " 'feature': df.columns,\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/226/Q2.ipynb b/submissions_extracted/226/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..d6fbe24e4b75019de9a8e2d1f7a7c31ef1836f72 --- /dev/null +++ b/submissions_extracted/226/Q2.ipynb @@ -0,0 +1,384 @@ +{ + "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", + "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", + "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: Create Datasets: Use TensorDataset to create train_dataset and test_dataset from the tensors.\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: Create DataLoaders: Create train_loader and test_loader with a batch size of 32.\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", + "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()\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 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", + " # 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", + " # Output layer: hidden layer -> number of classes (logits)\n", + " self.layer5 = 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", + " 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", + "# 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}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Start training for 20 epochs:\n", + "from torch.optim import Adam\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" + ], + "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", + "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/226/Q3.ipynb b/submissions_extracted/226/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..c6cc13ba98e0606b8c483866048b5878b932b004 --- /dev/null +++ b/submissions_extracted/226/Q3.ipynb @@ -0,0 +1,257 @@ +{ + "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", + "from sklearn.preprocessing import StandardScaler, LabelEncoder\n", + "from catboost import CatBoostClassifier\n", + "from sklearn.model_selection import KFold\n", + "from sklearn.metrics import mean_squared_error, mean_absolute_error\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: 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", + "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: Handle missing values appropriately\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: 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)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here: Encode categorical variables if needed\n", + "\n", + "label_encoder = LabelEncoder()\n", + "\n", + "for col in df.select_dtypes(include=[\"object\"]).columns:\n", + " df[col] = label_encoder.fit_transform(df[col])\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here: Apply feature scaling to numerical features (Use StandardScaler)\n", + "scaler = StandardScaler()\n", + "X_scaled = scaler.fit_transform(df)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here: Check for target imbalance and state if it is imbalanced or not\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": [ + "!pip install catboost" + ], + "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\"]\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:\n", + "\n", + "model = CatBoostClassifier(verbose=0)\n", + "\n", + "kf = KFold(n_splits=5, shuffle=True, random_state=42)\n", + "\n", + "mse_scores = []\n", + "mae_scores = []\n", + "\n", + "for train_idx, test_idx in kf.split(X_scaled):\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", + " # Train model\n", + " model.fit(X_train, y_train)\n", + "\n", + " # Predict\n", + " y_pred = model.predict(X_test)\n", + "\n", + " # Evaluation metrics\n", + " mse_scores.append(mean_squared_error(y_test, y_pred))\n", + " mae_scores.append(mean_absolute_error(y_test, y_pred))\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "feature_importance = pd.DataFrame({\n", + " 'feature': df.columns,\n", + " 'importance': model.feature_importances_\n", + "}).sort_values('importance', ascending=False)\n", + "\n", + "plt.figure(figsize=(10, 30))\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/227/Q1.ipynb b/submissions_extracted/227/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..7c069f00e10580019f70ca921fcf3bdcfa60c168 --- /dev/null +++ b/submissions_extracted/227/Q1.ipynb @@ -0,0 +1,448 @@ +{ + "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 seaborn as sns" + ], + "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", + "# Load the CSV file\n", + "Q1_data_path = os.path.join(path, 'Q1_data.csv')\n", + "\n", + "df_Q1_data = pd.read_csv(Q1_data_path)\n", + "\n", + "print(f\"Shape: {df_Q1_data.shape}\")\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", + "df_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", + "df_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", + "df_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", + "\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_Q1_data, \"Delivery_Time\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "\n", + "#Drop the 'Order_ID' column from the data\n", + "df = df_Q1_data.drop(['Order_ID'], axis=1)\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "\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", + "\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": [ + "# Fill cylinders with mode - discrete feature, mode is most representative\n", + "df['Weather'] = df['Weather'].fillna(df['Weather'].mode()[0])\n", + "\n", + "df['Traffic_Level'] = df['Traffic_Level'].fillna(df['Traffic_Level'].mode()[0])\n", + "\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'].mode()[0])\n", + "\n", + "df['Delivery_Time'] = df['Delivery_Time'].fillna(df['Delivery_Time'].mode()[0])" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "\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", + "\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": [ + "# Task 3: Write your code here:\n", + "\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)" + ], + "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))" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Encode categorical columns - converts text to integers\n", + "from sklearn.preprocessing import StandardScaler, LabelEncoder\n", + "\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": [ + "# 3. Do we have 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 5: Write your code here:\n", + "#Apply feature scaling for all features (Use StandardScaler)\n", + "\n", + "\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()\n" + ], + "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", + "# 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 = 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", + "from sklearn.model_selection import KFold\n", + "\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] #نستخدم .iloc لاستخراج البيانات\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)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "\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, y)\n", + "print(\"Model trained!\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "#Evaluate using MAE (Mean Absolute Error) ONLY\n", + "from sklearn.metrics import mean_absolute_error, mean_squared_error\n", + "\n", + "# 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", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "#Print the averaged score across all folds\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "feature_cols = ['Distance_km', 'Weather', 'Traffic_Level', 'Time_of_Day',\n", + " 'Vehicle_Type', 'Preparation_Time_min', 'Courier_Experience_yrs']" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "#Plot feature importance from your trained model\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", + "#Plot predicted delivery time histogram\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/227/Q2.ipynb b/submissions_extracted/227/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..0e7ad69cd1a6fbf3a2e4f2915ec5f167efc23401 --- /dev/null +++ b/submissions_extracted/227/Q2.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/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": [ + "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" + ], + "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", + "# 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}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 5. Display sample images\n", + "\n", + "\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\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", + "\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 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/228/Q1.ipynb b/submissions_extracted/228/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..84aee0a934a77a71e4728330991340b530de4a67 --- /dev/null +++ b/submissions_extracted/228/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": [ + "# Task 1: Write your code here:\n", + "\n", + "import os\n", + "import pandas as pd\n", + "\n", + "foodDelivery_path = os.path.join(path, 'Q1_data.csv')\n", + "df_foodDelivery = pd.read_csv(foodDelivery_path)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "\n", + "df_foodDelivery.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "\n", + "df_foodDelivery.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "\n", + "df_foodDelivery.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", + "# Delivery_Time distribution (target variable)\n", + "\n", + "plt.hist(df_foodDelivery['Delivery_Time'].dropna(), bins=50, 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_foodDelivery.columns.drop(\"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_foodDelivery)\n", + "\n", + "print(\"Handeling missing values...\")\n", + "\n", + "df_foodDelivery['Weather'] = df_foodDelivery['Weather'].fillna(df_foodDelivery['Weather'].mode()[0])\n", + "df_foodDelivery['Traffic_Level'] = df_foodDelivery['Traffic_Level'].fillna(df_foodDelivery['Traffic_Level'].mode()[0])\n", + "df_foodDelivery['Time_of_Day'] = df_foodDelivery['Time_of_Day'].fillna(df_foodDelivery['Time_of_Day'].mode()[0])\n", + "df_foodDelivery['Courier_Experience_yrs'] = df_foodDelivery['Courier_Experience_yrs'].fillna(df_foodDelivery['Courier_Experience_yrs'].mean())\n", + "df_foodDelivery['Delivery_Time'] = df_foodDelivery['Delivery_Time'].fillna(df_foodDelivery['Delivery_Time'].mean())\n", + "\n", + "print(\"Done\")\n", + "\n", + "df_foodDelivery.head(20)\n", + "\n" + ], + "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_foodDelivery)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "\n", + "from sklearn.preprocessing import LabelEncoder\n", + "\n", + "categorical_cols = df_foodDelivery.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_foodDelivery[col] = le.fit_transform(df_foodDelivery[col].astype(str))\n", + "\n", + "df_foodDelivery.head()\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "\n", + "from sklearn.preprocessing import StandardScaler\n", + "\n", + "numerical_cols = df_foodDelivery.select_dtypes(include=[\"int64\", \"float64\"]).columns.drop(\"Delivery_Time\") # DON'T SCALE THE TARGET\n", + "print(numerical_cols)\n", + "\n", + "scaler = StandardScaler()\n", + "df_foodDelivery[numerical_cols] = scaler.fit_transform(df_foodDelivery[numerical_cols])\n", + "df_foodDelivery.head()\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 6: Write your code here:\n", + "import seaborn as sns\n", + "\n", + "# Is the target imbalanced?\n", + "\n", + "def check_target_imbalance(df, target_column):\n", + " print(\"Target Distribution:\")\n", + " print(df[target_column])\n", + " sns.countplot(x=df[target_column])\n", + " plt.title(\"Target Distribution\")\n", + " plt.show()\n", + "\n", + "check_target_imbalance(df_foodDelivery, \"Delivery_Time\")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "feature_cols = ['Distance_km','Weather',\t'Traffic_Level',\t'Time_of_Day',\t'Vehicle_Type',\t'Preparation_Time_min',\t'Courier_Experience_yrs']\n", + "X = df_foodDelivery[feature_cols]\n", + "y = df_foodDelivery['Delivery_Time']" + ], + "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.ensemble import RandomForestRegressor\n", + "from sklearn.metrics import mean_absolute_error, mean_squared_error\n", + "from sklearn.model_selection import KFold\n", + "from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score\n", + "import numpy as np\n", + "\n", + "\n", + "kf = 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", + "mae = []\n", + "\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", + " # Train\n", + " model.fit(X_train, y_train)\n", + "\n", + " # Predict\n", + " y_pred = model.predict(X_test)\n", + "\n", + " meanabs = mean_absolute_error(y_test, y_pred)\n", + "\n", + " mae.append(meanabs)\n", + " print(\"RandomForestRegressor\")\n", + " print(meanabs)\n", + " print(\"\\n\")\n", + "\n", + "\n", + "print(\"Avrage score across all folds: \\n\")\n", + "sum = 0\n", + "for num in mae:\n", + " sum += num\n", + "\n", + "print(sum / len(mae))\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\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/228/Q2.ipynb b/submissions_extracted/228/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..722790d256b877b3a5f5e60847b1234f36bae773 --- /dev/null +++ b/submissions_extracted/228/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)" + ], + "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", + "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", + "from torch.utils.data import DataLoader, TensorDataset\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" + ], + "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", + "\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))\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" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your model class here:\n", + "\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", + " 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", + " # Output layer (raw scores / logits)\n", + " output = self.layer3(a2) # 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", + "\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", + "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 = 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", + "# Define optimizer\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", + "from torch.optim import Adam\n", + "\n", + "num_epochs = 20\n", + "learning_rate = 0.001\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 (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/228/Q3.ipynb b/submissions_extracted/228/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..9f76e4a818ecb071064352d8030bb4f70f5b362b --- /dev/null +++ b/submissions_extracted/228/Q3.ipynb @@ -0,0 +1,267 @@ +{ + "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", + "df_path = os.path.join(path, 'Q3_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 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", + "df = df.fillna(df.mean())\n", + "\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", + "# 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", + "\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", + "\n", + "import matplotlib.pyplot as plt\n", + "\n", + "# Delivery_Time distribution (target variable)\n", + "\n", + "plt.hist(df['Target'].dropna(), bins=50, edgecolor='black')\n", + "plt.title(f\"Target Distribution ({'Delivery_Time'})\")\n", + "plt.xlabel('Target')\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", + "\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", + "from sklearn.model_selection import StratifiedKFold\n", + "from catboost import CatBoostClassifier\n", + "from sklearn.model_selection import KFold\n", + "from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score\n", + "import numpy as np\n", + "\n", + "\n", + "kf = KFold(n_splits=5, shuffle=True, random_state=42)\n", + "\n", + "model = CatBoostClassifier(\n", + " verbose=0,\n", + " n_estimators=320,\n", + " max_depth=4\n", + " )\n", + "\n", + "all_results = {'accuracy': [], 'precision': [], 'recall': [], 'f1': []}\n", + "\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", + " # 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", + " 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['accuracy'].append(accuracy)\n", + " all_results['precision'].append(precision)\n", + " all_results['recall'].append(recall)\n", + " all_results['f1'].append(f1)\n", + "\n", + "\n", + " print(f\"\\n CatBoosterClassfier:\")\n", + " print(f\" Accuracy: {np.mean(all_results['accuracy']):.4f}\")\n", + " print(f\" Precision: {np.mean(all_results['precision']):.4f}\")\n", + " print(f\" Recall: {np.mean(all_results['recall']):.4f}\")\n", + " print(f\" F1-Score: {np.mean(all_results['f1']):.4f}\")\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/229/Q1.ipynb b/submissions_extracted/229/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..2a88fb091e7ed57732f64f822a5a047267a087e8 --- /dev/null +++ b/submissions_extracted/229/Q1.ipynb @@ -0,0 +1,307 @@ +{ + "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": [ + "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)" + ], + "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'])\n", + "df.head()" + ], + "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)\n", + "df_clean = df.dropna(subset=['Weather', 'Traffic_Level', 'Time_of_Day','Courier_Experience_yrs','Delivery_Time'])\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 OneHotEncoder\n", + "from sklearn.preprocessing import LabelEncoder\n", + "\n", + "label_encoder = LabelEncoder()\n", + "\n", + "categorie= ['Traffic_Level', 'Time_of_Day', 'Vehicle_Type','Weather']\n", + "#categories = pd.DataFrame({\"Weather\": ['Windy', 'Clear', 'Foggy', 'Rainy']})\n", + "#e = OneHotEncoder(sparse_output=False)\n", + "#df_clean = le.fit_transform(categories)\n", + "#print('\\nData after encoding:\\n', df_clean) #show after encoding\n", + "df_clean =label_encoder.fit_transform(categorie)\n", + "print('\\nData after encoding:\\n', df_clean) #show after encoding\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 = df_clean.drop(columns=['Delivery_Time'])\n", + "\n", + "scaler = StandardScaler()\n", + "\n", + "data_standard_scaled = scaler.fit_transform(features)" + ], + "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).astype(float)\n", + "y = df_clean['status'].astype(float)" + ], + "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", + "from sklearn.model_selection import KFold\n", + "from sklearn.metrics import mean_squared_error as sklearn_mse,sklearn_mae\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_mae = []\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", + " mae = sklearn_mae(y_test, y_pred)\n", + "\n", + "\n", + "\n", + " # Store results\n", + " lr_mae.append(mae)\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": [ + "# 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:" + ], + "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/229/Q2.ipynb b/submissions_extracted/229/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..931eaa7e0acb3cde1f156eb8f9fdf6039c8d491a --- /dev/null +++ b/submissions_extracted/229/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", + "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.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", + "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", + "rain_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", + "\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)\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", + "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:\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" + ], + "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/229/Q3.ipynb b/submissions_extracted/229/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..39e0b47822c7ddc231f0fa3d8b418d5b86b6aab1 --- /dev/null +++ b/submissions_extracted/229/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 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", + "df = pd.read_csv(f\"{path}/Q3_data.csv\")\n", + "df.head()" + ], + "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 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" + ], + "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.\")" + ], + "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\") # DON'T 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 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.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 StratifiedKFold\n", + "from sklearn.metrics import accuracy_score, f1_score\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': [], 'f1': []}\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 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)\n", + "\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\" F1-Score: {np.mean(all_results[model_name]['f1']):.4f}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:importances = {}\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", + "print(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/23/Q1.ipynb b/submissions_extracted/23/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..364ac0b4c4fd2df332d434e3ee600c2d3d79fd31 --- /dev/null +++ b/submissions_extracted/23/Q1.ipynb @@ -0,0 +1,241 @@ +{ + "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", + "# 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", + "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", + "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=\"Unnamed: 0\", 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.\")\n", + " else:\n", + " print(\"\\nNo Missing.\")\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", + "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 5: Write your code here:\n", + "from sklearn.preprocessing import MinMaxScaler\n", + "\n", + "features = df.columns.drop(\"Order_ID\")\n", + "\n", + "scaler = MinMaxScaler()\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:\n", + "X = df.drop(\"Order_ID\", axis=1).astype(int)\n", + "y = df['Order_ID'].astype(int)" + ], + "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", + "n_kfold = 5\n", + "\n", + "kf = KFold(n_splits=n_kfold, shuffle=True, random_state=42)\n", + "\n", + "lr_losses = []\n", + "lr_mse = []\n", + "lr_rmse = []\n", + "lr_r2 = []" + ], + "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/23/Q2.ipynb b/submissions_extracted/23/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..e570651758d79c91e83f86ff3dac019965c5d36c --- /dev/null +++ b/submissions_extracted/23/Q2.ipynb @@ -0,0 +1,216 @@ +{ + "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_tarin_tensor = torch.tensor(X_train)\n", + "x_test_tensor = torch.tensor(X_test)\n", + "y_tarin_tensor = torch.tensor(y_train)\n", + "y_test_tensor = torch.tensor(y_test)\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", + "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", + "\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:" + ], + "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/23/Q3.ipynb b/submissions_extracted/23/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..c97832709061629f03a86d1f40306ca8a3e2a744 --- /dev/null +++ b/submissions_extracted/23/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/230/Q1.ipynb b/submissions_extracted/230/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..dd44fb2e4529395c43e9f31715f43f80c9193e02 --- /dev/null +++ b/submissions_extracted/230/Q1.ipynb @@ -0,0 +1,343 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import os\n", + "import pandas as pd\n", + "import matplotlib.pyplot as plt\n", + "from sklearn.preprocessing import StandardScaler, LabelEncoder\n", + "from sklearn.model_selection import train_test_split, KFold\n", + "import numpy as np\n", + "from sklearn.model_selection import train_test_split\n", + "from sklearn.ensemble import RandomForestRegressor\n", + "from sklearn.model_selection import StratifiedKFold\n", + "from sklearn.metrics import mean_absolute_error, mean_squared_error\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": [ + "csv_file_path = os.path.join(path, '/kaggle/input/q1-exam-data/Q1_data.csv')\n", + "\n", + "df = pd.read_csv(csv_file_path)\n", + "\n", + "print(f\"Dataset downloaded to: {path}\")\n", + "print(f\"CSV file loaded from: {csv_file_path}\")\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": [ + "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('the target distribution')\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "df.drop(columns=['Order_ID'])" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 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", + "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": [ + "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", + "\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 = ['Weather', 'Traffic_Level', 'Time_of_Day', 'Vehicle_Type']\n", + "X = df[feature_cols]\n", + "y = df['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", + "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:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "np.random.seed(42)\n", + "\n", + "X_reg = pd.DataFrame({\"Feature_1\": np.random.randn(500)})\n", + "y_reg = 3 * X_reg[\"Feature_1\"] + np.random.randn(500) * 0.5\n", + "X_clf = pd.DataFrame({\"Feature_1\": np.random.randn(500)})\n", + "y_clf = (X_clf[\"Feature_1\"] > 0).astype(int)\n", + "\n", + "X, y = X_clf.copy(), y_clf.copy()\n", + "\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", + "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", + "X, y = X_clf.copy(), y_clf.copy()\n", + "\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(\"---------------------------------------------------\")\n", + "\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", + " 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", + " 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(\"--------------------------------------\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "\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", + "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", + "\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", + " model.fit(X_fold_train, y_fold_train)\n", + " y_fold_pred = model.predict(X_fold_val)\n", + "\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": [ + "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=(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", + "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()\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/230/Q2.ipynb b/submissions_extracted/230/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..5d1895a8a4b88a612286fddb95568dde9b5c2f4c --- /dev/null +++ b/submissions_extracted/230/Q2.ipynb @@ -0,0 +1,316 @@ +{ + "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 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", + "# 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", + "data = load_breast_cancer()\n", + "X = data.data\n", + "y = data.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", + "scaler = StandardScaler()\n", + "X_train = scaler.fit_transform(X_train)\n", + "X_test = scaler.transform(X_test)\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,num_workers=2)\n", + "test_loader = DataLoader(test_dataset,batch_size=32,shuffle=False,num_workers=2)" + ], + "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", + "\n", + "sample_image, sample_label = train_dataset[0]\n", + "print(f\"\\n Image shape: {sample_image.shape}\")\n", + "print(f\"Label: {sample_label}\")" + ], + "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", + " self.layer1 = nn.Linear(input_dim, hidden_dim)\n", + " self.layer2 = nn.Linear(hidden_dim, hidden_dim)\n", + " self.layer3 = nn.Linear(hidden_dim, 1)\n", + " self.relu = nn.ReLU()\n", + "\n", + "\n", + " def forward(self, x):\n", + " a1 = self.relu(self.layer1(x))\n", + "\n", + " a2 = self.relu(self.layer2(a1))\n", + " output = self.layer3(a2)\n", + " return output" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "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", + " 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", + " 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": [ + "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.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", + " 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", + "input_dim = X_train.shape[1]\n", + "hidden_dim = 64\n", + "model = NN3Layer(input_dim, hidden_dim).to(device)\n", + "\n", + "print(\"Model Architecture:\\n\")\n", + "print(model)\n", + "learning_rate = 0.001\n", + "criterion = nn.MSELoss()\n", + "\n", + "optimizer = AdamW(model.parameters(), learning_rate)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "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", + "\n", + " train_loss = train_one_epoch(model, optimizer, criterion, train_loader, device)\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": [ + "# 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", + "model.eval()\n", + "with torch.no_grad():\n", + " predictions = model(X_test.to(device)).cpu().numpy()\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}\")" + ], + "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/230/Q3.ipynb b/submissions_extracted/230/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..e5fda71348e877c8b5cb4de2b6776f9f39a7f573 --- /dev/null +++ b/submissions_extracted/230/Q3.ipynb @@ -0,0 +1,307 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "%pip install catboost -q\n", + "import os\n", + "import pandas as pd\n", + "import matplotlib.pyplot as plt\n", + "from sklearn.preprocessing import StandardScaler, LabelEncoder\n", + "from sklearn.model_selection import train_test_split, KFold\n", + "import numpy as np\n", + "from sklearn.model_selection import train_test_split\n", + "from sklearn.ensemble import RandomForestRegressor\n", + "from sklearn.model_selection import StratifiedKFold\n", + "from sklearn.metrics import mean_absolute_error, mean_squared_error\n", + "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": [ + "import kagglehub\n", + "\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": [ + "# Task 1: Write your code here:\n", + "csv_file_path = os.path.join(path, '/kaggle/input/q3-exam-data/Q3_data.csv')\n", + "\n", + "df = pd.read_csv(csv_file_path)\n", + "\n", + "print(f\"Dataset downloaded to: {path}\")\n", + "print(f\"CSV file loaded from: {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": [ + "def check_missing_values(df):\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": [ + "# 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(\"D_43\")\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:" + ], + "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", + "\n", + "def sigmoid(z):\n", + " return 1 / (1 + np.exp(-z))\n", + "\n", + "def binary_cross_entropy(y, y_hat):\n", + " epsilon = 1e-15\n", + " y_hat = np.clip(y_hat, epsilon, 1 - epsilon)\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", + "def gradient_descent(X, y, learning_rate, n_iters=500):\n", + " m, n = X.shape\n", + " theta = np.zeros(n)\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\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", + "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(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", + "\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", + "\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": [ + "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 = pd.DataFrame({\n", + " 'feature': feature,\n", + " 'importance': model.feature_importances_}).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/231/Q1.ipynb b/submissions_extracted/231/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..fc2b86b8d37bc2795276535c72c64fe1e5e10f3b --- /dev/null +++ b/submissions_extracted/231/Q1.ipynb @@ -0,0 +1,303 @@ +{ + "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": [ + "# imports\n", + "import os\n", + "import pandas as pd\n", + "import matplotlib.pyplot as plt\n", + "from sklearn.preprocessing import StandardScaler, LabelEncoder\n", + "from sklearn.model_selection import StratifiedKFold, train_test_split\n", + "from sklearn.ensemble import RandomForestClassifier\n", + "from sklearn.metrics import mean_absolute_error\n", + "import numpy as np\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "df = pd.read_csv('/kaggle/input/q1-exam-data/Q1_data.csv')" + ], + "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(), bins=50, edgecolor='black')\n", + "plt.title('Target Distribution')\n", + "plt.xlabel('Delievery Time')\n", + "plt.ylabel('Frequency')\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write df 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", + "# Since missing samples are relatively not that much, im gonna drop them\n", + "\n", + "df = df.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", + "check_duplicates(df)" + ], + "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", + "\n", + "for col in categorical_cols:\n", + " le = LabelEncoder()\n", + " df[col] = le.fit_transform(df[col])" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "df.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "\n", + "scaler = StandardScaler()\n", + "\n", + "# i will not be scaling cols that have been encoded and the target varible\n", + "cols_no_target_or_encoded = [\"Distance_km\", \"Preparation_Time_min\", \"Courier_Experience_yrs\" ]\n", + "\n", + "\n", + "df[cols_no_target_or_encoded] = scaler.fit_transform(df[cols_no_target_or_encoded])" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 6: Write your code here:\n", + "\n", + "plt.figure(figsize=(10, 5))\n", + "plt.hist(df[\"Delivery_Time\"].value_counts(), bins=50, edgecolor='black')\n", + "plt.title('Distribution')\n", + "plt.xlabel('Delievery Time')\n", + "plt.ylabel('Frequency')\n", + "plt.show()\n", + "\n", + "# there is an imbalance so doing stratified sampling here would be much better" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "X = df.drop(\"Delivery_Time\", axis=1).copy()\n", + "y = df[\"Delivery_Time\"]\n", + "\n" + ], + "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(\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", + "skf = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)\n", + "\n", + "\n", + "model = RandomForestClassifier(\n", + " n_estimators=200,\n", + " max_depth=10\n", + " )\n", + "mae = []\n", + "mae_sum = 0\n", + "y_preds = []\n", + "\n", + "for fold_idx, (train_index, test_index) in enumerate(skf.split(X, y)):\n", + " print(f\"\\nFold {fold_idx + 1}/{5}\")\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", + " mae_sum+=mean_absolute_error(y_test, y_pred)\n", + " y_preds.append(y_pred)\n", + "\n", + "\n", + "\n", + "\n", + "print(\"MAE:\", mae_sum)\n", + "print(\"avg MAE:\", mae_sum/5)\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "model.feature_importances_" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "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.hist(y_preds)\n", + "plt.show()" + ], + "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/231/Q2.ipynb b/submissions_extracted/231/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..8fde02d2b294701a97751884bb05557edc24dd51 --- /dev/null +++ b/submissions_extracted/231/Q2.ipynb @@ -0,0 +1,387 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import torch\n", + "from torch.utils.data import TensorDataset\n", + "from torch.utils.data import DataLoader, TensorDataset\n", + "import matplotlib.pyplot as plt\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", + "import pandas as pd" + ], + "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": [ + "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" + ], + "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", + "\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}\")" + ], + "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", + " # i put 36 here to match the dimension\n", + " plt.imshow(images[i].reshape(-1,36), 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", + "\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", + " x = x.view(x.size(0), -1)\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": [ + "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.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", + "\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", + "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 = 32 # Design choice\n", + "output_dim = 100\n", + "\n", + "# Instantiate model\n", + "model = NN4Layer(input_dim, hidden_dim, output_dim).to(device)\n", + "optimizer = AdamW(model.parameters(), learning_rate)\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", + "# 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/231/Q3.ipynb b/submissions_extracted/231/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..bb7a8f7412e2e9c0c4ee24bff385d1887165d1ca --- /dev/null +++ b/submissions_extracted/231/Q3.ipynb @@ -0,0 +1,354 @@ +{ + "cells": [ + { + "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.metrics import accuracy_score" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "!pip install catboost" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import pandas as pd\n", + "# imports\n", + "import os\n", + "import pandas as pd\n", + "import matplotlib.pyplot as plt\n", + "from sklearn.preprocessing import StandardScaler, LabelEncoder\n", + "from sklearn.model_selection import StratifiedKFold, train_test_split\n", + "from sklearn.ensemble import RandomForestClassifier\n", + "from sklearn.metrics import mean_absolute_error\n", + "import numpy as np\n", + "from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score\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", + "df = pd.read_csv('/kaggle/input/q3-exam-data/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": [ + "df" + ], + "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" + ], + "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", + "check_duplicates(df)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "\n", + "\n", + "#encoding is needed for target only to use classifier later, i will do encoding after scaling so labels odnt get affected\n", + "\n" + ], + "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", + "\n", + "scaler = StandardScaler()\n", + "\n", + "# i will not be scaling cols that have been encoded and the target varible\n", + "\n", + "\n", + "df[df.columns] = scaler.fit_transform(df[df.columns])" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "le = LabelEncoder()\n", + "df[\"Target\"] = le.fit_transform(df[\"Target\"])" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "target_df = df[\"Target\"]" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "\n", + "\n", + "plt.figure(figsize=(10, 5))\n", + "plt.hist(target_df, bins=50, edgecolor='black')\n", + "plt.title('Distribution')\n", + "plt.show()\n", + "\n", + "\n", + "# there is an imbalance so doing stratified sampling here would be much better" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "X = df.drop(\"Target\", axis=1).copy()\n", + "y = df[\"Target\"]\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "n_splits = 5 # K\n", + "acc_scores = []\n", + "accsum=0\n", + "model = CatBoostClassifier(\n", + " verbose=0,\n", + " n_estimators=320,\n", + " max_depth=4\n", + " )\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", + "# 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", + " 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", + " model.fit(X_train, y_train) # train\n", + " y_pred = model.predict(X_test) # validate\n", + " accuracy = accuracy_score(y_test, y_pred)\n", + " acc_scores.append(accuracy)\n", + " accsum+=accuracy\n", + "\n", + "\n", + "accuracy\n", + "print(accsum/5)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "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": [ + "#printing\n", + "np.argsort(model.feature_importances_)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "for i, (model, 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", + "feature_importance = pd.DataFrame({\n", + " 'importance': model.feature_importances_\n", + "}).sort_values('importance', ascending=False)\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/232/Q1.ipynb b/submissions_extracted/232/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..f867f708ef43f23ab53488b797c44b9e3d735471 --- /dev/null +++ b/submissions_extracted/232/Q1.ipynb @@ -0,0 +1,343 @@ +{ + "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 os\n", + "# Task 1: Write your code here:# Load the CSV file\n", + "csv_path = os.path.join(path, 'Q1_data.csv')\n", + "df = pd.read_csv(csv_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", + "import matplotlib.pyplot as plt\n", + "plt.figure(figsize=(10, 5))\n", + "plt.hist(df['Delivery_Time'], bins=30, edgecolor='black')\n", + "plt.title('Delivery_Time')\n", + "plt.xlabel('time \"minuts\"')\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')\n", + "print(f\"y_test shape: {df.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: 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" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "# Fill categorical columns with 'unknown'\n", + "categorical_cols = df.select_dtypes(include=[\"object\"]).columns\n", + "\n", + "print(\"Categorical Columns:\", list(categorical_cols))\n", + "# just Weather , Traffic_Level , Time_of_Day , has missing categoral values so fill with unkown\n", + "\n", + "for col in ['Weather','Traffic_Level','Time_of_Day']:\n", + " df[col] = df[col].fillna('unknown')" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "\n", + "# Fill numerical columns with 'mode'\n", + "\n", + "for col in ['Delivery_Time','Courier_Experience_yrs']:\n", + " df[col] = df[col].fillna(df[col].mode()[0])\n", + "\n", + "#check missing again\n", + "missing_percentage = (df.isnull().sum() / len(df)) * 100\n", + "missing_percentage\n", + "#data is full" + ], + "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() #check whole row it has same or not\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", + "print(f'shape now {df.shape}')" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "from sklearn.preprocessing import LabelEncoder #import LabelEncoder\n", + "\n", + "print('data before encoding:\\n', categorical_cols) #show before encoding\n", + "\n", + "label_encoder = LabelEncoder() # Instantiate LabelEncoder\n", + "for col in categorical_cols:\n", + " df[col] = label_encoder.fit_transform(df[col]) # Apply fit_transform to the column\n", + " print('\\nData after encoding:\\n', df[col]) #show after encoding\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", + "import seaborn as sns\n", + "def check_target_imbalance(df, target_column):\n", + " print(\"Target Distribution:\")\n", + " print(df[target_column].value_counts())\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", + "# Define features (X) and target (y)\n", + "feature_cols = ['Distance_km','Weather','Traffic_Level','Time_of_Day','Vehicle_Type','Preparation_Time_min','Courier_Experience_yrs']\n", + "X = df[feature_cols]\n", + "y = df['Delivery_Time']\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 = []" + ], + "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", + "models = {\n", + " \"Random Forest Regressor\": RandomForestRegressor(n_estimators=200),\n", + "}\n", + "n_splits = 5\n", + "kf = KFold(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", + " 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", + " print(f\" mae: {np.mean(mae):.4f}\")\n", + "" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "from sklearn.linear_model import Ridge, Lasso\n", + "models = {\n", + " \"Ridge Regression\": Ridge(alpha=1.0, max_iter=10000),\n", + " \"LASSO Regression\": Lasso(alpha=1.0, max_iter=10000),\n", + " \"Random Forest Regressor\": RandomForestRegressor(n_estimators=200),\n", + "}\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/232/Q2.ipynb b/submissions_extracted/232/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..75b7a8f362b2a290143ae06f0351f806f7f662d5 --- /dev/null +++ b/submissions_extracted/232/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", + "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.long)\n", + "y_test = torch.tensor(y_test, dtype=torch.long)\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", + "from torch.utils.data import DataLoader\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", + "\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}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 5. Display sample images\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", + "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", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Start training for 20 epochs:\n", + "from torch.optim import AdamW\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": [ + "# Plotting results\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/232/Q3.ipynb b/submissions_extracted/232/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..5ca1a5a5061cac9f5f77b1946ebdc7f2809209d9 --- /dev/null +++ b/submissions_extracted/232/Q3.ipynb @@ -0,0 +1,293 @@ +{ + "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", + "# Task 1: Write your code here:# Load the CSV file\n", + "csv_path = os.path.join(path, 'Q3_data.csv')\n", + "df = pd.read_csv(csv_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", + "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", + "#if above 30% remove\n", + "missing_data = missing_data[missing_data['Missing_Percentage'] > 30].sort_values('Missing_Percentage', ascending=False)\n", + "\n", + "print(\"Missing Data Analysis:\")\n", + "df = df.drop(columns=missing_data['Column'])\n", + "df.head()" + ], + "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() #check whole row it has same or not\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", + "print(f'shape now {df.shape}')" + ], + "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", + "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\") # 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", + "import matplotlib.pyplot as plt\n", + "def check_target_imbalance(df, target_column):\n", + " print(\"Target Distribution:\")\n", + " print(df[target_column].value_counts())\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", + "#not balanced" + ], + "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", + "# 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 StratifiedKFold\n", + "from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score\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", + "all_results = {}\n", + "\n", + "for name in sklearn_models:\n", + " all_results[name] = {'accuracy': [], 'precision': [], 'recall': [], 'f1': []}\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 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 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/233/Q1.ipynb b/submissions_extracted/233/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..708b59e73fd737b9ebcae2780e3d5191352a2b29 --- /dev/null +++ b/submissions_extracted/233/Q1.ipynb @@ -0,0 +1,338 @@ +{ + "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", + "data_path = os.path.join(path, 'Q1_data.csv')\n", + "df_data = pd.read_csv(data_path)\n", + "\n", + "print(f\"Dataset shape: {df_data.shape}\")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "df_data.head() #showing the first 5" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "df_data.info() #gives us clear info of what we need to know" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "df_data.describe() #describes the scale between data, good for checking the need to scale" + ], + "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_data['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", + "\n", + "df_data.dropna(subset=['Order_ID']) #we do not drop target!\n", + "\n", + "cols = [\t'Distance_km',\t'Weather',\t'Traffic_Level',\t'Time_of_Day',\t'Vehicle_Type',\t'Preparation_Time_min',\t'Courier_Experience_yrs']\n", + "df_clean = df_data.dropna(subset=cols).copy() #cleaning cols with\n", + "print(f\"Shape after cleaning: {df_clean.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "for col in cols:\n", + " df_clean[col] = df_clean[col].fillna('unknown')#fills missing values\n", + "\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_data):\n", + " duplicates = df_data.duplicated().sum()\n", + " print(f\"Number of Duplicate Samples: {duplicates}\")\n", + " if duplicates > 0:\n", + " print(\"Dropping Duplicates...\")\n", + " df_data.drop_duplicates(inplace=True)\n", + " print(\"Duplicates Dropped.\")\n", + " else:\n", + " print(\"No Duplicate Samples Found.\")\n", + "\n", + "check_duplicates(df_data)\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "from sklearn.preprocessing import LabelEncoder\n", + "categorical_cols = df_data.select_dtypes(include=[\"object\"]).columns\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" + ], + "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_data.select_dtypes(include=[\"int64\", \"float64\"]).columns.drop(\"Delivery_Time\") # 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()" + ], + "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", + "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", + "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.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", + "\n", + "#here we go the traditional way of k-fold\n", + "def mean_squared_error(y, y_hat):\n", + " return (1 / (2 * len(y))) * np.sum((y_hat - y) ** 2)\n", + "\n", + "\n", + "\n", + " #defining a gradient descent func\n", + "def gradient_descent(X, y, learning_rate, n_iters=500):\n", + " m, n = X.shape # m rows, n columns\n", + " theta = np.zeros(n) # initialize a zeros weight vector with n dimensions\n", + " losses = []\n", + "\n", + "#here we train the model using everything we did previously\n", + "for _ in df_data(range(5000), desc=\"Training Linear Regression\"):\n", + " y_hat = np.dot(X, theta)\n", + " gradient = np.dot(X.T, (y_hat - y)) / m\n", + " theta -= 0.001 * gradient\n", + "\n", + " loss = mean_squared_error(y, y_hat)\n", + " losses.append(loss)\n", + "\n", + " return theta, losses\n", + "\n", + "lr_losses = []\n", + "lr_mse = []\n", + "lr_rmse = []\n", + "lr_r2 = []\n", + "\n", + "\n", + "n_splits = 5\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", + " # 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", + "\n", + "\n", + "\n", + "\n", + "" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "\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", + "}\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:\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/233/Q2.ipynb b/submissions_extracted/233/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..1e58517524fcc171476f0000d4d24fc97e215f5b --- /dev/null +++ b/submissions_extracted/233/Q2.ipynb @@ -0,0 +1,200 @@ +{ + "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", + "\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/233/Q3.ipynb b/submissions_extracted/233/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..794200b0f56fedddbeae0400718f4c51a62147ca --- /dev/null +++ b/submissions_extracted/233/Q3.ipynb @@ -0,0 +1,286 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "\n", + "from IPython.display import clear_output\n", + "%pip install kagglehub catboost xgboost tqdm -q\n", + "clear_output()\n", + "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", + "from tqdm import tqdm\n", + "%matplotlib inline\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": [ + "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 1: Write your code here:\n", + "\n", + "\n", + "for col in ['P_2',\t'B_2',\t'S_3',\t'D_41','B_3','D_141','D_142','D_143','D_144','D_145']:\n", + " 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)" + ], + "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", + "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", + "from sklearn.preprocessing import StandardScaler\n", + "\n", + "numerical_cols = df.select_dtypes(include=[\"int64\", \"float64\"]).columns.drop(\"Target\") # we don't scale 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\") #there is imbalance" + ], + "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.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 StratifiedKFold\n", + "from sklearn.model_selection import StratifiedKFold\n", + "from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score\n", + "\n", + "sklearn_models = { #defining models\n", + "\n", + " \"CatBoost\": CatBoostClassifier(\n", + " verbose=0,\n", + " n_estimators=320,\n", + " max_depth=4\n", + " )\n", + "}\n", + "all_results = {}\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 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)\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/234/Q1.ipynb b/submissions_extracted/234/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..1002a97134927ffb25dc7624bd904dd3bd165c87 --- /dev/null +++ b/submissions_extracted/234/Q1.ipynb @@ -0,0 +1,246 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "import os\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", + "\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": [ + "\n", + "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", + "\n", + "# Price distribution (target variable)\n", + "plt.figure(figsize=(10, 5))\n", + "plt.hist(df['Delivery_Time'].dropna(), bins=50, 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": [ + " df.drop('Order_ID', axis = 1)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "df.info()" + ], + "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))" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 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": [ + "from sklearn.preprocessing import LabelEncoder\n", + "\n", + "label_encoders = {}\n", + "for col in df:\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:" + ], + "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": [ + "# # Train Random Forest Regressor\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": [ + "#\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}\")\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/234/Q2.ipynb b/submissions_extracted/234/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..85c36dc3fd1c63405fcefc1394be2db2e00916df --- /dev/null +++ b/submissions_extracted/234/Q2.ipynb @@ -0,0 +1,385 @@ +{ + "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.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" + ], + "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" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "\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.float32)\n", + "y_test =torch.tensor(y_test.values, dtype=torch.float32)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "]# Create TensorDatasets for training and testing\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", + "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:" + ], + "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:" + ], + "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.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" + ], + "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) # 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" + ], + "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": [ + "# Hyperparameters (feel free to experiment!)\n", + "num_epochs = 20\n", + "learning_rate = 0.001" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# TODO: Set up the device (use GPU if available, otherwise CPU)\n", + "device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")" + ], + "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": [ + "# Hyperparameters (feel free to experiment!)\n", + "num_epochs = 20\n", + "learning_rate = 0.001" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:" + ], + "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 (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/234/Q3.ipynb b/submissions_extracted/234/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..368509a3cf6cea5f410afa9a0c8b572a1554bf76 --- /dev/null +++ b/submissions_extracted/234/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": [ + "# # Load the dataset\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": [ + "import os\n", + "import pandas as pd" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "df_path = os.path.join(path, 'Q3_data.csv')\n", + "df = pd.read_csv(df_path)\n", + "print(f\"Dataset shape: {df.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "df.head()" + ], + "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", + "# 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": [ + "# 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", + "# 3. Do we have 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", + "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()\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", + "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 xgboost import XGBClassifier\n", + "from catboost import CatBoostClassifier" + ], + "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/235/Q1.ipynb b/submissions_extracted/235/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..ffacc1099b594a981f84c4e05cb05765d13b3b5b --- /dev/null +++ b/submissions_extracted/235/Q1.ipynb @@ -0,0 +1,269 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "import pandas as pd\n", + "import os\n", + "import matplotlib.pyplot as plt\n", + "from sklearn.preprocessing import StandardScaler,LabelEncoder\n", + "from sklearn.model_selection import train_test_split\n", + "import numpy as np\n", + "from sklearn.model_selection import KFold\n", + "from sklearn.ensemble import RandomForestRegressor\n", + "from sklearn.metrics import mean_absolute_error\n", + "from catboost import CatBoostRegressor\n", + "!pip install catboost\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", + "full_path = os.path.join(path, 'Q1_data.csv')" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\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(5)" + ], + "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.isna().sum()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "\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.drop(columns=['Order_ID'],inplace=True) # Order_ID is irrelevant so drop it\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "df['Weather'].fillna(df['Weather'].mode()[0],inplace=True); #mode\n", + "df['Time_of_Day'].fillna(df['Time_of_Day'].mode()[0],inplace=True); #mode\n", + "df['Courier_Experience_yrs'].fillna(df['Courier_Experience_yrs'].mode()[0],inplace=True); #mode\n", + "df['Traffic_Level'].fillna(df['Traffic_Level'].mode()[0],inplace=True); # mode\n", + "df = df.dropna(subset=['Delivery_Time']); # we cannot fill target" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "df.isna().sum()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "duplicates = df.duplicated().sum() # we have 557 duplicated rows we will drop them all\n", + "df = df.drop_duplicates()\n", + "print(f'we have: {duplicates} number of duplicate rows')\n", + "print(f'Duplicates dropped')\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "df = pd.get_dummies(df, columns=['Weather','Time_of_Day','Vehicle_Type','Traffic_Level'],dtype=int) #one hot encoder as aksed\n", + "# recommend some columns such as Traffic_Level, Time_of_Day should be Label encoded becuase depending on trafic and time maybe delivery delay\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "scaler = StandardScaler() # it is wrong to do the scaling on all of the data but i will do as you say.\n", + "df[['Distance_km','Preparation_Time_min']] = scaler.fit_transform(df[['Distance_km','Preparation_Time_min']])" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 6: Write your code here:\n", + "# ITS A REGRESSION PROBLEM THERE IS SKEWING NOT IMBALANCE" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "X = df.drop(columns=['Delivery_Time']) #Features\n", + "y = df['Delivery_Time'] # Target\n", + "\n" + ], + "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) # regression so we use kfold starify only for imbalanced (classification)\n", + "\n", + "metric = []\n", + "\n", + "for fold_idx, (train_index, test_index) in enumerate(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", + " model = RandomForestRegressor(n_estimators=200)\n", + " model.fit(X_train,y_train)\n", + " y_pred = model.predict(X_test)\n", + " mae = mean_absolute_error(y_test,y_pred)\n", + " metric.append(mae)\n", + "\n", + "print(f'Mean MAE: {np.mean(metric)}')" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "pd.Series(model.feature_importances_,index=X.columns).sort_values().plot(kind='barh')\n", + "# as i suggested and said before some of these features should be label encoded because they have order to them" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "pr_time = model.predict(X)\n", + "plt.plot(pr_time,'o-');" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "kf_2 = KFold(n_splits=5, shuffle=True, random_state=42)\n", + "rf = []\n", + "cb = []\n", + "for fold_idx, (train_index, test_index) in enumerate(kf_2.split(X)):\n", + "\n", + " X_train, X_test = X.iloc[train_index], X.iloc[test_index]\n", + " y_train, y_test = y.iloc[train_index], y.iloc[test_index]\n", + "\n", + " model_r = RandomForestRegressor(n_estimators=300)\n", + " model_r.fit(X_train,y_train)\n", + " y_pred_r = model.predict(X_test)\n", + " mae_r = mean_absolute_error(y_test,y_pred_r)\n", + " rf.append(mae_r)\n", + "\n", + "\n", + " model_c = CatBoostRegressor(verbose=0,n_estimators=200)\n", + " model_c.fit(X_train,y_train)\n", + " y_pred_c = model.predict(X_test)\n", + " mae_c = mean_absolute_error(y_test,y_pred_c)\n", + " cb.append(mae_c)\n", + "\n", + "\n", + "print(f'RandomForst: {np.mean(rf)}')\n", + "print(f'Catboost Forst: {np.mean(cb)}')" + ], + "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/235/Q2.ipynb b/submissions_extracted/235/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..fddd7ef4e224519e492d24ffe5b777974f4306c8 --- /dev/null +++ b/submissions_extracted/235/Q2.ipynb @@ -0,0 +1,316 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\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", + "from torch.utils.data import DataLoader, TensorDataset\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)\n", + "X_test = torch.tensor(X_test)\n", + "y_train = torch.tensor(y_train)\n", + "y_test = torch.tensor(y_test)\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" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 4. Print shape of one batch\n", + "x,y = next(iter(train_loader))\n", + "x.shape,y.shape[0]" + ], + "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.imshow(images[i].squeeze())\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 Regression(nn.Module):\n", + "\n", + " def __init__(self, input_dim, hidden_dim):\n", + "\n", + " super(Regression, 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", + " # non-linearity activation function\n", + " self.relu = nn.ReLU()\n", + "\n", + " # forward pass\n", + " def forward(self, x):\n", + " x = self.layer1(x)\n", + " x = self.relu(x)\n", + " x = self.layer2(x)\n", + " x = self.relu(x)\n", + " x = self.layer3(x)\n", + " x = self.relu(x)\n", + " x= self.layer4(x)\n", + " return a2" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "def train_one_epoch(model, optimizer, criterion, train_loader):\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)\n", + " y_batch = y_batch\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):\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 # shape: (batch_size, num_features)\n", + " y_batch = y_batch # shape: (batch_size, 1)\n", + "\n", + " # Forward pass (continuous output)\n", + " outputs = model(X_batch)\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", + "\n", + "model = Regression(3*36*36,64)\n", + "num_epochs = 20\n", + "learning_rate = 0.001\n", + "\n", + "criterion = nn.MSELoss()\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", + "\n", + " # Train one epoch\n", + " train_loss = train_one_epoch(model, optimizer, criterion, train_loader)\n", + "\n", + " # Validate\n", + " val_loss, val_accuracy = validate(model, criterion, test_loader)\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/235/Q3.ipynb b/submissions_extracted/235/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..a33af122d5608382e7cb3edb9757f4f558044a59 --- /dev/null +++ b/submissions_extracted/235/Q3.ipynb @@ -0,0 +1,237 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "!pip install catboost\n", + "import kagglehub\n", + "import pandas as pd\n", + "import os\n", + "import matplotlib.pyplot as plt\n", + "from sklearn.preprocessing import StandardScaler,LabelEncoder\n", + "from sklearn.model_selection import train_test_split\n", + "import numpy as np\n", + "from sklearn.model_selection import KFold\n", + "from sklearn.metrics import mean_absolute_error\n", + "from sklearn.model_selection import StratifiedKFold\n", + "from sklearn.metrics import accuracy_score, f1_score\n", + "from catboost import CatBoostClassifier\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)\n", + "full_path = os.path.join(path, 'Q3_data.csv')" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\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(3)" + ], + "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.drop(columns=['D_142'],inplace = True) # more than 90% is messing\n", + "\n", + "# i didnt have time to do the rest but i know the catboostclassifier can handle the nulls.\n", + "\n", + "df.isna().sum()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "df.duplicated().sum() # no duplicates exists" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "numerical_cols = df.select_dtypes(include=['object']).columns\n", + "print(f'categorical features: {len(numerical_cols)}')" + ], + "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=['int64','float64']).columns.drop('Target')\n", + "df[numerical_cols] = scaler.fit_transform(df[numerical_cols])\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "df['Target'].value_counts().plot(kind='bar'); # it is extremely unbalanced" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "df['Target'].dtype" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "X = df.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", + "# Task 2,3,4,5: Write your code here:\n", + "skf = StratifiedKFold(n_splits=5, shuffle=True, random_state=42) # classifiers\n", + "\n", + "f1_mean = []\n", + "acc_mean = []\n", + "for fold_idx, (train_index, test_index) in enumerate(skf.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", + " model = CatBoostClassifier(verbose=0,n_estimators=300,max_depth=4)\n", + " model.fit(X_train,y_train)\n", + " y_pred = model.predict(X_test)\n", + " f1 = f1_score(y_test,y_pred)\n", + " acc = accuracy_score(y_test,y_pred)\n", + " f1_mean.append(f1)\n", + " acc_mean.append(acc)\n", + "\n", + "print(f'Mean MAE: {np.mean(f1_mean)}')\n", + "print(f'Mean accuracy: {np.mean(acc_mean)}')" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "pd.Series(model.feature_importances_,index=X.columns)[:14].sort_values().plot(kind='barh') #limited to only 10 because we have alot and all\n", + "#are 0 importance" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "print(f'most important feature is: {pd.Series(model.feature_importances_,index=X.columns)[:1].sort_values(ascending=False)}')" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "skf = StratifiedKFold(n_splits=5, shuffle=True, random_state=42) # classifiers\n", + "x = X['P_2']\n", + "\n", + "f1_mean_2 = []\n", + "acc_mean_2 = []\n", + "\n", + "for fold_idx, (train_index, test_index) in enumerate(skf.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", + " model = CatBoostClassifier(verbose=0,n_estimators=300,max_depth=4)\n", + " model.fit(X_train,y_train)\n", + " y_pred = model.predict(X_test)\n", + " f1 = f1_score(y_test,y_pred)\n", + " acc = accuracy_score(y_test,y_pred)\n", + " f1_mean_2.append(f1)\n", + " acc_mean_2.append(acc)\n", + "\n", + "print(f'Mean MAE: {np.mean(f1_mean)}')\n", + "print(f'Mean Accuracy: {np.mean(acc_mean)}')" + ], + "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/236/Q1.ipynb b/submissions_extracted/236/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..84227d3cf1ee69f22df18a73805cf38ece2e9c3b --- /dev/null +++ b/submissions_extracted/236/Q1.ipynb @@ -0,0 +1,409 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "import numpy as np\n", + "import pandas as pd\n", + "pd.set_option(\"display.max_columns\", None)\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.metrics import accuracy_score,classification_report,confusion_matrix,mean_squared_error,r2_score\n", + "from sklearn.neighbors import KNeighborsClassifier\n", + "from sklearn.neighbors import KNeighborsRegressor\n", + "from sklearn.svm import SVC\n", + "from sklearn.svm import SVR\n", + "from sklearn.tree import DecisionTreeClassifier\n", + "from sklearn.tree import DecisionTreeRegressor\n", + "from sklearn.ensemble import RandomForestClassifier\n", + "from sklearn.ensemble import RandomForestRegressor\n", + "from xgboost import XGBClassifier\n", + "from xgboost import XGBRegressor\n", + "import os\n", + "from IPython.display import clear_output\n", + "\n", + "!pip install dask[dataframe] catboost\n", + "\n", + "clear_output()\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", + "csv_path = os.path.join(path, \"Q1_data.csv\")\n", + "\n", + "df = pd.read_csv(csv_path)\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "\n", + "df.head()" + ], + "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:\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(columns=['Order_ID'])" + ], + "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)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "df=df.drop(columns=['Weather'])\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "df['Delivery_Time']=df['Delivery_Time'].fillna(df['Delivery_Time'].mode()[0])\n", + "df['Courier_Experience_yrs']=df['Courier_Experience_yrs'].fillna(df['Courier_Experience_yrs'].mode()[0])\n", + "df['Time_of_Day']=df['Time_of_Day'].fillna(df['Time_of_Day'].mode()[0])\n", + "df['Traffic_Level']=df['Traffic_Level'].fillna(df['Traffic_Level'].mode()[0])" + ], + "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 4: Write your code here:\n", + "from sklearn.preprocessing import LabelEncoder\n", + "le = LabelEncoder()\n", + "\n", + "# Encode the target column\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'])\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", + "features = df.columns.drop(['Traffic_Level','Time_of_Day','Vehicle_Type']) # 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", + "\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:\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.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 sklearn.model_selection import KFold\n", + "from sklearn.metrics import mean_squared_error as sklearn_mse, mean_absolute_error, r2_score\n", + "from catboost import CatBoostRegressor\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "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", + " \"Random Forest Regressor\": RandomForestRegressor(n_estimators=200),\n", + " \"CatBoost\": CatBoostRegressor(verbose=0)\n", + "\n", + "}" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "all_results = {}\n", + "lmae = []\n", + "\n", + "\n", + "for name in models:\n", + " all_results[name] = {'mae': []}" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "n_splits = 5\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", + "\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\" mae: {np.mean(all_results[model_name]['mae']):.4f}\")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "coeffs = {}\n", + "\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:\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(\"(Ground Truth)\")\n", + "plt.ylabel(\"Predicted \")\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", + "\n", + "# was done above" + ], + "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/236/Q2.ipynb b/submissions_extracted/236/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..7178e274a1a990e47879d2fbb9d75200e7a220d4 --- /dev/null +++ b/submissions_extracted/236/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", + "import numpy as np\n", + "import pandas as pd\n", + "pd.set_option(\"display.max_columns\", None)\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.metrics import accuracy_score,classification_report,confusion_matrix,mean_squared_error,r2_score\n", + "from sklearn.neighbors import KNeighborsClassifier\n", + "from sklearn.neighbors import KNeighborsRegressor\n", + "from sklearn.svm import SVC\n", + "from sklearn.svm import SVR\n", + "from sklearn.tree import DecisionTreeClassifier\n", + "from sklearn.tree import DecisionTreeRegressor\n", + "from sklearn.ensemble import RandomForestClassifier\n", + "from sklearn.ensemble import RandomForestRegressor\n", + "from xgboost import XGBClassifier\n", + "from xgboost import XGBRegressor\n", + "from torch.utils.data import DataLoader, TensorDataset\n", + "import torch\n", + "import torch.nn as nn\n", + "from torch.optim import Adam\n", + "import matplotlib.pyplot as plt\n", + "import torch.nn.functional as F\n", + "\n", + "\n", + "import warnings\n", + "warnings.filterwarnings(\"ignore\")\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": [ + "# 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", + "\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", + "\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", + "# 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", + "\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", + "# 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", + "# 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\n", + "\n", + "# TODO: choose number of hidden neurons\n", + "hidden_dim = 14\n", + "\n", + "# TODO: what are the number of classes ?\n", + "output_dim = 10\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" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Run Training\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", + "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/236/Q3.ipynb b/submissions_extracted/236/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..5a82fc8d03e0334e3cde6a7598640e6c05e580bf --- /dev/null +++ b/submissions_extracted/236/Q3.ipynb @@ -0,0 +1,310 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "import numpy as np\n", + "import pandas as pd\n", + "pd.set_option(\"display.max_columns\", None)\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.metrics import accuracy_score,classification_report,confusion_matrix,mean_squared_error,r2_score\n", + "from sklearn.neighbors import KNeighborsClassifier\n", + "from sklearn.neighbors import KNeighborsRegressor\n", + "from sklearn.svm import SVC\n", + "from sklearn.svm import SVR\n", + "from sklearn.tree import DecisionTreeClassifier\n", + "from sklearn.tree import DecisionTreeRegressor\n", + "from sklearn.ensemble import RandomForestClassifier\n", + "from sklearn.ensemble import RandomForestRegressor\n", + "import os\n", + "%pip install kagglehub catboost xgboost tqdm -q\n", + "\n", + "\n", + "\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", + "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": [ + "df[]" + ], + "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", + "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", + "# 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", + "\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\") # DON'T 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 5: 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, \"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 catboost import CatBoostClassifier\n", + "from sklearn.model_selection import StratifiedKFold\n", + "from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score\n", + "models = {\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 models:\n", + " all_results[name] = {'accuracy': [], 'precision': [], 'recall': [], 'f1': []}\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", + "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", + " 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": [ + "# Retrieve CatBoost feature importances and sort them\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, 15))\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", + "df['P_2']" + ], + "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/237/Q1.ipynb b/submissions_extracted/237/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..31fa82ac5c6adb15799f7940b21119e46b42e215 --- /dev/null +++ b/submissions_extracted/237/Q1.ipynb @@ -0,0 +1,292 @@ +{ + "cells": [ + { + "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, KFold\n", + "from sklearn.preprocessing import StandardScaler, LabelEncoder,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')\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", + "dpath = os.path.join(path, 'Q1_data.csv')\n", + "df = pd.read_csv(dpath)\n", + "df" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "df.head(1)" + ], + "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 code here:\n", + "df.drop(columns=['Order_ID'])\n" + ], + "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", + "for col in ['Weather', 'Traffic_Level', 'Time_of_Day']:\n", + " df[col] = df[col].fillna('unknown')\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", + " df.drop_duplicates(inplace=True)\n", + "\n", + "check_duplicates(df)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "X = df.drop(columns=['Delivery_Time'])\n", + "y = df['Delivery_Time']\n", + "\n", + "# Encode categorical columns - converts text to integers\n", + "categorical_cols = ['Weather'\t,'Traffic_Level','Time_of_Day'\t,'Vehicle_Type']\n", + "for col in categorical_cols:\n", + " le = LabelEncoder()\n", + " df[col] = le.fit_transform(df[col].astype(str))\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "\n", + "X = df.drop(columns=['Delivery_Time'])\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" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 6: 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, \"Delivery_Time\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here: already done at part2 task 5" + ], + "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", + "from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score\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_splits = 5\n", + "skf = StratifiedKFold(n_splits=n_splits, shuffle=True, random_state=42)\n", + "\n", + "model= RandomForestClassifier( n_estimators=320, max_depth=4)\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) # 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", + " # 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" + ], + "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/237/Q2.ipynb b/submissions_extracted/237/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..655822fe8b2b8370411c9bc077004fd9d7d4c721 --- /dev/null +++ b/submissions_extracted/237/Q2.ipynb @@ -0,0 +1,366 @@ +{ + "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", + "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", + "# 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", + "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=20, shuffle=True)\n", + "test_loader = DataLoader(test_dataset, batch_size=20, shuffle=False)\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 4. Print shape of one batch\n", + "\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: Write your model class here:\n", + "import torch.nn as nn\n", + "\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", + " 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", + "\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", + " 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", + "# Device setup\n", + "device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n", + "\n", + "# Model parameters\n", + "input_dim = 3888\n", + "hidden_dim = 14 # Design choice\n", + "output_dim = 10\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}\")" + ], + "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", + "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", + "# 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/238/Q1.ipynb b/submissions_extracted/238/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..5d1a7a71cb9588e0f94766f7e6b26f0a8d22e954 --- /dev/null +++ b/submissions_extracted/238/Q1.ipynb @@ -0,0 +1,374 @@ +{ + "cells": [ + { + "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", + "import os\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/q1-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "print(os.listdir(path))\n", + "# print the files in the dirctry to know which onw to use" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "df = pd.read_csv(path +\"/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", + "\n", + "y = df['Delivery_Time']\n", + "plt.figure(figsize=(7, 5))\n", + "\n", + "plt.plot(y)\n", + "plt.title('delivery_time')\n", + "plt.xlabel('samples')\n", + "plt.legend()\n", + "\n", + "# plt.tight_layout()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "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": [ + "df.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "df_clean = df.copy()\n", + "def pmis(df_clean):\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", + " print(missing_data.head(10))\n", + "\n", + "pmis(df_clean)\n", + "df_clean.info()\n", + "df_clean=df_clean.dropna(subset=['Delivery_Time'])\n", + "df_clean=df_clean.dropna(subset=['Courier_Experience_yrs'])\n", + "# we drom the missing in the y becouse we can not hundel it\n", + "pmis(df_clean)\n", + "\n", + "\n", + "df_clean = df_clean.fillna('unknown')\n", + "\n", + "pmis(df_clean)\n", + "# we filled \"unknown\" in all missing values exapt in y\n", + "df_clean.isnull().sum()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "print(\"duplicated: \",df_clean.duplicated().sum())\n", + "df_clean.drop_duplicates(inplace=True)\n", + "\n", + "print(\"duplicated: \",df_clean.duplicated().sum())\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "le = LabelEncoder()\n", + "df_clean['Vehicle_Type'] = le.fit_transform(df_clean['Vehicle_Type'])\n", + "df_clean['Time_of_Day'] = le.fit_transform(df_clean['Time_of_Day'])\n", + "df_clean['Traffic_Level'] = le.fit_transform(df_clean['Traffic_Level'])\n", + "df_clean['Weather'] = le.fit_transform(df_clean['Weather'])\n", + "\n", + "df_clean.info()\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "#using one hut encoder\n", + "from sklearn.preprocessing import OneHotEncoder\n", + "categories = pd.DataFrame({\"types\": ['Vehicle_Type', 'Time_of_Day', 'Traffic_Level', 'Weather']})\n", + "\n", + "print('data before encoding:\\n', categories)\n", + "\n", + "onehot_encoder = OneHotEncoder(sparse_output=False)\n", + "data_onehot_encoded = onehot_encoder.fit_transform(categories)\n", + "print('\\nData after encoding:\\n', data_onehot_encoded)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "scaler = StandardScaler()\n", + "X_scaled = scaler.fit_transform(df_clean)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import seaborn as sns\n", + "\n", + "# 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", + "\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": [ + "X_train.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "from sklearn.model_selection import StratifiedKFold\n", + "from sklearn.ensemble import RandomForestClassifier\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:\n", + "\n", + "# task 2)\n", + "\n", + "n_splits = 5 # K=5 Folds\n", + "\n", + "skf = StratifiedKFold(n_splits=n_splits, shuffle=True, random_state=42)\n", + "\n", + "# task 3)\n", + "\n", + "model = RandomForestClassifier(n_estimators=100, max_depth=15, random_state=42)\n", + "model.fit(X_train, y_train)\n", + "y_pred = model.predict(X_test)\n", + "\n", + "\n", + "# task 4)\n", + "mae = mean_absolute_error(y_test, y_pred)\n", + "\n", + "print(f\"MAE: ${mae:,.2f}\")\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "feature_cols = [ \"Distance_km\",\"Weather\",\"Traffic_Level\",\"Time_of_Day\", \"Vehicle_Type\",\"Preparation_Time_min\", \"Courier_Experience_yrs\"]" + ], + "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.figure(figsize=(7, 5))\n", + "\n", + "plt.plot(y_pred)\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/238/Q2.ipynb b/submissions_extracted/238/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..fe1c1250932b3b3a00452d3b310eee259ce10019 --- /dev/null +++ b/submissions_extracted/238/Q2.ipynb @@ -0,0 +1,439 @@ +{ + "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" + ], + "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", + "import os\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", + "\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", + "\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}\")" + ], + "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", + " 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", + " # 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", + " # Second hidden layer\n", + " z3 = self.layer3(a2)\n", + " a3 = self.relu(z3)\n", + "\n", + " # Output layer (raw scores / logits)\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", + "\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(X_batch.size(0), -1).to(device)\n", + "\n", + " # we use batch size each time becouse in each time in the loop the batch size will change\n", + "\n", + " # Forward pass\n", + " outputs = model(X_batch).view(X_batch.size(0), 1)\n", + " # print(outputs.shape, y_batch.shape)\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", + " # 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", + "\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", + "hidden_dim = 64\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": [ + "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" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Start training for 20 epochs:\n", + "\n", + "\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", + " 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:\n", + "images, labels = next(iter(train_loader))\n", + "labels_pred = model(images.view(-1,3888))\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 {labels_pred[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/238/Q3.ipynb b/submissions_extracted/238/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..dde3c9ee5243d2950700804a8ba29d0f63df1558 --- /dev/null +++ b/submissions_extracted/238/Q3.ipynb @@ -0,0 +1,290 @@ +{ + "cells": [ + { + "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", + "import os\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", + "\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": [ + "print(os.listdir(path))\n", + "# print the files in the dirctry to know which onw to use" + ], + "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", + "df_clean = df.copy()\n", + "def pmis(df_clean):\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", + " print(missing_data.head(10))\n", + " return missing_data\n", + "\n", + "# pmis(df_clean)\n", + "# df_clean.info()\n", + "# we drom the missing in the y becouse we can not hundel it\n", + "pmis(df_clean)\n", + "\n", + "\n", + "df_clean = df_clean.fillna('unknown')\n", + "\n", + "pmis(df_clean)\n", + "# we filled \"unknown\" in all missing values exapt in y\n", + "df_clean.isnull().sum()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "print(\"duplicated: \",df_clean.duplicated().sum())\n", + "\n", + "# no duplicated\n" + ], + "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", + "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", + "scaler = StandardScaler()\n", + "df_clean = scaler.fit_transform(df_clean)\n" + ], + "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_clean)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "X = df_clean.drop(axis=1)\n", + "y = df_clean\n", + "\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": [ + "from sklearn.model_selection import StratifiedKFold\n", + "from sklearn.ensemble import RandomForestClassifier\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:\n", + "\n", + "# task 2)\n", + "\n", + "n_splits = 5 # K=5 Folds\n", + "\n", + "skf = StratifiedKFold(n_splits=n_splits, shuffle=True, random_state=42)\n", + "\n", + "# task 3)\n", + "\n", + "model = RandomForestClassifier(n_estimators=100, max_depth=15, random_state=42)\n", + "model.fit(X_train, y_train)\n", + "y_pred = model.predict(X_test)\n", + "\n", + "\n", + "# task 4)\n", + "mae = mean_absolute_error(y_test, y_pred)\n", + "\n", + "print(f\"MAE: ${mae:,.2f}\")\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", + "print(feature_importance[0])" + ], + "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/239/Q1.ipynb b/submissions_extracted/239/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..896e37afdbec5e71f90c273940b129d5e68aa79e --- /dev/null +++ b/submissions_extracted/239/Q1.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/q1-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "#import important laibraries\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", + "from tqdm import tqdm" + ], + "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": [ + "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:\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 5: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "df.drop('Order_ID',axis=1,inplace=True)\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 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": [ + "cols_names=['Weather','Traffic_Level','Time_of_Day']\n", + "\n", + "for col in cols_names:\n", + " print(col ,len(df[col].unique()))" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "Weather_counts = df['Weather'].value_counts()\n", + "plt.figure(figsize=(10, 5))\n", + "plt.bar(Weather_counts.index, Weather_counts.values, color='teal')\n", + "plt.title('Weather Distribution')\n", + "plt.xlabel('Weather ')\n", + "plt.ylabel('Count')\n", + "plt.xticks(rotation=45)\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "Traffic_Level_counts = df['Traffic_Level'].value_counts()\n", + "plt.figure(figsize=(10, 5))\n", + "plt.bar(Traffic_Level_counts.index, Traffic_Level_counts.values, color='teal')\n", + "plt.title('Traffic_Level Distribution')\n", + "plt.xlabel('Traffic_Level ')\n", + "plt.ylabel('Count')\n", + "plt.xticks(rotation=45)\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "Time_of_Day_counts = df['Time_of_Day'].value_counts()\n", + "plt.figure(figsize=(10, 5))\n", + "plt.bar(Time_of_Day_counts.index, Time_of_Day_counts.values, color='teal')\n", + "plt.title('Time_of_Day_counts Distribution')\n", + "plt.xlabel('Time_of_Day_counts ')\n", + "plt.ylabel('Count')\n", + "plt.xticks(rotation=45)\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "for var in df.columns:\n", + " print(var,'contain',len(df[var].unique()),'labels')\n", + " #here i display the lables" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "from sklearn.model_selection import train_test_split\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.2, random_state = 4,shuffle=True )\n", + "\n", + "print(\"x train shape is : \",X_train.shape)\n", + "print(\"x test shape is : \",X_test.shape)\n", + "print(\"y train shape is : \",y_train.shape)\n", + "print(\"y test shape is : \",y_test.shape)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "#here i want to categorical to be fill with mode and the num fill with median i know i split before and i know the data are small its not matter\n", + "categorical_columns_miss=[col for col in X.columns if df[col].dtype=='object']\n", + "\n", + "num_columns_miss= [col for col in X.columns if df[col].dtype'float64']\n", + "\n", + "miss_cat=[col for col in X.categorical_columns_miss if X[col].isnull().sum()>0]\n", + "miss_num=[col for col in X.num_columns_miss if X[col].isnull().sum()>0]\n", + "\n", + "for df1 in [X_test,X_train]:\n", + " for col in miss_num:\n", + " col_median=X_train[col].median()\n", + " df1[col].fillna(col_median,inplace=True)\n", + "\n", + "for df2 in [X_test,X_train]:\n", + " for col in miss_cat:\n", + " col_mpde=X_train[col].mode()\n", + " df1[col].fillna(col_median,inplace=True)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "df_clean.isnull().sum()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: 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.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": [], + "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": [ + "from sklearn.ensemble import RandomForestRegressor\n", + "from sklearn.metrics import mean_absolute_error, mean_squared_error\n", + "\n", + "model = RandomForestRegressor(n_estimators=100, max_depth=5, random_state=42, n_jobs=-1)\n", + "model.fit(X_train, y_train)\n", + "print(\"Model trained!\")\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:\n", + "#here another approch call voting you combine between multiple modela and give the good performance but as i mention above i cant solve and have a sloution in only 3 hours and exam iam sceintic i can tell you how we will solve it no implment without any sourse\n", + "from sklearn.ensemble import VotingClassifier\n", + "\n", + "voting_clf = VotingClassifier(\n", + " estimators=[\n", + " ('xgb', best_models['XGBoost']['Best Estimator']),\n", + " ('gb', best_models['RandomForestRegressor']['Best Estimator']),\n", + " ('lr', best_models['CatBoostRegressor']['Best Estimator'])\n", + " ],\n", + " voting='soft'\n", + ")\n", + "\n", + "voting_clf.fit(X_resampled, y_resampled)\n", + "\n", + "y_pred_voting = voting_clf.predict(X_test_selected)\n", + "y_proba_voting = voting_clf.predict_proba(X_test_selected)[:, 1]\n", + "\n", + "evaluate_model(\"Voting Classifier\", y_test, y_pred_voting, y_proba_voting)" + ], + "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/239/Q2.ipynb b/submissions_extracted/239/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..85e5d33188851e1bb1dcbe0f09e83f36ca8b5cde --- /dev/null +++ b/submissions_extracted/239/Q2.ipynb @@ -0,0 +1,392 @@ +{ + "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 pandas as pd\n", + "import torch\n", + "import torch.nn as nn\n", + "from torch.optim import Adam\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)\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", + "\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}\")" + ], + "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", + " 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", + " 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", + " train_losses = []\n", + "\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", + " epoch_loss += loss.item()\n", + "\n", + " avg_loss = epoch_loss / len(train_loader)\n", + " train_losses.append(avg_loss)\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", + "device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n", + "\n", + "# Model parameters\n", + "input_dim = 36 * 36\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", + "num_epochs = 20\n", + "learning_rate = 0.001\n", + "\n", + "# Define criterion (loss function) - using mse because regrresion\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", + "val_accuracies = []\n", + "\n", + "for epoch in range(20):\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 = train_one_epoch(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}/{20}] | Loss: {avg_loss:.6f}\")" + ], + "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", + "# 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/239/Q3.ipynb b/submissions_extracted/239/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..dd197361b2242d518376673d552a348c2efc9de4 --- /dev/null +++ b/submissions_extracted/239/Q3.ipynb @@ -0,0 +1,247 @@ +{ + "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 important laibraries\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", + "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": [ + "# 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 need to encodedd because all num" + ], + "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", + "scaled = scaler.fit_transform(df)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "df['Target'].value_counts().plot(kind='bar', color=['blue', 'orange'])\n", + "plt.title('Distribution of Target Variable (y)')\n", + "plt.xlabel('Class')\n", + "plt.ylabel('Count')\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "# we will use StratifiedKFold because they are in balance data\n", + "X = df.drop(['Target'], axis=1)\n", + "y = df['Target']\n", + "\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 sklearn.model_selection import KFold, StratifiedKFold, cross_val_score\n", + "from catboost import CatBoostClassifier\n", + "\n", + "kfold = KFold(n_splits=5, shuffle=True, random_state=42)\n", + "model = CatBoostClassifier()\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": [ + "from sklearn.ensemble import ExtraTreesClassifier\n", + "\n", + "\n", + "model = ExtraTreesClassifier()\n", + "model.fit(X_train, y_train)\n", + "\n", + "feat_importances = pd.Series(model.feature_importances_, index=X_train.columns)\n", + "\n", + "plt.figure(figsize=(12, 15))\n", + "feat_importances.nlargest(48).sort_values().plot(kind='barh', color='skyblue')\n", + "plt.title('Top 48 Features by Importance (ExtraTreesClassifier)')\n", + "plt.xlabel('Feature Importance')\n", + "plt.tight_layout()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:\n", + "#here i can use this SelectKBest,chi2 here an lasso or ridge but as i mention the time time and without any good resourses how i can perform i know its advance but i learn it\n", + "from sklearn.feature_selection import SelectKBest, chi2\n", + "\n", + "selector = SelectKBest(score_func=chi2, k='all')\n", + "selector.fit(X_train, y_train)\n", + "\n", + "scores = selector.scores_\n", + "feature_scores = pd.Series(scores, index=X_train.columns)\n", + "top_features = feature_scores.nlargest(42)\n", + "\n", + "plt.figure(figsize=(10,8))\n", + "top_features.sort_values().plot(kind='barh')\n", + "plt.title('Top Features by Chi2 Score')\n", + "plt.xlabel('Chi2 Score')\n", + "plt.ylabel('Features')\n", + "plt.grid(True)\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/24/Q1.ipynb b/submissions_extracted/24/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..2fb325cee4a73b4b8d1bdb8f84a70d2e2cfcd162 --- /dev/null +++ b/submissions_extracted/24/Q1.ipynb @@ -0,0 +1,270 @@ +{ + "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", + "\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", + "dataset_path = os.path.join(path, 'Q1_data.csv')\n", + "df = pd.read_csv(dataset_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", + "\n", + "df['Delivery_Time'].hist(bins= 20)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "df.drop(columns= 'Order_ID')\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "clean_df = df.dropna(subset=['Weather','Traffic_Level','Time_of_Day','Courier_Experience_yrs','Delivery_Time'])" + ], + "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(clean_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 = ['Weather', 'Traffic_Level', 'Time_of_Day', 'Vehicle_Type']\n", + "for col in categorical_cols:\n", + " le = LabelEncoder()\n", + " clean_df[col] = le.fit_transform(clean_df[col])\n", + "\n", + "clean_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", + "\n", + "features = df.columns.drop(\"Delivery_Time\")\n", + "scaler = StandardScaler()\n", + "clean_df[features] = scaler.fit_transform(clean_df[features])\n", + "clean_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:\n", + "X = clean_df.drop(\"Delivery_Time\", axis=1).astype(float)\n", + "y = clean_df['Delivery_Time'].astype(float)" + ], + "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", + "total_mae = 0\n", + "mae_count = 0\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", + " model = RandomForestRegressor(n_estimators=100, max_depth=20, random_state=42, n_jobs=-1)\n", + " model.fit(X_train, y_train)\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(\"Model trained!\")\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", + " total_mae+= mae\n", + " mae_count+=1\n", + " print(f\"MAE: ${mae:,.2f}\")\n", + " print(f\"RMSE: ${rmse:,.2f}\")\n", + " print(\"-\" * 30)\n", + "\n", + "avg_mae = total_mae/mae_count\n", + "print(f'AVG mae = {avg_mae}')" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\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" + ], + "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/24/Q2.ipynb b/submissions_extracted/24/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..d303e3f189ecd1077ad5dd9be369161392049ca0 --- /dev/null +++ b/submissions_extracted/24/Q2.ipynb @@ -0,0 +1,204 @@ +{ + "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)\n", + "X_test = torch.tensor(X_test)\n", + "y_train = torch.tensor(y_train)\n", + "y_test = torch.tensor(y_test)" + ], + "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)" + ], + "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)\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", + "import matplotlib.pyplot as p\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/24/Q3.ipynb b/submissions_extracted/24/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..521840408e1411d2febc895e3f0a26f9586e5ace --- /dev/null +++ b/submissions_extracted/24/Q3.ipynb @@ -0,0 +1,176 @@ +{ + "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)\n" + ], + "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", + "dataset_path = os.path.join(path, 'Q3_data.csv')\n", + "df = pd.read_csv(dataset_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", + "\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", + "columns = df.columns\n", + "\n", + "for col in columns:\n", + " if df[col].isnull().sum() == df[col].count():\n", + " df.drop(columns=[col])\n", + "\n", + "df.isnull().sum()" + ], + "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/240/Q1.ipynb b/submissions_extracted/240/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..c0d52d4a77894692bdab5f009659c842de40d98c --- /dev/null +++ b/submissions_extracted/240/Q1.ipynb @@ -0,0 +1,344 @@ +{ + "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, \"/kaggle/input/q1-exam-data/Q1_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()\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 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.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: 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", + "\n", + "df=df.dropna()\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", + "from sklearn.preprocessing import OneHotEncoder\n", + "from sklearn.preprocessing import LabelEncoder\n", + "le = LabelEncoder()\n", + "categorical_cols = df.select_dtypes(include=[\"object\"]).columns\n", + "onehot_encoder = OneHotEncoder(sparse_output=False)\n", + "df[categorical_cols]= le.fit_transform(categorical_cols)\n", + "df.info()\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", + "standard_scaler = StandardScaler()\n", + "data_standard_scaled = standard_scaler.fit_transform(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", + "\n", + " df[target_column].hist() # Yeah you can just do this :)\n", + " plt.show()\n", + "\n", + "check_target_imbalance(df, \"Delivery_Time\")\n", + "#it's impalance" + ], + "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.ensemble import RandomForestRegressor\n", + "from sklearn.metrics import mean_absolute_error as mae1\n", + "model=RandomForestRegressor(n_estimators=200)\n", + "\n", + "\n", + "from sklearn.model_selection import StratifiedKFold\n", + "from sklearn.metrics import accuracy_score, f1_score\n", + "n_splits = 5 # K=5 Folds\n", + "lr_mae = []\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", + " # Train\n", + " model.fit(X_train, y_train)\n", + " y_pred = model.predict(X_test)\n", + " # Validate\n", + "\n", + "\n", + " mae=mae1(y_test, y_pred)\n", + " lr_mae.append(mae)\n", + "np.mean(lr_mae)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "# Feature importance\n", + "importances =model.feature_importances_\n", + "features = X.columns\n", + "feature_importance = pd.DataFrame({\n", + " 'features': features,\n", + " 'importance': model.feature_importances_\n", + "}).sort_values('importance', ascending=False)\n", + "\n", + "plt.figure(figsize=(10, 6))\n", + "plt.barh(feature_importance['features'], 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(bins=30, edgecolor='black')\n", + "plt.title(f\"Target Distribution ({'Delivery_Time'})\")\n", + "plt.xlabel('target_column')\n", + "plt.ylabel(\"Frequency\")\n", + "plt.grid(False)\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "!pip install catboost" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:\n", + "\n", + "from sklearn.ensemble import RandomForestRegressor\n", + "from catboost import CatBoostRegressor\n", + "from sklearn.metrics import mean_absolute_error as mae1\n", + "models = {\n", + " \"Random Forest Regressor\": RandomForestRegressor(n_estimators=200),\n", + " \"CatBoost\": CatBoostRegressor(verbose=0)\n", + "}\n", + "\n", + "all_results = {}\n", + "\n", + "for name in models:\n", + " all_results[name] = {'mae':[]}\n", + "\n", + "from sklearn.model_selection import StratifiedKFold\n", + "from sklearn.metrics import f1_score\n", + "n_splits = 5 # K=5 Folds\n", + "lr_mae = []\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", + " for model_name, model in models.items():\n", + " print(f\"Training {model_name}...\")\n", + " # Train\n", + " model.fit(X_train, y_train)\n", + " #prediction of both models\n", + " y_pred = model.predict(X_test)\n", + " #calculating MAE\n", + " mae=mae1(y_test, y_pred)\n", + "\n", + " all_results[model_name][\"mae\"].append(mae)\n", + "\n", + "\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}\")" + ], + "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/240/Q2.ipynb b/submissions_extracted/240/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..5cced804b3a7805826a6be9d22270a5c6365675f --- /dev/null +++ b/submissions_extracted/240/Q2.ipynb @@ -0,0 +1,462 @@ +{ + "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", + "# 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.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", + "\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 = CIFAR10(root='./datasets', train=True, transform=to_tensor, download=True)\n", + "# Testing dataset\n", + "test_dataset = CIFAR10(root='./datasets', train=False, transform=to_tensor, download=True)\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", + "\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", + "# 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", + "# 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", + "\n", + "X_batch.shape" + ], + "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()\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", + " # 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", + "\n", + "\n", + " # TODO: What are the dimensions of previous and output layer? (hint: hidden neurons? num of classes?)\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)#YOUR CODE HERE)\n", + " a1 = self.relu(z1)#YOUR CODE HERE)\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", + "\n", + "\n", + " # Output layer TODO\n", + " z4 = self.layer4(a3)# )\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", + "\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)# \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)# \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)# , dim=1)\n", + "\n", + " # TODO: Multiclass predictions\n", + " predicted = torch.argmax(probabilities, dim=1)# , 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" + ], + "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", + "# 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 = 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}\")" + ], + "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": [ + "# 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:\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 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='rgb')\n", + " plt.title(f\"True: {labels[i]} | Pred: {predictions[i]}\")\n", + " plt.axis('off')\n", + "\n", + "plt.tight_layout()\n", + "plt.show()\n", + "'''\n", + "Loading images...\n", + "X_train shape: (1600, 3, 36, 36)\n", + "X_test shape: (400, 3, 36, 36)\n", + "y_train shape: (1600,)\n", + "y_test shape: (400,)\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/240/Q3.ipynb b/submissions_extracted/240/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..9483059473fa6b55e7e02664bd52c3a775cd2850 --- /dev/null +++ b/submissions_extracted/240/Q3.ipynb @@ -0,0 +1,343 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "!pip install catboost" + ], + "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", + "\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", + "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 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.fillna(df.mean())\n", + "check_missing_values(df)\n", + "df.head()" + ], + "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.head()\n", + "df['D_142']" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "#There is no catagorial columns but i did it anyway\n", + "from sklearn.preprocessing import OneHotEncoder\n", + "from sklearn.preprocessing import LabelEncoder\n", + "le = LabelEncoder()\n", + "categorical_cols = df.select_dtypes(include=[\"object\"]).columns\n", + "onehot_encoder = OneHotEncoder(sparse_output=False)\n", + "df[categorical_cols]= le.fit_transform(categorical_cols)\n", + "df.info()\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "from sklearn.preprocessing import StandardScaler\n", + "standard_scaler = 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", + "# 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, \"Target\")\n", + "\n", + "#there is clear imbalanced\n", + "#we use Stratifed kfold and F1 metric" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "# Task 1: Write your code here:\n", + "\n", + "X = df.drop(\"Target\", axis=1).astype(float)\n", + "y = df['Target'].astype(float)\n", + "\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:\n", + "from sklearn.metrics import f1_score# i will use F1 because of imbalance\n", + "from catboost import CatBoostClassifier\n", + "model=CatBoostClassifier(\n", + " verbose=0,\n", + " n_estimators=320,\n", + " max_depth=4\n", + " )\n", + "from sklearn.metrics import mean_absolute_error as mae1\n", + "\n", + "\n", + "\n", + "from sklearn.model_selection import StratifiedKFold\n", + "from sklearn.metrics import accuracy_score, f1_score\n", + "n_splits = 5 # K=5 Folds\n", + "lr_mae = []\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", + " # Train\n", + " model.fit(X_train, y_train)\n", + " y_pred = model.predict(X_test)\n", + " # Validate\n", + "\n", + "\n", + " mae=mae1(y_test, y_pred)\n", + " lr_mae.append(mae)\n", + "print(f\" F1-Score average: {np.mean(lr_mae):.4f}\")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "'''\n", + "\n", + "\n", + "\n", + "\n", + "fig, axes = plt.subplots(1, figsize=(18, 6))\n", + "axes = axes.flatten()\n", + "\n", + "\n", + "\n", + "model_name,imp=importances.items()\n", + "sorted_idx = np.argsort(imp)\n", + "ax = axes[0]\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", + "\n", + "plt.tight_layout()\n", + "plt.show()\n", + "'''\n", + "importances =model.feature_importances_\n", + "features = X.columns\n", + "feature_importance = pd.DataFrame({\n", + " 'features': features,\n", + " 'importance': model.feature_importances_\n", + "}).sort_values('importance', ascending=False).head(10)\n", + "\n", + "plt.figure(figsize=(10, 6))\n", + "plt.barh(feature_importance['features'], 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", + "#The most important feature is P_2\n", + "print(df['P_2'])\n", + "print(\"The most important feature is :P_2\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:\n", + "X=df[\"P_2\"].astype(float)\n", + "y = df['Target'].astype(float)\n", + "X.info()\n", + "\n", + "#_---\n", + "from sklearn.metrics import f1_score# i will use F1 because of imbalance\n", + "from catboost import CatBoostClassifier\n", + "model=CatBoostClassifier(\n", + " verbose=0,\n", + " n_estimators=320,\n", + " max_depth=4\n", + " )\n", + "from sklearn.metrics import mean_absolute_error as mae1\n", + "\n", + "\n", + "\n", + "from sklearn.model_selection import StratifiedKFold\n", + "from sklearn.metrics import accuracy_score, f1_score\n", + "n_splits = 5 # K=5 Folds\n", + "lr_mae = []\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", + " # Train\n", + " model.fit(X_train, y_train)\n", + " y_pred = model.predict(X_test)\n", + " # Validate\n", + "\n", + "\n", + " mae=mae1(y_test, y_pred.sequeze(-1,1))\n", + " lr_mae.append(mae)\n", + "print(f\" F1-Score average: {np.mean(lr_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/241/Q1.ipynb b/submissions_extracted/241/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..beef79eeda2e210103c99f2d59cd019f9c0dab57 --- /dev/null +++ b/submissions_extracted/241/Q1.ipynb @@ -0,0 +1,324 @@ +{ + "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", + "\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", + "# Load the dataset\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", + "\n", + "print(f\"Dataset shape: {df_Q1.shape}\")\n", + "df_Q1.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "\n", + "df_Q1.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "\n", + "# Descriptive statistics for numerical columns\n", + "df_Q1.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "\n", + "df_Q1['Delivery_Time']\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Delivery_Time distribution (target variable)\n", + "plt.figure(figsize=(10, 5))\n", + "plt.plot(df_Q1['Delivery_Time'].dropna())\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", + "\n", + "df_Q1.drop(columns=['Order_ID'])" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "\n", + "# Select relevant columns, we do not select 'model' (too many unique values, too sparse and will hurt the model performance)\n", + "cols = ['Distance_km', 'Weather', 'Traffic_Level', 'Time_of_Day', 'Vehicle_Type', 'Preparation_Time_min', 'Courier_Experience_yrs', 'Delivery_Time']\n", + "df_clean = df_Q1[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=['Distance_km', 'Weather', 'Traffic_Level', 'Time_of_Day', 'Vehicle_Type', 'Preparation_Time_min', 'Courier_Experience_yrs', 'Delivery_Time'])\n", + "print(f\"After dropping missing values: {df_clean.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "\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_Q1)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "\n", + "# 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", + " 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", + "\n", + "\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", + "\n", + "# 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_Q1, \"Delivery_Time\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "\n", + "# Define features and target\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_clean[feature_cols]\n", + "y = df_clean['Delivery_Time']\n", + "\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", + "\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", + "\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", + "\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['Delivery_Time'].dropna(), bins=30, edgecolor='black', color='orange')\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/241/Q2.ipynb b/submissions_extracted/241/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..a421cf610fa665ec5b03b6e19aaf2db1471e5d27 --- /dev/null +++ b/submissions_extracted/241/Q2.ipynb @@ -0,0 +1,479 @@ +{ + "cells": [ + { + "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" + ], + "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", + "# 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" + ], + "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 # 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", + "\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", + "print(f\"\\n Image shape: {sample_image.shape}\") # (1, 28, 28)\n", + "print(f\"Label: {sample_label}\")\n", + "\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\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", + "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" + ], + "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", + "\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 = 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", + "# 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", + "\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", + "\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 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/241/Q3.ipynb b/submissions_extracted/241/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..5487220517f5f731342bf166dc6d513ceac78ff9 --- /dev/null +++ b/submissions_extracted/241/Q3.ipynb @@ -0,0 +1,412 @@ +{ + "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", + "\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_path = os.path.join(path, 'Q3_data.csv')\n", + "df_Q3 = pd.read_csv(Q3_path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "\n", + "print(f\"Dataset shape: {df_Q3.shape}\")\n", + "df_Q3.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "\n", + "df_Q3.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "\n", + "df_Q3.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "\n", + "# Do we have missing values?\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_Q3)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "\n", + "# Check for duplicates\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_Q3)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "\n", + "# Do we have categorical columns?\n", + "categorical_cols = df_Q3.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", + "scaler = StandardScaler()\n", + "df_Q3= scaler.fit_transform(df_Q3)" + ], + "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_Q3,'Target')" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "!pip install xgboost" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "!pip install catboost" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "\n", + "from catboost import CatBoostClassifier\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "models = {\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": [ + "results = {}\n", + "\n", + "for model_name in models:\n", + " results[model_name] = {'accuracy': [], 'precision': [], 'recall': [], 'f1': []}" + ], + "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": [ + "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": [ + "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", + "\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 2,3,4,5: Write your code here:\n", + "\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}\")" + ], + "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", + "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/242/Q1.ipynb b/submissions_extracted/242/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..35c22495e929b0c0d79b2b13853ed3b8de9f6b37 --- /dev/null +++ b/submissions_extracted/242/Q1.ipynb @@ -0,0 +1,247 @@ +{ + "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", + "import pandas as pd\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": [ + "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", + "\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": [ + "df = df.drop(\"Order_ID\", axis=1).copy()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "\n", + "df[\"Delivery_Time\"] = df[\"Delivery_Time\"].fillna(df[\"Delivery_Time\"].mean())\n", + "df[\"Weather\"] = df[\"Weather\"].fillna(\"Unknown\")\n", + "df[\"Traffic_Level\"] = df[\"Traffic_Level\"].fillna(\"Unknown\")\n", + "df[\"Time_of_Day\"] = df[\"Time_of_Day\"].fillna(\"Unknown\")\n", + "df[\"Courier_Experience_yrs\"] = df[\"Courier_Experience_yrs\"].fillna(df[\"Courier_Experience_yrs\"].mean())\n", + "df.isna().sum()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "print(df.duplicated().sum())\n", + "\n", + "df = df.drop_duplicates()\n", + "print(df.duplicated().sum())" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "from sklearn.preprocessing import LabelEncoder\n", + "df.info()\n", + "categorical_cols = df.select_dtypes(include=[\"object\"]).columns\n", + "\n", + "for col in categorical_cols:\n", + " encoder = LabelEncoder()\n", + " df[col] = encoder.fit_transform(df[col])\n", + "df.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "from sklearn.preprocessing import StandardScaler\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": [ + "df[\"Delivery_Time\"].value_counts()\n", + "\n", + "#The target is imbalanced" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "X = df.drop(\"Delivery_Time\",axis=1).copy()\n", + "y = df[\"Delivery_Time\"].copy()" + ], + "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_absolute_error\n", + "\n", + "lr_mae =[]\n", + "maes = 0\n", + "model = RandomForestRegressor(n_estimators=100,max_depth=20, random_state=42)\n", + "n_splits = 10\n", + "kf = KFold(n_splits=n_splits, shuffle=True, random_state=42)\n", + "y_pred =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", + " # Train\n", + " model.fit(X_train,y_train)\n", + "\n", + " # Predict\n", + " y_pred = model.predict(X_test)\n", + " # Calculate evaluation metrics\n", + " mae = mean_absolute_error(y_test, y_pred)\n", + "\n", + " maes = maes+mae\n", + " # Store results\n", + " lr_mae.append(mae)\n", + "\n", + "print(f\"Avg: {maes/n_splits}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Feature importance\n", + "feature_importance = pd.DataFrame({\n", + " 'feature': numerical_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.hist(y_pred)\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/242/Q2.ipynb b/submissions_extracted/242/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..8e39a9ec3f0a4c962245b7921adbfbccb6d12dd8 --- /dev/null +++ b/submissions_extracted/242/Q2.ipynb @@ -0,0 +1,347 @@ +{ + "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\n", + " images.append(img_array)\n", + " ages.append(age)\n", + "\n", + "X = np.array(images)\n", + "y = np.array(ages)\n", + "\n", + "\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 DataLoader, TensorDataset\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", + "\n", + "train_dataset = TensorDataset(X_train, y_train)\n", + "test_dataset = TensorDataset(X_test, y_test)\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", + "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", + "plt.imshow(train_dataset[0][0])\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)\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", + "\n", + " X_batch = X_batch.to(device)\n", + " y_batch = y_batch.to(device)\n", + "\n", + "\n", + " outputs = model(X_batch)\n", + " loss = criterion(outputs, y_batch)\n", + "\n", + "\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)\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", + " # 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", + "input_dim = 36*36\n", + "print(X_train.shape)\n", + "print(input_dim)\n", + "hidden_dim = 10\n", + "output_dim = 1\n", + "\n", + "# Instantiate model\n", + "model = NN4Layer(input_dim, hidden_dim, output_dim).to(device)\n", + "\n", + "learning_rate = 0.001\n", + "\n", + "criterion = nn.MSELoss()\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", + "val_accuracies = []\n", + "\n", + "num_epochs =20\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": [ + "\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/242/Q3.ipynb b/submissions_extracted/242/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..75cff71bd33fc1ecb8d314103cb5a934b04c619d --- /dev/null +++ b/submissions_extracted/242/Q3.ipynb @@ -0,0 +1,248 @@ +{ + "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", + "print(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", + "cols = df.columns.drop(\"Target\")\n", + "\n", + "for col in cols:\n", + " df[col] = df[col].fillna(df[col].mean())\n", + "df.isna().sum()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "df.duplicated().sum()" + ], + "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", + "categorical_cols\n", + "\n", + "#There is 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=[\"int64\", \"float64\"]).columns.drop(\"Target\")\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 5: Write your code here:\n", + "df['Target'].value_counts()\n", + "\n", + "# The 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).copy()\n", + "y = df[\"Target\"].copy()" + ], + "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", + "\n", + "from catboost import CatBoostClassifier\n", + "from sklearn.model_selection import StratifiedKFold\n", + "from sklearn.metrics import f1_score, accuracy_score\n", + "\n", + "avgScore =[]\n", + "avgAcc =[]\n", + "sumAcc = 0\n", + "sumF1 = 0\n", + "model = CatBoostClassifier(n_estimators=100,verbose=0,max_depth=4, random_state=42)\n", + "n_splits = 10\n", + "skf = StratifiedKFold(n_splits=n_splits, shuffle=True, random_state=42)\n", + "y_pred =0\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", + " # Train\n", + " model.fit(X_train,y_train)\n", + "\n", + " # Predict\n", + " y_pred = model.predict(X_test)\n", + " # Calculate evaluation metrics\n", + " f1Score = f1_score(y_test, y_pred)\n", + " accuracy = accuracy_score(y_test, y_pred)\n", + " sumF1 = sumF1+f1Score\n", + " sumAcc = sumAcc + accuracy\n", + " print(f\"F1 Score: {sumF1/n_splits} \\nAccuracy: {sumAcc/n_splits}\")\n", + " # Store results\n", + " avgAcc.append(accuracy)\n", + " avgScore.append(f1Score)\n", + "\n", + "print()\n", + "print(\"Avg Metrices:\")\n", + "print(f\"Avg F1 Score: {sumF1/n_splits} \\nAvg Accuracy: {sumAcc/n_splits}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import matplotlib.pyplot as plt\n", + "feature_importance = pd.DataFrame({\n", + " 'feature': numerical_cols,\n", + " 'importance': model.feature_importances_\n", + "}).sort_values('importance', ascending=False)\n", + "\n", + "feature_importance=feature_importance[feature_importance[\"importance\"] > 2.5]\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", + "print(\"The golden feature is P_2\")\n", + "print(df[\"P_2\"].head())" + ], + "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/243/Q1.ipynb b/submissions_extracted/243/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..0b4c8c1aa5ba5a166242202b6158ac0f7e505a67 --- /dev/null +++ b/submissions_extracted/243/Q1.ipynb @@ -0,0 +1,305 @@ +{ + "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", + "import kagglehub\n", + "import os\n", + "from tqdm import tqdm\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" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "csv_path = os.path.join(path, \"/kaggle/input/q1-exam-data/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.columns.drop('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", + "\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", + "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", + "check_missing_values(df)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "df.duplicated().sum()\n", + "df.drop_duplicates()" + ], + "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", + "for col in categorical_cols:\n", + " le = LabelEncoder()\n", + " df[col] = le.fit_transform(df[col].astype(str))\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: 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", + "X = df[feature_cols]\n", + "y = df['Delivery_Time']\n", + "\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", + "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()}\")\n", + "\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:\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\")\n", + "\n", + "\n", + "#Yes it's imbalanced" + ], + "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", + "X = df[feature_cols]\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.metrics import mean_squared_error, mean_absolute_error\n", + "from sklearn.ensemble import RandomForestRegressor\n", + "\n", + "\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", + "#Random forest\n", + "model = RandomForestRegressor(n_estimators=100, max_depth=15,random_state=42)\n", + "model.fit(X_train_scaled, y_train)\n", + "\n", + "y_pred = model.predict(X_test_scaled)\n", + "\n", + "mae = mean_absolute_error(y_test, y_pred)\n", + "\n", + "f1 = f1_score(y_test, y_pred)\n", + "print(f1)\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()\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/243/Q2.ipynb b/submissions_extracted/243/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..ed0e05fb93d24916ba36f88fd2ca617e857a692a --- /dev/null +++ b/submissions_extracted/243/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": [ + "# 1. Convert Numpy arrays to PyTorch Tensors\n", + "import torch\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" + ], + "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", + "\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", + "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", + "\n", + "\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]\n", + "\n", + " plt.imshow(img)\n", + " plt.title(f\"y_batch: {y_batch[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", + " self.layer1 = nn.Linear(input_dim, hidden_dim)\n", + "\n", + " self.layer2 = nn.Linear(hidden_dim, hidden_dim)\n", + "\n", + "\n", + " self.layer3 = nn.Linear(hidden_dim, hidden_dim)\n", + "\n", + " self.layer4 = nn.Linear(hidden_dim, output_dim)\n", + "\n", + " # activation function for non-linearity\n", + " self.relu = nn.ReLU()\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", + " # 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", + "\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\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)\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 = 2 * 32 * 32 # CIFAR-10 images flattened (RGB)\n", + "\n", + "# TODO: choose number of hidden neurons\n", + "hidden_dim = 32 # 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 = 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: choose number of epochs, increase it if you have gpus :)\n", + "num_epochs = 15\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)\n", + "train_losses = []\n", + "val_losses = []\n", + "val_accuracies = []" + ], + "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", + "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, 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" + ], + "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/243/Q3.ipynb b/submissions_extracted/243/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..928181892ab047b5d0e3093ee6425f080f68e7a0 --- /dev/null +++ b/submissions_extracted/243/Q3.ipynb @@ -0,0 +1,276 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "import numpy as np\n", + "import pandas as pd\n", + "import matplotlib.pyplot as plt\n", + "import os\n", + "import kagglehub\n", + "%pip install kagglehub catboost\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.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", + "\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('/kaggle/input/q3-exam-data/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", + "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", + "missing_values = df.isnull()\n", + "df[missing_values] = df[missing_values].fillna(df[missing_values].mean)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "df.duplicated().sum()\n", + "df.drop_duplicates()" + ], + "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", + "for col in categorical_cols:\n", + " le = LabelEncoder()\n", + " df[col] = le.fit_transform(df[col].astype(str))\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "feature_cols = df.select_dtypes(include=['int64', 'float64']).columns.drop('Target')\n", + "\n", + "X = df[feature_cols]\n", + "y = df['Target']\n", + "\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", + "print(f\"Train: {X_train.shape}, Test: {X_test.shape}\")\n", + "print(f\"Target in train: {y_train.sum()}, in test: {y_test.sum()}\")\n", + "\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 5: Write your code here:\n", + "\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, \"Target\")\n", + "\n", + "\n", + "#Yes it's imbalanced" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "\n", + "X = df[feature_cols]\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.metrics import mean_squared_error, mean_absolute_error\n", + "from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score\n", + "\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", + "#cat boost\n", + "model = CatBoostClassifier(verbose=0,n_estimators=100,max_depth=4)\n", + "\n", + "model.fit(X_train_scaled, y_train)\n", + "\n", + "y_pred = model.predict(X_test_scaled)\n", + "\n", + "mae = mean_absolute_error(y_test, y_pred)\n", + "\n", + "f1 = f1_score(y_test, y_pred)\n", + "print(f1)\n" + ], + "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()\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/244/Q1.ipynb b/submissions_extracted/244/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..95319ed585e73c223e73e2c2d605af3dc2e767a7 --- /dev/null +++ b/submissions_extracted/244/Q1.ipynb @@ -0,0 +1,283 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import pandas as pd\n", + "import matplotlib.pyplot as plt\n", + "import kagglehub\n", + "import os\n", + "from sklearn.preprocessing import StandardScaler\n", + "from sklearn.model_selection import KFold, cross_val_score\n", + "from sklearn.ensemble import RandomForestRegressor\n", + "from sklearn.metrics import mean_absolute_error, make_scorer\n", + "import numpy as np\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": [ + "csv_path = os.path.join(path, \"Q1_data.csv\")\n", + "\n", + "df = pd.read_csv(csv_path)\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "\n", + "print(df.head())\n", + "\n", + "\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "\n", + "print(df.info())\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "print(df.describe())\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "\n", + "\n", + "# Drop missing values from target column\n", + "Delivery_Time = df[\"Delivery_Time\"].dropna()\n", + "\n", + "# Plot target distribution safely\n", + "plt.figure(figsize=(6,4))\n", + "plt.hist(Delivery_Time, bins=30)\n", + "plt.xlabel(\"Delivery Time (minutes)\")\n", + "plt.ylabel(\"Frequency\")\n", + "plt.title(\"Delivery Time Distribution\")\n", + "plt.show()\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "\n", + "# 1. Drop the 'Order_ID' column\n", + "df = df.drop(columns=[\"Order_ID\"])\n", + "\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 2. Handle missing values\n", + "# Check missing values\n", + "df.isnull().sum()\n", + "\n", + "# Fill numerical missing values with median\n", + "num_cols = df.select_dtypes(include=[\"int64\", \"float64\"]).columns\n", + "df[num_cols] = df[num_cols].fillna(df[num_cols].median())\n", + "\n", + "# Fill categorical missing values with mode\n", + "cat_cols = df.select_dtypes(include=[\"object\"]).columns\n", + "for col in cat_cols:\n", + " df[col] = df[col].fillna(df[col].mode()[0])\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "# 3. Check and remove duplicates\n", + "df = df.drop_duplicates()\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "# 4. Encode categorical variables (One-Hot Encoding)\n", + "df = pd.get_dummies(df, drop_first=True)\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "\n", + "\n", + "# 5. Apply feature scaling (StandardScaler)\n", + "X = df.drop(\"Delivery_Time\", axis=1)\n", + "y = df[\"Delivery_Time\"]\n", + "\n", + "scaler = StandardScaler()\n", + "X_scaled = scaler.fit_transform(X)\n", + "\n", + "\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "\n", + "# 6. Check target imbalance (Regression → usually not required)\n", + "# This step is not applicable for regression problems" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "\n", + "\n", + "# 1. Split features and target\n", + "X = X_scaled\n", + "y = y\n", + "\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 2. K-Fold (Regression → NOT Stratified)\n", + "kf = KFold(n_splits=5, shuffle=False)\n", + "\n", + "# 3. Train RandomForest model\n", + "model = RandomForestRegressor(n_estimators=200, random_state=42)\n", + "\n", + "# 4. Evaluate using MAE ONLY\n", + "mae_scorer = make_scorer(mean_absolute_error, greater_is_better=False)\n", + "\n", + "scores = cross_val_score(\n", + " model,\n", + " X,\n", + " y,\n", + " cv=kf,\n", + " scoring=mae_scorer\n", + ")\n", + "\n", + "# 5. Print averaged score\n", + "print(\"Average MAE:\", -scores.mean())" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Train model on full data\n", + "model.fit(X, y)\n", + "\n", + "# 1. Plot feature importance\n", + "importances = model.feature_importances_\n", + "indices = np.argsort(importances)\n", + "\n", + "plt.figure(figsize=(8,6))\n", + "plt.barh(range(len(indices)), importances[indices])\n", + "plt.yticks(range(len(indices)), np.array(df.drop(\"Delivery_Time\", axis=1).columns)[indices])\n", + "plt.xlabel(\"Feature Importance\")\n", + "plt.title(\"Feature Importance from RandomForest\")\n", + "plt.show()\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 2. Plot predicted delivery time histogram\n", + "y_pred = model.predict(X)\n", + "\n", + "plt.figure(figsize=(6,4))\n", + "plt.hist(y_pred, bins=30)\n", + "plt.xlabel(\"Predicted Delivery Time\")\n", + "plt.ylabel(\"Frequency\")\n", + "plt.title(\"Predicted Delivery Time Distribution\")\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/244/Q2.ipynb b/submissions_extracted/244/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..fe70b038dd8e62df4b44c75da84efa71d7962ca3 --- /dev/null +++ b/submissions_extracted/244/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", + "import torch\n", + "from torch.utils.data import TensorDataset, DataLoader\n", + "import matplotlib.pyplot as plt\n", + "import torch.nn as nn\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": [ + "\n", + "\n", + "# 1) Convert numpy arrays to PyTorch tensors\n", + "X_train_t = torch.tensor(X_train, dtype=torch.float32)\n", + "X_test_t = torch.tensor(X_test, dtype=torch.float32)\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 labels are shape (N,), make them (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", + "\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 2) Create TensorDatasets\n", + "train_dataset = TensorDataset(X_train_t, y_train_t)\n", + "test_dataset = TensorDataset(X_test_t, y_test_t)\n", + "\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", + "\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "\n", + "# 4) Inspect one batch\n", + "X_batch, y_batch = next(iter(train_loader))\n", + "print(\"X batch shape:\", X_batch.shape)\n", + "print(\"y batch shape:\", y_batch.shape)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "\n", + "# 5) Display a few images\n", + "# If images are flattened, try to reshape them (adjust H, W, C if needed)\n", + "plt.figure(figsize=(10, 4))\n", + "for i in range(6):\n", + " img = X_batch[i].detach().cpu()\n", + "\n", + " # Handle common formats:\n", + " # (C,H,W) -> (H,W,C)\n", + " if img.ndim == 3 and img.shape[0] in [1, 3]:\n", + " img = img.permute(1, 2, 0)\n", + "\n", + " plt.subplot(1, 6, i+1)\n", + " plt.imshow(img.squeeze(), cmap=\"gray\" if img.ndim == 2 or (img.ndim==3 and img.shape[-1]==1) else None)\n", + " plt.axis(\"off\")\n", + " plt.title(int(y_batch[i].item()))\n", + "plt.tight_layout()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 1) Model class with 4 linear layers\n", + "class AgeRegressor(nn.Module):\n", + " def __init__(self, input_dim):\n", + " super().__init__()\n", + " self.net = nn.Sequential(\n", + " nn.Linear(input_dim, 512),\n", + " nn.ReLU(),\n", + " nn.Linear(512, 256),\n", + " nn.ReLU(),\n", + " nn.Linear(256, 64),\n", + " nn.ReLU(),\n", + " nn.Linear(64, 1)\n", + " )\n", + "\n", + " def forward(self, x):\n", + " # Flatten if input is image-like\n", + " x = x.view(x.size(0), -1)\n", + " return self.net(x)\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 2) Training loop function\n", + "def train_one_epoch(model, loader, criterion, optimizer, device):\n", + " model.train()\n", + " total_loss = 0.0\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 = criterion(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", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 3) Validation loop function\n", + "@torch.no_grad()\n", + "def validate(model, loader, criterion, device):\n", + " model.eval()\n", + " total_loss = 0.0\n", + " for Xb, yb in loader:\n", + " Xb, yb = Xb.to(device), yb.to(device)\n", + " preds = model(Xb)\n", + " loss = criterion(preds, yb)\n", + " total_loss += loss.item() * Xb.size(0)\n", + "\n", + " return total_loss / len(loader.dataset)\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 4) Define device, model, loss, optimizer\n", + "device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n", + "\n", + "# infer input_dim from one batch\n", + "X_batch, _ = next(iter(train_loader))\n", + "input_dim = X_batch.view(X_batch.size(0), -1).shape[1]\n", + "\n", + "model = AgeRegressor(input_dim).to(device)\n", + "criterion = nn.MSELoss()\n", + "optimizer = torch.optim.Adam(model.parameters(), lr=1e-3)\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 5) Train for 20 epochs and track losses\n", + "train_losses, val_losses = [], []\n", + "\n", + "for epoch in range(1, 21):\n", + " tr_loss = train_one_epoch(model, train_loader, criterion, optimizer, device)\n", + " va_loss = validate(model, test_loader, criterion, device)\n", + "\n", + " train_losses.append(tr_loss)\n", + " val_losses.append(va_loss)\n", + "\n", + " print(f\"Epoch {epoch:02d} | Train Loss: {tr_loss:.4f} | Val Loss: {va_loss:.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 (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/244/Q3.ipynb b/submissions_extracted/244/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..50c5fb76ba778a350462378314018f53e4efd425 --- /dev/null +++ b/submissions_extracted/244/Q3.ipynb @@ -0,0 +1,230 @@ +{ + "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()\n", + "import kagglehub\n", + "import pandas as pd\n", + "from sklearn.preprocessing import StandardScaler\n", + "from sklearn.model_selection import StratifiedKFold, cross_val_score\n", + "from sklearn.metrics import f1_score, make_scorer\n", + "import numpy as np\n", + "from catboost import CatBoostClassifier\n", + "import matplotlib.pyplot as plt\n", + "# Download latest version\n", + "\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": [ + "# 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", + "\n", + "\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "print(df.head())" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "print(df.info())" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "print(df.describe())" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "\n", + "# 1. Handle missing values\n", + "# Fill numerical columns with median\n", + "num_cols = df.select_dtypes(include=[\"int64\", \"float64\"]).columns\n", + "df[num_cols] = df[num_cols].fillna(df[num_cols].median())\n", + "\n", + "# Fill categorical columns with mode\n", + "cat_cols = df.select_dtypes(include=[\"object\"]).columns\n", + "for col in cat_cols:\n", + " df[col] = df[col].fillna(df[col].mode()[0])\n", + "\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 2. Check and remove duplicates\n", + "df = df.drop_duplicates()\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "\n", + "# 3. Encode categorical variables (if any)\n", + "df = pd.get_dummies(df, drop_first=True)\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 4. Apply feature scaling to numerical features\n", + "X = df.drop(\"Target\", axis=1)\n", + "y = df[\"Target\"]\n", + "\n", + "scaler = StandardScaler()\n", + "X_scaled = scaler.fit_transform(X)\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 5. Check target imbalance\n", + "y.value_counts(normalize=True)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "\n", + "\n", + "# 1) Split into features (X) and target (y)\n", + "X = X_scaled\n", + "y = y\n", + "\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 2) Correct split for classification\n", + "cv = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)\n", + "\n", + "# 4) Choose appropriate metric ONLY (Accuracy vs F1)\n", + "class_dist = y.value_counts(normalize=True)\n", + "imbalanced = class_dist.min() < 0.40 # simple rule of thumb\n", + "\n", + "if imbalanced:\n", + " scoring = make_scorer(f1_score) # binary F1\n", + "else:\n", + " scoring = \"accuracy\"\n", + "\n", + "# 3) Train CatBoostClassifier\n", + "model = CatBoostClassifier(\n", + " iterations=500,\n", + " depth=6,\n", + " learning_rate=0.1,\n", + " loss_function=\"Logloss\",\n", + " verbose=0,\n", + " random_seed=42\n", + ")\n", + "\n", + "# 5) Print averaged score across folds\n", + "scores = cross_val_score(model, X, y, cv=cv, scoring=scoring)\n", + "print((\"Average F1:\" if imbalanced else \"Average Accuracy:\"), scores.mean())" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Train model on full data\n", + "# Get feature importance\n", + "# Sort features by importance\n", + "# 1) Plot feature importance\n", + "\n", + "# 2) Print the most important (golden) feature\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 2) Print the most important (golden) feature\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/245/Q1.ipynb b/submissions_extracted/245/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..405fdf677b7609bf89f7e8a559d1cc45ce5da16f --- /dev/null +++ b/submissions_extracted/245/Q1.ipynb @@ -0,0 +1,378 @@ +{ + "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": [ + "# Load data\n", + "Q_data = os.path.join(path, \"Q1_data.csv\")\n", + "df = pd.read_csv(Q_data)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Print first 5 rows\n", + "print(df.head(5))" + ], + "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.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", + "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", + "df['Weather'] = df_clean['Weather'].fillna(\"none\")\n", + "df['Traffic_Level'] = df_clean['Traffic_Level'].fillna(\"none\")\n", + "df['Time_of_Day'] = df_clean['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", + "check_missing_values(df)\n", + "df.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)" + ], + "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_clean.select_dtypes(include=[\"int64\", \"float64\",\"object\"]).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": [ + "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\")\n", + "\n", + "\n", + "#Yes the data is imblanaced" + ], + "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": [], + "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": [ + "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_absolute_error(y, y_hat)\n", + " losses.append(loss)\n", + "\n", + " return theta, losses" + ], + "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)\n", + "\n", + "\n", + "scaler = StandardScaler()\n", + "X_train_scaled = scaler.fit_transform(X_train)\n", + "X_test_scaled = scaler.transform(X_test)\n", + "\n", + "\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_scaled, y_train)\n", + "print(\"Model trained!\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "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/245/Q2.ipynb b/submissions_extracted/245/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..59eb4726228c5b69f80c802851a34366568efffe --- /dev/null +++ b/submissions_extracted/245/Q2.ipynb @@ -0,0 +1,370 @@ +{ + "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", + "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", + "X_train_tensor = torch.tensor(X_train, dtype=torch.float32)\n", + "y_train_tensor = torch.tensor(y_train, dtype=torch.long)\n", + "\n", + "X_test_tensor = torch.tensor(X_test, dtype=torch.float32)\n", + "y_test_tensor = torch.tensor(y_test, dtype=torch.long)" + ], + "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=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", + "images, labels = next(iter(train_loader))" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 5. Display sample images\n", + "plt.figure(figsize=(8, 4))\n", + "\n", + "for i in range(32):\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", + "\n", + " # third linear layer: hidden layer -> hidden layer\n", + " self.layer3 = nn.Linear(hidden_dim, hidden_dim)\n", + " # Fourth linear layer: hidden layer -> output layer\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.layer3(a2)\n", + " a3 = self.relu(z3)\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": [ + "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 = 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": [ + "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": [ + "# 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/245/Q3.ipynb b/submissions_extracted/245/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..714bb4d0ea7146d22d7194020dc5391eb649527f --- /dev/null +++ b/submissions_extracted/245/Q3.ipynb @@ -0,0 +1,378 @@ +{ + "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 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": [ + "Q3_data = os.path.join(path, \"Q3_data.csv\")\n", + "df = pd.read_csv(Q3_data)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "print(df.head(5))" + ], + "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", + "check_missing_values(df)\n", + "cols = df.select_dtypes(include=[\"float64\",\"int64\"]).columns\n", + "\n", + "print(\"Columns:\", list(cols))\n", + "from sklearn.preprocessing import LabelEncoder\n", + "\n", + "label_encoders = {}\n", + "for col in cols:\n", + " le = LabelEncoder()\n", + " df[col] = le.fit_transform(df[col])\n", + " label_encoders[col] = le\n", + "\n", + "df\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": [ + "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=[\"float64\"]) # 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": [ + "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')\n", + "\n", + "\n", + "#yes the data is imblanaced" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# sigmoid in NumPy\n", + "def sigmoid(z):\n", + " return 1 / (1 + np.exp(-z))" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 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)\n", + "\n", + " loss = -1/len(y) * np.sum(y * np.log(y_hat) + (1 - y) * np.log(1 - y_hat))\n", + " return loss" + ], + "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 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" + ], + "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 StratifiedKFold\n", + "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=5 Folds\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": [ + " # Storage for logistic regression results for each fold\n", + "lr_losses = []\n", + "lr_accuracy = []\n", + "lr_precision = []\n", + "lr_recall = []\n", + "lr_f1 = []" + ], + "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]\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": [ + "print(\" Performance:\")\n", + "print(f\" Accuracy: {np.mean(lr_accuracy):.4f}\")\n", + "print(f\" F1-Score: {np.mean(lr_f1):.4f}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "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/246/Q1.ipynb b/submissions_extracted/246/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..29b5c6ab1fc613d23a8664c70f1cfe2ef9bc4be5 --- /dev/null +++ b/submissions_extracted/246/Q1.ipynb @@ -0,0 +1,290 @@ +{ + "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\n", + "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": [ + "\n", + "# 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", + "\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[\"Delivery_Time\"].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, \"Sales\")" + ], + "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", + "for col in ['Weather', 'Traffic_Level', 'Time_of_Day']:\n", + " df[col] = df[col].fillna('unknown')\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", + "\n", + "print(\"Missing values remaining:\", df.isnull().sum().sum())\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" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "from sklearn.preprocessing import LabelEncoder\n", + "categories=['Weather', 'Traffic_Level', 'Time_of_Day']\n", + "for col in categories:\n", + " le = LabelEncoder()\n", + " df[col] = le.fit_transform(df[col].astype(str))\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", + "categorical_cols = df.select_dtypes(include=[\"number\"]).columns\n", + "\n", + "print('data before scaling:\\n', categorical_cols) #show before scaling\n", + "standard_scaler = StandardScaler() # Instantiate StandardScaler\n", + "data_standard_scaled = standard_scaler.fit_transform(df[categorical_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", + "def check_target_imbalance(df, target_column):\n", + " print(\"Target Distribution:\")\n", + " df[target_column].hist() # Yeah you can just do this :)\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)\n", + "y= df[\"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 StratifiedKFold\n", + "from sklearn.ensemble import RandomForestRegressor\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", + " 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 Random Forest Regressor\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", + "\n", + "criterion = nn.MSELoss()\n", + "loss = criterion(y_pred, y_true)\n", + "avg_loss = running_loss / len(train_loader)\n", + "\n", + "\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": [ + "# Task 2: Write your code here:\n", + "def check_target_distribution(df, target_column):\n", + " df[\"Delivery_Time\"].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/246/Q2.ipynb b/submissions_extracted/246/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..30f1c9a97aa67cec5a6246e76aa7f9182cc0b03b --- /dev/null +++ b/submissions_extracted/246/Q2.ipynb @@ -0,0 +1,396 @@ +{ + "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", + "import torch\n", + "from torchvision.transforms.functional import to_tensor\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", + "\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 2. Create TensorDataset objects\n", + "# Create TensorDatasets for training and testing\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", + "\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", + "# 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", + "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.view(-1,3*36*36), 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", + "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", + "\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.layer3(a2)\n", + " a3 = self.relu(z3)\n", + "\n", + " # Output layer (raw scores / logits)\n", + " output = self.layer4(a2) # 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", + "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", + " # 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", + "\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 # MNIST images flattened\n", + "hidden_dim = 512 # 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", + "# 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)\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", + "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:\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", + "# 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": [] + } + ], + "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/246/Q3.ipynb b/submissions_extracted/246/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..de36dc6bbc35a90b29445d90d3723eb03ab63b1a --- /dev/null +++ b/submissions_extracted/246/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", + "import matplotlib.pyplot as plt\n", + "import seaborn as sns\n", + "import os\n", + "from tqdm import tqdm\n", + "\n", + "%matplotlib inline\n", + "from IPython.display import clear_output\n", + "\n", + "%pip install kagglehub catboost lightgbm tqdm -q\n", + "\n", + "clear_output()\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" + ], + "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", + "missing_values = df.isnull().sum()\n", + "print(\"Missing Values per Column:\")\n", + "print(missing_values[missing_values > 0])\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('unknown')\n", + "\n", + "categorical_cols = df.select_dtypes(include=[\"number\"]).columns.drop('Target')\n", + "for col in categorical_cols:\n", + " print(f\"Encoding column: {col}\")\n", + " df[col] = df[col].fillna(df[col].mode()[0])\n", + "\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)\n", + "\n", + "\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "from sklearn.preprocessing import LabelEncoder\n", + "categories=df.select_dtypes(include=[\"object\"]).columns\n", + "for col in categories:\n", + " le = LabelEncoder()\n", + " df[col] = le.fit_transform(df[col].astype(str))" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "from sklearn.preprocessing import StandardScaler #import StandardScaler\n", + "categorical_cols = df.select_dtypes(include=[\"number\"]).columns\n", + "\n", + "print('data before scaling:\\n', categorical_cols) #show before scaling\n", + "standard_scaler = StandardScaler() # Instantiate StandardScaler\n", + "data_standard_scaled = standard_scaler.fit_transform(df[categorical_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 5: Write your code here:\n", + "def check_target_imbalance(df, target_column):\n", + " print(\"Target Distribution:\")\n", + " df[target_column].hist() # Yeah you can just do this :)\n", + " plt.show()\n", + " check_target_imbalance(df, \"golden\")" + ], + "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", + "\n", + "\n", + "\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_\n", + "score\n", + "from catboost import CatBoostClassifier\n", + "from sklearn.model_selection import StratifiedKFold\n", + "from sklearn.ensemble import RandomForestRegressor\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", + " 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 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!\")\n", + "\n", + "\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)" + ], + "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: Write your code here:\n", + "print(df[\"Target\"])" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:\n", + "from sklearn.model_selection import train_test_split, KFold\n", + "X, y = X_reg.copy(), y_reg.copy()\n", + "# Define K-Fold Cross Validation\n", + "kf = KFold(n_splits=5, shuffle=True, random_state=42)\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", + "#optional\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)" + ], + "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/247/Q1.ipynb b/submissions_extracted/247/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..a2031eaef24ab81741e2dc52490c9b7bc4643eaa --- /dev/null +++ b/submissions_extracted/247/Q1.ipynb @@ -0,0 +1,378 @@ +{ + "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", + "\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": [ + "# 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\") #Left skewed." + ], + "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", + "print(\"Missing Values:\")\n", + "Missing_values= df.isnull().sum()\n", + "\n", + "print(Missing_values)\n", + "if Missing_values.any():\n", + " print(\"There's missing values\")\n", + "else:\n", + " print(\"No missing values\")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "#Drop Missing Values\n", + "df= df.dropna()\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "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", + "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": [ + "#Enocde categorical columns\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: Write your code here: Feature Scaling\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", + "print(\"Target Distribution:\")\n", + "print(\"Delivery time: \", df['Delivery_Time'].sum())\n", + "print(f\"Normal: {(df['Delivery_Time'] == 0).sum()}\")\n", + "sns.countplot(x=df['Delivery_Time'])\n", + "plt.title(\"Target Distribution\")\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "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" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "from sklearn.model_selection import train_test_split\n", + "\n", + "# Task 1: Write your code here:\n", + "X = df.drop(\"Delivery_Time\", axis=1).astype(float) # X = Features\n", + "y = df['Delivery_Time'].astype(float) # y = Delivery time\n", + "\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", + "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 2,3,4,5: Write your code here:\n", + "\n", + "# K-Fold\n", + "from sklearn.model_selection import KFold\n", + "\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)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "#Task 4 Random Forest Model\n", + "from sklearn.ensemble import RandomForestRegressor\n", + "\n", + "model = RandomForestRegressor(random_state=42) # instantiate\n", + "model.fit(X_train, y_train) # fit\n", + "y_pred = model.predict(X_test)\n", + "\n", + "print(\"Model Trained\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5 Evaluate MAE\n", + "from sklearn.metrics import mean_absolute_error\n", + "mae = mean_absolute_error(y_test, y_pred)\n", + "print(\"MAE :\", mae)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "y.hist(figsize=(15,8))" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "sns.histplot(y,kde=True,color='blue',bins=30)\n", + "\n", + "plt.title(\"speed Distribution\")\n", + "plt.xlabel(\"Delivery Time\", fontsize=12)\n", + "plt.ylabel(\"Count\",fontsize=12)\n", + "plt.show()\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/247/Q2.ipynb b/submissions_extracted/247/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..1221b78f679671c4dee5b80c250b0fc3a9874c95 --- /dev/null +++ b/submissions_extracted/247/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": [ + "# 1. Convert Numpy arrays to PyTorch Tensors\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", + "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", + "sample_image, sample_label = train_dataset[0]\n", + "print(f\"\\n Image shape: {sample_image.shape}\")\n", + "print(f\"Label: {sample_label}\")" + ], + "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" + ], + "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", + "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", + "import torch.nn as nn\n", + "import torch.nn.functional as F\n", + "class NN4Layer(nn.Module):\n", + "\n", + " def __init__(self, input_dim, hidden_dim, output_dim):\n", + " super(NN4Layer, self).__init__()\n", + "\n", + "\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", + " 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(z1)\n", + "\n", + " # Layer 3 TODO\n", + " z3 = self.layer3(a2)\n", + " a3 = self.relu(z2)\n", + "\n", + "\n", + " # Output layer TODO\n", + " z4 = self.layer5(a3)\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)\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.to(device)\n", + " y_batch = y_batch.to(device)\n", + "\n", + " # Forward pass\n", + " # TODO: make predictions\n", + " outputs = model(X_batch) # \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 = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n", + "\n", + "# Model parameters\n", + "input_dim = 36*36 # Number of tabular features\n", + "hidden_dim = 14 # Design choice\n", + "output_dim = 4\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" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Start training for 20 epochs:\n", + "from torch.optim import AdamW, Adam\n", + "num_epochs = 20\n", + "learning_rate = 0.001\n", + "criterion = nn.CrossEntropyLoss()\n", + "optimizer = AdamW(model.parameters(), learning_rate)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Run Training\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", + " 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", + "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/247/Q3.ipynb b/submissions_extracted/247/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..370b0746e6cc788b60508330c2289b79ca0cf6d1 --- /dev/null +++ b/submissions_extracted/247/Q3.ipynb @@ -0,0 +1,366 @@ +{ + "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", + "\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": [ + "# 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", + "print(\"Missing Values:\")\n", + "Missing_values= df.isnull().sum()\n", + "\n", + "print(Missing_values)\n", + "if Missing_values.any():\n", + " print(\"There's missing values\")\n", + "else:\n", + " print(\"No missing values\")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "#Drop Missing Values\n", + "df= df.dropna()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "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", + "categorical_cols = df.select_dtypes(include=[\"object\"]).columns\n", + "\n", + "print(\"Categorical Columns:\", list(categorical_cols)) #No need to encode. there's no categorical columns" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "from sklearn.preprocessing import StandardScaler, MinMaxScaler\n", + "numerical_cols = df.select_dtypes(include=[\"int64\", \"float64\"]).columns.drop(\"Target\")\n", + "numerical_cols.astype('string')\n", + "standard_scaler = StandardScaler() # Instantiate StandardScaler\n", + "data_standard_scaled = standard_scaler.fit_transform(df.drop(\"Target\", axis =1)) # Apply fit_transform\n", + "\n", + "print('\\nData after scaling:\\n', data_standard_scaled)" + ], + "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)) #Normalize=true will give the precentage\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": [ + "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" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Use previously generated random data (example: classification data)\n", + "from sklearn.model_selection import train_test_split\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, # 20% for test, remaining 80% for train\n", + " random_state=42, # reproducible output, shuffle the data\n", + " shuffle=True, # representative splits\n", + " stratify=y # preserve class distribution\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)" + ], + "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", + "# 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" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "!pip install dask[dataframe] catboost\n", + "from catboost import CatBoostClassifier\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "from sklearn.metrics import accuracy_score, classification_report\n", + "cb = CatBoostClassifier(verbose=0)\n", + "cb.fit(X_train, y_train)\n", + "cb_pred = cb.predict(X_test)\n", + "print(\"CatBoost Accuracy\", accuracy_score(y_test, cb_pred))" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "y_pred = cb.predict(X_test)\n", + "\n", + "print(f\"Accuracy: {accuracy_score(y_test, y_pred):.4f}\")\n", + "print(classification_report(y_test, y_pred, target_names=['Normal', 'Legendary']))" + ], + "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/248/Q1.ipynb b/submissions_extracted/248/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..b1866769749804ad244417b56200bad11565e1ca --- /dev/null +++ b/submissions_extracted/248/Q1.ipynb @@ -0,0 +1,488 @@ +{ + "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": [ + "\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", + "# Load the dataset\n", + "r_path = os.path.join(path, 'Q1_data.csv')\n", + "df_r = pd.read_csv(r_path)\n", + "\n", + "print(f\"Dataset shape: {df_r.shape}\")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "df_r.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "df_r.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "missing_percentage = (df_r.isnull().sum() / len(df_r)) * 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 4: Write your code here:\n", + "df_r.describe()\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:plt.figure(figsize=(10, 5))\n", + "plt.hist(df_r['Delivery_Time'].dropna(), bins=50, edgecolor='black')\n", + "plt.title('Delivery_Time')\n", + "plt.xlabel('Delivery_Time')\n", + "plt.ylabel('Traffic_Level')\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "cols = ['Order_ID', 'Delivery_Time', 'Traffic_Level', 'Weather', 'Time_of_Day', 'Distance_km', 'Preparation_Time_min']\n", + "df_clean = df_r[cols].copy()\n", + "\n", + "\n", + "print(f\"Before: {df_clean.shape}\")\n", + "df_clean = df_clean.dropna(subset=['Order_ID'])\n", + "print(f\"After dropping missing Delivery_Time/Weather/Traffic_Level/Time_of_Day/Courier_Experience_yrs: {df_clean.shape}\")\n", + "\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "#df_clean[col] = df_clean[col].fillna('unknown')\n", + "\n", + "\n", + "df_clean['Order_ID'] = df_clean['Order_ID'].fillna(df_clean['Order_ID'].mode()[0])\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_r.duplicated().sum()\n", + " print(f\"Number of Duplicate Samples: {duplicates}\")\n", + " if duplicates > 0:\n", + " print(\"Dropping Duplicates...\")\n", + " df_r.drop_duplicates(inplace=True)\n", + " print(\"Duplicates Dropped.\")\n", + " else:\n", + " print(\"No Duplicate Samples Found.\")\n", + "\n", + "check_duplicates(df_r)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "categorical_cols = ['Order_ID', 'Distance_km', 'Traffic_Level', 'Delivery_Time']\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({\"Feature_1\": [471, 710, 714,625],\"Feature_2\": [50, 92, 66,44]})\n", + "\n", + "print(\"Before scaling:\")\n", + "data_for_scale\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 6: Write your code here:\n", + "\n", + "def mean_squared_error(y, y_hat):\n", + " return (1 / (2 * len(y))) * np.sum((y_hat - y) ** 2)\n", + "" + ], + "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": [ + "# Task 1: Write your code here:\n", + "feature_cols = ['Order_ID', 'Delivery_Time', 'Traffic_Level', 'Weather', 'Time_of_Day', 'Distance_km', 'Preparation_Time_min']\n", + "X = df_clean[feature_cols]\n", + "y = df_clean['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" + ], + "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", + "\n", + "\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", + "y_pred = model.predict(X_test_scaled)\n", + "\n", + "mae = mean_absolute_error(y_test, y_pred)\n", + "model.fit(X_train, y_train)\n", + "print(f\"MAE: ${mae:,.2f}\")\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", + "\n", + "\n", + "\n" + ], + "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_scaled, y_train)\n", + "print(\"Model trained!\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "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": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "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)" + ], + "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", + "print(\"\\nDataset Shapes\")\n", + "print(\"X:\", X.shape)\n", + "print(\"y:\", y.shape)\n", + "\n", + "# Encode Categorical Features\n", + "label_encoder = LabelEncoder()\n", + "\n", + "for col in X.select_dtypes(include=[\"object\"]).columns:\n", + " X[col] = label_encoder.fit_transform(X[col])\n", + "\n", + "# Feature Scaling\n", + "scaler = StandardScaler()\n", + "X_scaled = scaler.fit_transform(X)\n", + "\n", + "\n", + "# K-Fold Cross Validation\n", + "kf = KFold(n_splits=5, shuffle=True, random_state=42)\n", + "\n", + "mse_scores = []\n", + "mae_scores = []\n", + "\n", + "for train_idx, test_idx in kf.split(X_scaled):\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", + " # Train model\n", + "\n", + " # Predict\n", + "\n", + "\n", + "\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()\n", + "\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": [ + "# Price distribution (target variable)\n", + "plt.figure(figsize=(10, 5))\n", + "plt.hist(df_r['Delivery_Time'].dropna(), bins=50, edgecolor='black')\n", + "plt.title('Delivery_Time')\n", + "plt.xlabel('Delivery_Time')\n", + "plt.ylabel('Distance_km')\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/248/Q2.ipynb b/submissions_extracted/248/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..78c8cd4a232a0d83a42c9c48578041458125ea0c --- /dev/null +++ b/submissions_extracted/248/Q2.ipynb @@ -0,0 +1,225 @@ +{ + "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": [], + "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", + "\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": [ + "# 1. Convert Numpy arrays to PyTorch Tensors\n", + "\n", + "data=train_test_split()\n", + "x=data.data\n", + "y=data.target\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" + ], + "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/248/Q3.ipynb b/submissions_extracted/248/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..25b4d3886a094c8ded72b52d700204d340ed0fdd --- /dev/null +++ b/submissions_extracted/248/Q3.ipynb @@ -0,0 +1,264 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [], + "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": [ + "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", + "\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", + "d_path = os.path.join(path, \"Q3_data.csv\")\n", + "\n", + "df_d = pd.read_csv(d_path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "df_d.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "df_d.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "df_d.describe()\n" + ], + "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_d):\n", + " duplicates = df_d.duplicated().sum()\n", + " print(f\"Number of Duplicate Samples: {duplicates}\")\n", + " if duplicates > 0:\n", + " print(\"Dropping Duplicates...\")\n", + " df_d.drop_duplicates(inplace=True)\n", + " print(\"Duplicates Dropped.\")\n", + " else:\n", + " print(\"No Duplicate Samples Found.\")\n", + "\n", + "check_duplicates(df_d)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "# Encode categorical columns - converts text to integers\n", + "categorical_cols = ['P_2', 'B_2', 'S_3', 'D_41', 'B_3', 'D_141']\n", + "for col in categorical_cols:\n", + " le = LabelEncoder()\n", + " df_d_clean[col] = le.fit_transform(df_clean[col].astype(str))\n", + "\n", + "df_d_clean.head()\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "data_for_scale = pd.DataFrame({\"Feature_1\": [11, 40, 19,12],\"Feature_2\": [2384, 439, 3282,576]})\n", + "\n", + "print(\"Before scaling:\")\n", + "data_for_scale\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", + "feature_cols = ['P_2','D_39', 'B_1']\n", + "X = df_clean[feature_cols]\n", + "#y = df_clean['card']\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" + ], + "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/249/Q1.ipynb b/submissions_extracted/249/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..1d793e94e2a4160e7b4ba3b2f5d8ac4406f4b9b3 --- /dev/null +++ b/submissions_extracted/249/Q1.ipynb @@ -0,0 +1,303 @@ +{ + "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", + "Delivery_path = os.path.join(path, 'Q1_data.csv')\n", + "df_cars = pd.read_csv(Delivery_path)\n", + "\n", + "print(f\"Dataset shape: {df_cars.shape}\")\n", + "\n", + "#naming is off becuse of copy pasting to save time" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "df_cars.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "df_cars.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "df_cars.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "print(f\"delivery_time: {df_cars['Delivery_Time'].sum()}\")\n", + "print(f\"Normal: {(df_cars['Delivery_Time'] == 0).sum()}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "stat_cols = ['Order_ID', 'Distance_km', 'Preparation_Time_min', 'Courier_Experience_yrs', 'Delivery_Time']\n", + "df_clean = df_cars.dropna(subset=['Order_ID']).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:\n", + "for col in ['Order_ID', 'Distance_km', 'Preparation_Time_min', 'Courier_Experience_yrs', 'Delivery_Time', 'Weather', 'Traffic_Level', 'Time_of_Day', 'Vehicle_Type']:\n", + " df_clean[col] = df_clean[col].fillna('unknown')\n", + "#df_clean['Order_ID', 'Distance_km', 'Preparation_Time_min', 'Courier_Experience_yrs', 'Delivery_Time'] = df_clean['Order_ID', 'Distance_km', 'Preparation_Time_min', 'Courier_Experience_yrs', 'Delivery_Time'].fillna('none')\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:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "categorical_cols = ['Order_ID', 'Distance_km', 'Preparation_Time_min', 'Courier_Experience_yrs', 'Delivery_Time', '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", + "# Define features (X) and target (y)\n", + "feature_cols = ['Order_ID', 'Distance_km', 'Preparation_Time_min', 'Courier_Experience_yrs', 'Delivery_Time', 'Weather', 'Traffic_Level', 'Time_of_Day', 'Vehicle_Type']\n", + "X = df_clean[feature_cols]\n", + "y = df_clean[ '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": [ + "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", + "# Define features (X) and target (y)\n", + "feature_cols = ['Order_ID', 'Distance_km', 'Preparation_Time_min', 'Courier_Experience_yrs', 'Delivery_Time', 'Weather', 'Traffic_Level', 'Time_of_Day', 'Vehicle_Type']\n", + "X = df_clean[feature_cols]\n", + "y = df_clean[ '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", + "\n", + "model = RandomForestRegressor(n_estimators=200)\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", + "print(f\"MAE: ${mae:,.2f}\")\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}\")\n", + "print(f\"RMSE: ${rmse_scores.mean():,.2f}\")" + ], + "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" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "plt.figure(figsize=(9, 2))\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 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/249/Q2.ipynb b/submissions_extracted/249/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..503b77343a8bb7ec508891387ce535df4bdf7853 --- /dev/null +++ b/submissions_extracted/249/Q2.ipynb @@ -0,0 +1,196 @@ +{ + "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", + "\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 = torch.tensor([1600, 3, 36, 36])\n", + "y = torch.randn([400, 3, 36, 36])\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/249/Q3.ipynb b/submissions_extracted/249/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..e20568087539545cf5a0d820e7414bff332576b3 --- /dev/null +++ b/submissions_extracted/249/Q3.ipynb @@ -0,0 +1,383 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "\n", + "#naming is off becuse of copy pasting to save timeimport 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", + "\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", + "Delivery_path = os.path.join(path, 'Q3_data.csv')\n", + "df_cars = pd.read_csv(Delivery_path)\n", + "\n", + "print(f\"Dataset shape: {df_cars.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "df_cars.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "df_cars.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "df_cars.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "stat_cols = ['P_2', 'D_39', 'B_1', 'B_2', 'R_1']\n", + "df_clean = df_cars.dropna().copy()\n", + "for col in stat_cols:\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 2: Write your code here:\n", + "def check_duplicates(df_clean):\n", + "\n", + " #TODO: get duplicated data using pandas\n", + " duplicates = df_clean.duplicated().sum()\n", + "\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 3: Write your code here:\n", + "categorical_cols = ['P_2', 'D_39', 'B_1', 'B_2', 'R_1']\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:\n", + "from sklearn.preprocessing import MinMaxScaler\n", + "\n", + "# Pick only the numerical columns, NOT the target\n", + "numerical_cols = df_clean.select_dtypes(include=[\"number\"]).columns.drop()\n", + "\n", + "scaler = MinMaxScaler()\n", + "\n", + "# scale the `numerical_cols`\n", + "df_clean[numerical_cols] = scaler.fit_transform(df_clean[numerical_cols])\n", + "\n", + "df_clean.head()\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "def check_target_imbalance(df_clean):\n", + " print(\"Target Distribution:\")\n", + "\n", + " df_clean[categorical_cols].hist() # Yeah you can just do this :)\n", + " plt.show()\n", + "\n", + "check_target_imbalance(df_clean)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "feature_cols = ['P_2', 'D_39', 'B_1', 'B_2', 'R_1']\n", + "X = df_clean[feature_cols]\n", + "y = df_clean[ 'P_2']\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", + "from sklearn.model_selection import StratifiedKFold\n", + "from sklearn.metrics import accuracy_score, f1_score\n", + "\n", + "n_splits = 5\n", + "skf = StratifiedKFold(n_splits=n_splits, shuffle=True, random_state=42)\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": [ + "pip install catboost" + ], + "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": [ + "# TODO: Define models with hyperparameters of your choice\n", + "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": [ + "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", + " 'F1-Score': f1\n", + " }\n", + "\n", + " # Print metrics\n", + " print(f\" Accuracy: {accuracy:.4f}\")\n", + "\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": [] + }, + { + "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/25/Q1.ipynb b/submissions_extracted/25/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..37ecc1acf2762c290b2b30c34661b509969f67f8 --- /dev/null +++ b/submissions_extracted/25/Q1.ipynb @@ -0,0 +1,191 @@ +{ + "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_csv(Q1_data)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "Plot" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "Drop (ORDER_ID)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "handle missing vlues" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "chick and remove dublicate" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "encode categroical" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "apply feature scalling" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 6: Write your code here:\n", + "chick for in target" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "split dataset" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:\n", + "Kfold" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "plot feature" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "plot predected" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:\n", + "train model\n", + "avergae\n", + "clculate 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/25/Q2.ipynb b/submissions_extracted/25/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..abe5cac03a733c197d46b84bd0878c677444ec6b --- /dev/null +++ b/submissions_extracted/25/Q2.ipynb @@ -0,0 +1,199 @@ +{ + "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", + "convert" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 2. Create TensorDataset objects\n", + "create\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 3. Create DataLoaders\n", + "correlate\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 4. Print shape of one batch\n", + "print\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 5. Display sample images\n", + "\n", + "display" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your model class here:\n", + "model" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your training loop here:\n", + "loop" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your validation loop here:\n", + "validation" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Define device, model, loss, optimizer:\n", + "define" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Start training for 20 epochs:\n", + "start training" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "plot training" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2 (Bonus): Write your code here:\n", + "plot preduction" + ], + "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/25/Q3.ipynb b/submissions_extracted/25/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..bfa33b5cb9785e63434b70e5416301c339eec0e6 --- /dev/null +++ b/submissions_extracted/25/Q3.ipynb @@ -0,0 +1,176 @@ +{ + "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", + "read dataset" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "aspect row" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "display" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "show stastical" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "handle" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "check" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "encode" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "apply" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "check" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "split" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:\n", + "use train evaluate print" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "plot" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "identify" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:\n", + "create\n", + "run\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/250/Q1.ipynb b/submissions_extracted/250/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..36af53a01daa1b4d8784d672643006039e62d02f --- /dev/null +++ b/submissions_extracted/250/Q1.ipynb @@ -0,0 +1,313 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "\n", + "# --- Basic Libraries ---\n", + "import numpy as np\n", + "import pandas as pd\n", + "import matplotlib.pyplot as plt\n", + "import os\n", + "import warnings\n", + "warnings.filterwarnings('ignore')\n", + "\n", + "# --- For downloading datasets ---\n", + "import kagglehub\n", + "\n", + "# --- Scikit-Learn: Data Splitting ---\n", + "from sklearn.model_selection import train_test_split, StratifiedKFold, cross_val_score\n", + "\n", + "# --- Scikit-Learn: Preprocessing ---\n", + "from sklearn.preprocessing import StandardScaler, MinMaxScaler, LabelEncoder, OneHotEncoder\n", + "from sklearn.impute import SimpleImputer\n", + "\n", + "# --- Scikit-Learn: Regression Models ---\n", + "from sklearn.linear_model import LinearRegression, Ridge, Lasso\n", + "from sklearn.ensemble import RandomForestRegressor, GradientBoostingRegressor\n", + "from sklearn.tree import DecisionTreeRegressor\n", + "from sklearn.svm import SVR\n", + "\n", + "# --- Scikit-Learn: Classification Models ---\n", + "from sklearn.linear_model import LogisticRegression\n", + "from sklearn.ensemble import RandomForestClassifier, GradientBoostingClassifier\n", + "from sklearn.tree import DecisionTreeClassifier\n", + "from sklearn.svm import SVC\n", + "from sklearn.neighbors import KNeighborsClassifier\n", + "\n", + "# --- Scikit-Learn: Metrics ---\n", + "from sklearn.metrics import (\n", + " # Regression metrics\n", + " mean_squared_error, mean_absolute_error, r2_score,\n", + " # Classification metrics\n", + " accuracy_score, precision_score, recall_score, f1_score,\n", + " classification_report, confusion_matrix, roc_auc_score, roc_curve\n", + ")\n", + "\n", + "# --- Scikit-Learn: Unsupervised Learning ---\n", + "from sklearn.decomposition import PCA\n", + "from sklearn.manifold import TSNE\n", + "from sklearn.cluster import KMeans\n", + "\n", + "# --- PyTorch ---\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 images) ---\n", + "from torchvision.datasets import MNIST, CIFAR10\n", + "from torchvision.transforms.functional import to_tensor\n", + "from torchvision.transforms import ToTensor, Compose, Normalize\n", + "\n", + "# --- Check PyTorch/CUDA ---\n", + "print(f\"PyTorch version: {torch.__version__}\")\n", + "print(f\"CUDA available: {torch.cuda.is_available()}\")\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": [ + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q1-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)\n", + "\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "\n", + "# Then load the CSV\n", + "df = pd.read_csv(os.path.join(path, 'Q1_data.csv'))\n", + "\n", + "# Alternative: path + \"/Q1_data.csv\"\n", + "df = pd.read_csv(path + \"/Q1_data.csv\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "df.head() # First 5 rows\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "df.tail() # Last 5 rows\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "df.info() # Data types and non-null counts\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "df.describe() # Statistics for numerical columns\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", + "Drop_ID = Drop.Order_ID_column" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "print(df.isnull().sum()) # Count missing values per column\n", + "print(df.isnull().sum().sum()) # Total missing values\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "print(df.isnull().sum()) # Count missing values per column\n", + "print(df.isnull().sum().sum()) # Total missing values\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "\n", + "from sklearn.preprocessing import OneHotEncoder\n", + "\n", + "encoder = OneHotEncoder(sparse=False, drop='first') # drop='first' to avoid dummy trap\n", + "encoded = encoder.fit_transform(df[['Order_ID_column']])" + ], + "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:\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "#Prepare Data\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)\n", + "\n", + "scaler = StandardScaler()\n", + "X_train_scaled = scaler.fit_transform(X_train) # Fit on training data ONLY\n", + "X_test_scaled = scaler.transform(X_test) # Transform test (NO fit!)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Choose and Train Model\n", + "# --- Linear Regression ---\n", + "model = LinearRegression()\n", + "\n", + "# --- Ridge Regression (L2 regularization) ---\n", + "model = Ridge(alpha=1.0)\n", + "\n", + "# --- Lasso Regression (L1 regularization) ---\n", + "model = Lasso(alpha=0.1)\n", + "\n", + "# --- Random Forest Regressor ---\n", + "model = RandomForestRegressor(n_estimators=100, random_state=42)\n", + "\n", + "# --- Decision Tree Regressor ---\n", + "model = DecisionTreeRegressor(random_state=42)\n", + "\n", + "# Fit the model\n", + "model.fit(X_train_scaled, y_train)\n", + "\n", + "# Make Predictions\n", + "y_pred = model.predict(X_test_scaled)\n", + "\n", + "# Evaluate\n", + "mse = mean_squared_error(y_test, y_pred)\n", + "rmse = np.sqrt(mse)\n", + "mae = mean_absolute_error(y_test, y_pred)\n", + "r2 = r2_score(y_test, y_pred)\n", + "\n", + "print(f\"MSE: {mse:.4f}\")\n", + "print(f\"RMSE: {rmse:.4f}\")\n", + "print(f\"MAE: {mae:.4f}\")\n", + "print(f\"R² Score: {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/250/Q2.ipynb b/submissions_extracted/250/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..983b635cd7198e04cd81400049b46b77ba653d83 --- /dev/null +++ b/submissions_extracted/250/Q2.ipynb @@ -0,0 +1,260 @@ +{ + "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_tensor = torch.tensor(X_train_scaled, dtype=torch.float32)\n", + "X_test_tensor = torch.tensor(X_test_scaled, dtype=torch.float32)\n", + "y_train_tensor = torch.tensor(y_train.values, dtype=torch.long) # long for CrossEntropyLoss\n", + "y_test_tensor = torch.tensor(y_test.values, dtype=torch.long)\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 2. Create TensorDataset objects\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 3. Create DataLoaders\n", + "batch_size = 32\n", + "train_dataset = TensorDataset(X_train_tensor, y_train_tensor)\n", + "test_dataset = TensorDataset(X_test_tensor, y_test_tensor)\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", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 4. Print shape of one batch\n", + "print(f\"Train batches: {len(train_loader)}, Test batches: {len(test_loader)}\")\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", + "input_dim = X_train_scaled.shape[1] # Number of features (columns)\n", + "# num_classes already set in STEP 3\n", + "\n", + "print(f\"============= AUTOMATIC DIMENSIONS =============\")\n", + "print(f\"Input dim (features): {input_dim}\")\n", + "print(f\"Output dim (classes): {num_classes}\")\n", + "print(f\"================================================\")\n", + "\n", + "class TabularClassifier(nn.Module):\n", + " def __init__(self, input_dim, num_classes):\n", + " super(TabularClassifier, self).__init__()\n", + " self.fc1 = nn.Linear(input_dim, 128) # input_dim -> 128\n", + " self.fc2 = nn.Linear(128, 64) # 128 -> 64\n", + " self.fc3 = nn.Linear(64, num_classes) # 64 -> num_classes\n", + "\n", + " def forward(self, x):\n", + " x = F.relu(self.fc1(x))\n", + " x = F.relu(self.fc2(x))\n", + " x = self.fc3(x) # No activation (CrossEntropyLoss handles it)\n", + " return x\n", + "\n", + "model = TabularClassifier(input_dim, num_classes)\n", + "print(f\"\\nModel architecture:\")\n", + "print(model)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your training loop here:\n", + "num_epochs = 50\n", + "for epoch in range(num_epochs):\n", + " train_loss = train_one_epoch(model, optimizer, criterion, train_loader, device)\n", + " if (epoch + 1) % 10 == 0:\n", + " val_acc = validate(model, criterion, test_loader, device)\n", + " print(f\"Epoch [{epoch+1}/{num_epochs}] - Loss: {train_loss:.4f}, Acc: {val_acc:.4f}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your validation loop here:\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 = model.to(device)\n", + "criterion = nn.CrossEntropyLoss()\n", + "optimizer = Adam(model.parameters(), lr=0.001)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Start training for 20 epochs:\n", + "\n", + "# Train & Validate functions\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", + " X_batch, y_batch = X_batch.to(device), y_batch.to(device)\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", + " return running_loss / len(train_loader)\n", + "\n", + "def validate(model, criterion, test_loader, device):\n", + " model.eval()\n", + " correct, total = 0, 0\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", + " outputs = model(X_batch)\n", + " predictions = torch.argmax(outputs, dim=1)\n", + " correct += (predictions == y_batch).sum().item()\n", + " total += y_batch.size(0)\n", + " return correct / total\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 (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/250/Q3.ipynb b/submissions_extracted/250/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..100a23c3679cb169992cca74c5731eae1cd2a51d --- /dev/null +++ b/submissions_extracted/250/Q3.ipynb @@ -0,0 +1,278 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# ============================================\n", + "# ESSENTIAL IMPORTS - COPY ALL OF THESE!\n", + "# ============================================\n", + "\n", + "# --- Basic Libraries ---\n", + "import numpy as np\n", + "import pandas as pd\n", + "import matplotlib.pyplot as plt\n", + "import os\n", + "import warnings\n", + "warnings.filterwarnings('ignore')\n", + "\n", + "# --- For downloading datasets ---\n", + "import kagglehub\n", + "\n", + "# --- Scikit-Learn: Data Splitting ---\n", + "from sklearn.model_selection import train_test_split, StratifiedKFold, cross_val_score\n", + "\n", + "# --- Scikit-Learn: Preprocessing ---\n", + "from sklearn.preprocessing import StandardScaler, MinMaxScaler, LabelEncoder, OneHotEncoder\n", + "from sklearn.impute import SimpleImputer\n", + "\n", + "# --- Scikit-Learn: Regression Models ---\n", + "from sklearn.linear_model import LinearRegression, Ridge, Lasso\n", + "from sklearn.ensemble import RandomForestRegressor, GradientBoostingRegressor\n", + "from sklearn.tree import DecisionTreeRegressor\n", + "from sklearn.svm import SVR\n", + "\n", + "# --- Scikit-Learn: Classification Models ---\n", + "from sklearn.linear_model import LogisticRegression\n", + "from sklearn.ensemble import RandomForestClassifier, GradientBoostingClassifier\n", + "from sklearn.tree import DecisionTreeClassifier\n", + "from sklearn.svm import SVC\n", + "from sklearn.neighbors import KNeighborsClassifier\n", + "\n", + "# --- Scikit-Learn: Metrics ---\n", + "from sklearn.metrics import (\n", + " # Regression metrics\n", + " mean_squared_error, mean_absolute_error, r2_score,\n", + " # Classification metrics\n", + " accuracy_score, precision_score, recall_score, f1_score,\n", + " classification_report, confusion_matrix, roc_auc_score, roc_curve\n", + ")\n", + "\n", + "# --- Scikit-Learn: Unsupervised Learning ---\n", + "from sklearn.decomposition import PCA\n", + "from sklearn.manifold import TSNE\n", + "from sklearn.cluster import KMeans\n", + "\n", + "# --- PyTorch ---\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 images) ---\n", + "from torchvision.datasets import MNIST, CIFAR10\n", + "from torchvision.transforms.functional import to_tensor\n", + "from torchvision.transforms import ToTensor, Compose, Normalize\n", + "\n", + "# --- Check PyTorch/CUDA ---\n", + "print(f\"PyTorch version: {torch.__version__}\")\n", + "print(f\"CUDA available: {torch.cuda.is_available()}\")\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", + "\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q3-exam-data\")\n", + "print(\"Path to dataset files:\", path)\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "# Then load the CSV\n", + "df = pd.read_csv(os.path.join(path, 'Q3_data.csv'))\n", + "\n", + "# Alternative: path + \"/Q1_data.csv\"\n", + "df = pd.read_csv(path + \"/Q3_data.csv\")\n", + "\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "df.head() # First 5 rows\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() # Statistics for numerical columns\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "df_clean = df.dropna()\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "df_clean = df_clean.drop_duplicates()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "\n", + "# ENCODE CATEGORICAL\n", + "# Find categorical columns\n", + "cat_cols = df_clean.select_dtypes(include=['object']).columns.tolist()\n", + "print(f\"Categorical columns: {cat_cols}\")\n", + "\n", + "# Encode using LabelEncoder\n", + "le = LabelEncoder()\n", + "for col in cat_cols:\n", + " if col != target_col: # Don't encode target yet\n", + " df_clean[col] = le.fit_transform(df_clean[col])\n", + "\n", + "# If target is string, encode it too\n", + "if df_clean[target_col].dtype == 'object':\n", + " df_clean[target_col] = le.fit_transform(df_clean[target_col])" + ], + "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", + "data = load_breast_cancer()\n", + "X = data.data # Features\n", + "y = data.target # Target labels\n", + "feature_names = data.feature_names\n", + "target_names = data.target_names" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:\n", + "\n", + "\n", + "# K-Fold setup (use StratifiedKFold for classification)\n", + "kfold = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)\n", + "\n", + "# Evaluate each model with K-Fold\n", + "print(\"===== K-FOLD CROSS-VALIDATION RESULTS =====\")\n", + "cv_results = {}\n", + "\n", + "for name, model in models.items():\n", + " scores = cross_val_score(model, X_train_scaled, y_train, cv=kfold, scoring='accuracy')\n", + " cv_results[name] = scores\n", + " print(f\"{name}:\")\n", + " print(f\" Scores: {scores.round(4)}\")\n", + " print(f\" Mean: {scores.mean():.4f} (+/- {scores.std()*2:.4f})\\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/251/Q1.ipynb b/submissions_extracted/251/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..f975dd3833e1f1728ca1af59d9d656daddb980da --- /dev/null +++ b/submissions_extracted/251/Q1.ipynb @@ -0,0 +1,327 @@ +{ + "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", + "\n", + "\n", + "from sklearn.model_selection import train_test_split, KFold #80 - 20\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", + "# Load the dataset\n", + "delivery_path = os.path.join(path, 'Q1_data.csv')#دمج الباث مع الفايل\n", + "df_delivery = pd.read_csv(delivery_path)#تحميل الملف ا\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() #Display Index, Columns, and Data:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "df_delivery.describe()#Summary Statistics" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "\n", + "\n", + "plt.figure(figsize=(10, 5))\n", + "plt.hist(df_delivery['Delivery_Time'].dropna(), bins=30, edgecolor='black')\n", + "plt.title('target 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.drop(columns=['Order_ID']) #Drop Columns" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "print(\"Missing values:\")\n", + "print(df_delivery.isnull().sum())#Check for Missing Values (isnull)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\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", + "# if the number is 0, then we have no duplicated rows\n" + ], + "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", + " # 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" + ], + "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_delivery) #show before scaling\n", + "standard_scaler = StandardScaler() # Instantiate StandardScaler\n", + "data_standard_scaled = standard_scaler.fit_transform(df_delivery) # 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", + "# First, let's convert the target variable to numeric\n", + "# status: Placed = 1, Not Placed = 0\n", + "df_delivery['status'] = df_delivery['status'].map({'Placed': 1, 'Not Placed': 0})#زي ليبل انكودر يبدل بليسد بواحد\n", + "# Is the target imbalanced?\n", + "def check_target_imbalance(df, Delivery_Time):\n", + " print(\"Target Distribution:\")\n", + " print(df_delivery[Delivery_Time].value_counts(normalize=True))#نحسب كم البليسد و نسوي لهم نورملايزد يعني عددهم قسمه الكل 10/30 و نوت بليسد 20\n", + " sns.countplot(x=df_delivery[Delivery_Time])\n", + " plt.title(\"Target Distribution\")\n", + " plt.show()\n", + "\n", + "check_target_imbalance(df_delivery, \"status\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "from sklearn.model_selection import train_test_split\n", + "\n", + "# Use previously generated random data (example: classification data)\n", + "X, y = df_delivery.copy(), df_delivery.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", + "# 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 2,3,4,5: Write your code here:\n", + "#2\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", + " #3\n", + " from sklearn.ensemble import RandomForestClassifier\n", + " sklearn_model = { \"Random Forest\": RandomForestClassifier(\n", + " n_estimators=320, # Number of trees\n", + " max_depth=4\n", + " )}\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + " #4\n", + " # Evaluation metrics\n", + " mse_scores.append(mean_squared_error(y_test, y_pred))\n", + " mae_scores.append(mean_absolute_error(y_test, y_pred))\n", + "\n", + "\n", + "# Print Evaluation Metrics\n", + "print(\"\\nModel Evaluation Metrics (K-Fold)\\n\" + \"-\"*40)\n", + "print(f\"MAE : {np.mean(mae_scores):.2f}\")\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", + "# Plot Predictions\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", + ")" + ], + "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/251/Q2.ipynb b/submissions_extracted/251/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..e440f98ccbb72a4169debf9cf841c96590f43aaa --- /dev/null +++ b/submissions_extracted/251/Q2.ipynb @@ -0,0 +1,374 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "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", + "\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": [ + "import kagglehub\n", + "import torch#المكتبه\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", + "#(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", + "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", + "# TODO: Transform to PyTorch tensors with dtype=torch.float32\n", + "X_train = torch.tensor(X_train.x, dtype=torch.float32)\n", + "X_test = torch.tensor(X_test.x, dtype=torch.float32)\n", + "y_train = torch.tensor(y_train.y, dtype=torch.float32)\n", + "y_test = torch.tensor(y_test.y, dtype=torch.float32)\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", + "\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", + "# 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", + "\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", + "\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", + " # thered 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", + " # therd 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.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 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", + "\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", + "\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", + "num_epochs = 20\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", + "\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+20}/{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:" + ], + "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/251/Q3.ipynb b/submissions_extracted/251/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..4d5c67395850d297d78f9d3f230317ddc514966c --- /dev/null +++ b/submissions_extracted/251/Q3.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", + "\n", + "\n", + "from sklearn.model_selection import train_test_split, KFold #80 - 20\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", + "\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", + "Anonymized_path = os.path.join(path, 'Q3_data.csv')\n", + "df_Anonymized = pd.read_csv(Anonymized_path)#تحميل الملف ا" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "df_Anonymized.head()#طباعه اول خمس" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "df_Anonymized.info()# Display Index, Columns, and Data:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "df_Anonymized.describe()#Summary Statistics" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "print(\"Missing values:\")\n", + "print(df_Anonymized.isnull().sum())#Check for Missing Values (isnull)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\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", + "# if the number is 0, then we have no duplicated rows" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "# Encode categorical columns - converts text to integers\n", + "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", + "df_clean.head()\n", + "\n", + "#i rhenk we dont need it" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "from sklearn.preprocessing import StandardScaler #import StandardScaler\n", + "data=df_Anonymized\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))" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:# First, let's convert the target variable to numeric\n", + "# status: Placed = 1, Not Placed = 0\n", + "df_Anonymized['status'] = df_Anonymized['status'].map({'Placed': 1, 'Not Placed': 0})#زي ليبل انكودر يبدل بليسد بواحد\n", + "# Is the target imbalanced?\n", + "def check_target_imbalance(df, Delivery_Time):\n", + " print(\"Target Distribution:\")\n", + " print(df_Anonymized[Delivery_Time].value_counts(normalize=True))#نحسب كم البليسد و نسوي لهم نورملايزد يعني عددهم قسمه الكل 10/30 و نوت بليسد 20\n", + " sns.countplot(x=df_Anonymized[Delivery_Time])\n", + " plt.title(\"Target Distribution\")\n", + " plt.show()\n", + "\n", + "check_target_imbalance(df_Anonymized, \"status\")" + ], + "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:\n", + "#2\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", + "\n", + " #3\n", + "from catboost import CatBoostClassifier\n", + " sklearn_model = { \"CatBoost\": CatBoostClassifier(\n", + " verbose=0,\n", + " n_estimators=320,\n", + " max_depth=4\n", + " )\n", + "}\n", + "\n", + "\n", + "\n", + "\n", + "#5\n", + " results = {}\n", + " results[sklearn_model] = {'recall': [], 'f1': []}\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", + " 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/252/Q1.ipynb b/submissions_extracted/252/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..f793c773a681e4397f7a8779759837c397a16ba0 --- /dev/null +++ b/submissions_extracted/252/Q1.ipynb @@ -0,0 +1,246 @@ +{ + "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:Read the dataset Q1_data.csv using read_csv()\n", + "#1- download labrary\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", + "#2-read dataset\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:" + ], + "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", + "#Handle missing values appropriately (Hint: I guess you want to have a closer look at the columns with missing values :) )\n", + "print(\"Missing values:\")\n", + "print(df_food.isnull().sum())\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "#Check and remove duplicates if any exist\n", + "#1-Drop Missing Values\n", + "df_food.dropna()\n", + "\n", + "#2-" + ], + "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", + "\n", + "df_clean = df_food.dropna().copy()\n", + "le = LabelEncoder()\n", + "# Fit on ALL types found in both columns so the numbers match\n", + "all_types = pd.concat([df_clean['Time_of_Day'], df_clean['Vehicle_Type']])\n", + "le.fit(all_types)\n", + "df_clean['Time_of_Day'] = le.transform(df_clean['Time_of_Day'])\n", + "df_clean['Vehicle_Type'] = le.transform(df_clean['Vehicle_Type'])" + ], + "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", + "#1- first doing is Feature Engineering to better\n", + "df_clean['late_Delivery_Time'] = 10 - df_clean['Delivery_Time'].head()\n", + "feature_cols = ['Order_ID' , 'Distance_km' , 'Preparation_Time_min' ,\n", + " 'Courier_Experience_yrs' , 'Delivery_Time']\n", + "#2-Scale features\n", + "# Train-test split (80% train, 20% test)\n", + "x = df_clean[feature_cols]\n", + "y = df_clean['Courier_Experience_yrs']\n", + "# TODO: Split data\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", + "\n", + "scaler = StandardScaler()\n", + "X_train_scaled = scaler.fit_transform(X_train)\n", + "X_test_scaled = scaler.transform(X_test)\n" + ], + "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" + ], + "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", + "#2-Use the correct split: KFold OR StratifiedKFold\n", + "\n", + "\n", + "#3-Train a RandomForest model\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", + "# TODO: Predict\n", + "y_pred = model.predict(X_test)\n", + "#4-Evaluate using MAE (Mean Absolute Error) ONLY\n", + "\n", + "\n", + "#5-Print the averaged score across all folds" + ], + "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/252/Q2.ipynb b/submissions_extracted/252/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..c8937ff34d658b6340ef5c82e1d71e84083e0ea8 --- /dev/null +++ b/submissions_extracted/252/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/252/Q3.ipynb b/submissions_extracted/252/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..a231dc2558d9cffb98106af83f71ebf1e446dd3d --- /dev/null +++ b/submissions_extracted/252/Q3.ipynb @@ -0,0 +1,214 @@ +{ + "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", + "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", + "a_path = os.path.join(path, 'Q3_data.csv')\n", + "df = pd.read_csv(a_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(\"Missing values:\")\n", + "print(df.isnull().sum())" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "df.dropna()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "df_clean = df.dropna().copy()\n", + "le = LabelEncoder()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "#1- first doing is Feature Engineering to better\n", + "feature_cols = [ 'D_39' , 'B_1' , 'B_2' , 'R_1' , 'S_3' , 'D_41' ,'B_3']\n", + "#2-Scale features\n", + "# Train-test split (80% train, 20% test)\n", + "x = df_clean[feature_cols]\n", + "y = df_clean['P_2']\n", + "# TODO: Split data\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", + "\n", + "scaler = StandardScaler()\n", + "X_train_scaled = scaler.fit_transform(X_train)\n", + "X_test_scaled = scaler.transform(X_test)\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", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:\n", + "\n", + "#2-\n", + "\n", + "#3- Train a CatBoostClassifier model\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" + ], + "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/253/Q1.ipynb b/submissions_extracted/253/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..b61919b50894af44ff00692f76f3f6d15a5c4a8f --- /dev/null +++ b/submissions_extracted/253/Q1.ipynb @@ -0,0 +1,287 @@ +{ + "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", + "# 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, \"/kaggle/input/q1-exam-data/Q1_data.csv\")\n", + "\n", + "df = pd.read_csv(csv_path)\n", + "df.head()\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "df.info()\n" + ], + "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_pokemon['delivery_time'].dropna(), bins=30, edgecolor='black')\n", + "plt.title('delivery time')\n", + "plt.xlabel('delivery time')\n", + "plt.ylabel('houre')\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "df.drop(columns=['Order_ID'])" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "df.isnull().sum()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "df['Courier_Experience_yrs'] = df['Courier_Experience_yrs'].fillna(df['Courier_Experience_yrs'].median())\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "df.dropna(subset=['Weather'])\n", + "df.dropna(subset=['Traffic_Level'])\n", + "df.dropna(subset=['Time_of_Day'])\n", + "df.dropna(subset=['Courier_Experience_yrs'])\n", + "df.dropna(subset=['Delivery_Time'])\n", + "\n", + "\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "df.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)\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\n", + "\n", + "print('data before encoding:\\n', df)\n", + "\n", + "onehot_encoder = OneHotEncoder(sparse_output=False)\n", + "data_onehot_encoded = onehot_encoder.fit_transform(df)\n", + "\n", + "print('\\nData after encoding:\\n', data_onehot_encoded)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "data_for_scale = pd.DataFrame({\"Feature_1\": ['a'],\"Feature_2\": ['b']})\n", + "\n", + "print(\"Before scaling:\")\n", + "data_for_scale\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "from sklearn.preprocessing import StandardScaler\n", + "\n", + "print('data before scaling:\\n', data_for_scale)\n", + "standard_scaler = StandardScaler()\n", + "data_standard_scaled = standard_scaler.fit_transform(data_for_scale)\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:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "from sklearn.model_selection import train_test_split\n", + "\n", + "# Use previously generated random data (example: classification data)\n", + "X = df[df.columns.drop('Delivery_Time')]\n", + "y = df['Delivery_Time']\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", + ")\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": [ + "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": [ + "average_losses = np.mean(df, axis=0)\n", + "\n", + "plt.figure(figsize=(10, 6))\n", + "plt.plot(df, label='a')\n", + "plt.xlabel('a')\n", + "plt.ylabel('a')\n", + "plt.title('a')\n", + "plt.legend()\n", + "plt.grid(True, alpha=0.3)\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "average_losses = np.mean(delivery_time, axis=0)\n", + "\n", + "plt.figure(figsize=(10, 6))\n", + "plt.plot(average_losses, label='a')\n", + "plt.xlabel('a')\n", + "plt.ylabel('a')\n", + "plt.title('a')\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/253/Q2.ipynb b/submissions_extracted/253/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..7c6905ddb96c317b8fb78b7a0833c45fd2b8f3e9 --- /dev/null +++ b/submissions_extracted/253/Q2.ipynb @@ -0,0 +1,355 @@ +{ + "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": [ + "\n", + "X = images.data\n", + "y = images.target // noooo time\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": [ + "# 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", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "train_loader = DataLoader(\n", + " train_dataset,\n", + " batch_size=32,\n", + " shuffle=True,\n", + " num_workers=2\n", + ")\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "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", + "\n", + "linear = nn.Linear(in_features=4, out_features=1)\n", + "\n", + "x = torch.randn(4, 3)\n", + "\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])" + ], + "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.view(-1, 1).to(device)\n", + " outputs = model(X_batch)\n", + " loss = criterion(outputs, y_batch)\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", + " 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(): # 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": [], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 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", + "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", + "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": [ + "# Plotting results\n", + "plt.figure(figsize=(7, 5))\n", + "\n", + "plt.plot(train_losses, label='a')\n", + "plt.plot(val_losses, label='a')\n", + "plt.title('a')\n", + "plt.xlabel('a')\n", + "plt.ylabel('a')\n", + "plt.legend()\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/253/Q3.ipynb b/submissions_extracted/253/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..550118e87164f043083f4e5fb8a0fd2720e05153 --- /dev/null +++ b/submissions_extracted/253/Q3.ipynb @@ -0,0 +1,247 @@ +{ + "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", + "\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, \"/kaggle/input/q3-exam-data/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": [ + "df.isnull().sum()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "df['P_2'] = df['P_2'].fillna(df['P_2'].median())\n", + "df['B_2'] = df['B_2'].fillna(df['B_2'].median())\n", + "df['D_142'] = df['D_142'].fillna(df['D_142'].median())\n", + "df['D_143'] = df['D_143'].fillna(df['D_143'].median())\n", + "df['D_144'] = df['D_144'].fillna(df['D_144'].median())\n", + "df['D_145'] = df['D_145'].fillna(df['D_145'].median())\n", + "\n", + "\n", + "\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "df.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)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3 no need" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "from sklearn.preprocessing import StandardScaler\n", + "\n", + "print('data before scaling:\\n', data_for_scale)\n", + "standard_scaler = StandardScaler()\n", + "df[df.columns.drop('Target')] = standard_scaler.fit_transform(df[df.columns.drop('Target')])\n", + "\n", + "print('\\nData after scaling:\\n', data_standard_scaled)" + ], + "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\n", + "\n", + "# Use previously generated random data (example: classification data)\n", + "X = df[df.columns.drop('Delivery_Time')]\n", + "y = df['Delivery_Time']\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", + ")\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": [ + "from sklearn.preprocessing import StandardScaler\n", + "\n", + "print('data before scaling:\\n', data_for_scale)\n", + "standard_scaler = StandardScaler()\n", + "data_standard_scaled = standard_scaler.fit_transform(data_for_scale)\n", + "\n", + "print('\\nData after scaling:\\n', data_standard_scaled)\n", + "\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "importances = {}\n", + "\n", + "importances['a'] = sklearn_models['a'].feature_importances_\n", + "importances['a'] = sklearn_models['a'].feature_importances_\n", + "importances['a'] = sklearn_models['a'].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", + " 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} a\")\n", + " ax.set_xlabel(\"a\")\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": [ + "# 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/254/Q1.ipynb b/submissions_extracted/254/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..1edf74c828a03f520dbc46e7b765a9f8721a351b --- /dev/null +++ b/submissions_extracted/254/Q1.ipynb @@ -0,0 +1,322 @@ +{ + "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", + "\n" + ], + "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", + " 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)\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", + "print(\"Categorical Columns:\", list(categorical_cols))\n", + "\n", + "import sklearn\n", + "from sklearn.preprocessing import OneHotEncoder\n", + "\n", + "label_encoders = {}\n", + "for col in categorical_cols:\n", + " le = OneHotEncoder()\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: Write your code here:\n", + "\n", + "from sklearn.preprocessing import StandardScaler\n", + "features = df.columns.drop(\"Delivery_Time\") # DON'T SCALE THE TARGET\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", + "import matplotlib.pyplot as plt\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", + "X = df.drop(\"Delivery_Time\", axis=1)\n", + "y = df['Delivery_Time']" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import numpy as np\n", + "from tqdm import tqdm\n", + "# Mean Squared Error in NumPy\n", + "def mean_absloult_error(y, y_hat):\n", + " return (1 / (2 * len(y))) * np.sum((y_hat - y) )\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_absloult_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\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", + "# Storage for linear regression results for each fold\n", + "lr_losses = []\n", + "lr_mse = []\n", + "lr_rmse = []\n", + "lr_r2 = []\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", + " # 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", + "\n", + "\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" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "print(\"Linear Regression Results\")\n", + "print(f\" Average MSE: {np.mean(lr_mse):.4f}\")\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: 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", + "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/254/Q2.ipynb b/submissions_extracted/254/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..fe33cb9bc10a6b1bf77790bf5740c4ae0a83c2db --- /dev/null +++ b/submissions_extracted/254/Q2.ipynb @@ -0,0 +1,348 @@ +{ + "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 DataLoader\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" + ], + "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" + ], + "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", + "\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) # do we use softmax here?\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" + ], + "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)\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:\n", + "\n", + "num_epochs = 20\n", + "learning_rate = 0.001\n", + "\n", + "# Define criterion (loss function)\n", + "criterion = nn.CrossEntropyLoss()\n", + "# Define optimizer\n", + "# optimizer choices adamW, SGD, adam, RMSprop\n", + "# usage torch.optim.YOUR_CHOICE(model.parameters(), lr=LEARNING_RATE, other_args)\n", + "optimizer = AdamW(model.parameters(), 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", + " 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/254/Q3.ipynb b/submissions_extracted/254/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..eaeaa0ff0a27ca477dc20d85c7803742cbf7eead --- /dev/null +++ b/submissions_extracted/254/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()\n", + "\n", + "\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 3: Write your code here:\n", + "import sklearn\n", + "from sklearn.preprocessing import LabelEncoder\n", + "\n", + "# 3. Do we have 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", + "\n", + "from sklearn.preprocessing import StandardScaler\n", + "features = df.columns.drop(\"Target\") # DON'T SCALE THE TARGET\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", + "# 1. Is the target imbalanced?\n", + "import matplotlib.pyplot as plt\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\")" + ], + "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']" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 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)\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", + "" + ], + "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 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" + ], + "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", + "\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", + "# Storage for logistic regression results for each fold\n", + "lr_accuracy = []\n", + "lr_f1 = []" + ], + "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]\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_accuracy.append(accuracy)\n", + " lr_f1.append(f1)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "# Calculate average loss across folds\n", + "\n", + "import numpy as np\n", + "import matplotlib.pyplot as plt\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 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/255/Q1.ipynb b/submissions_extracted/255/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..5edcb0d8c27d49b275a0ec2ee8a088801896e461 --- /dev/null +++ b/submissions_extracted/255/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": [ + "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" + ], + "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", + "#Your target is the column: \"delivery_time\".\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", + "df = df.drop(columns=\"Order_ID\", axis=1)" + ], + "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\n", + "#the columns with missing values :) )\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)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# we have missing values , so drop\n", + "#df = df.drop(columns=\"Order_ID\",\"Weather\", \"Traffic_Level\",\"Time_of_Day\",axis=1)\n", + "stat_cols= [\"Weather\", \"Traffic_Level\",\"Time_of_Day\"]\n", + "# Drop rows with missing stat values\n", + "df_clean = df.dropna(subset=stat_cols).copy()\n", + "df = df.drop(columns=\"Weather\", axis=1)\n", + "df = df.drop(columns=\"Traffic_Level\", axis=1)\n", + "df = df.drop(columns=\"Time_of_Day\", axis=1)\n", + "# Fill missing\n", + "#df_clean['Weather'] = df_clean['type2'].fillna('none')" + ], + "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) # 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", + "#3. Do we have 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", + "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: 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" + ], + "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) # .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 # K=5 Folds\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" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "from sklearn.ensemble import RandomForestClassifier\n", + "\n", + "#**Define models with their hyperparameters**\n", + "models = {\n", + " \"Random Forest\": RandomForestClassifier(\n", + " n_estimators=320, # Number of trees\n", + " max_depth=4\n", + " )\n", + "}\n", + "\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/255/Q2.ipynb b/submissions_extracted/255/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..8a6239ce0f2844b6664c710a12bd08fc7858e855 --- /dev/null +++ b/submissions_extracted/255/Q2.ipynb @@ -0,0 +1,385 @@ +{ + "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 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" + ], + "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", + "# 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" + ], + "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)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 4. Print shape of one batch\n", + "\n", + "# Get the first batch from the 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", + "import matplotlib.pyplot as plt\n", + "\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", + "class NN4Layer(nn.Module):\n", + "\n", + " def __init__(self, input_dim, hidden_dim, output_dim):\n", + " # تهيئة الكلاس الأساسي من مكتبة PyTorch\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 laye\n", + " self.layer2 = nn.Linear(hidden_dim, hidden_dim)\n", + "\n", + " # therd 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", + " # ReLU activation for non-linearity\n", + " self.relu = nn.ReLU()\n", + "\n", + " def forward(self, x):\n", + " \"\"\" Adding Flatten here\"\"\"\n", + " # Flatten the input image from (Batch, 1, 28, 28) to (Batch, 784)\n", + " # هذا هو الجزء الناقص: \"فرد\" المصفوفة المربعة لتصبح خطاً مستقيماً ليناسب الطبقة الخطية\n", + " x = x.view(x.size(0), -1)\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", + " # ال كارتيزين مردي ايش ذا هو اللوس فنكشن\n", + " # 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", + " # Move batch to the selected device\n", + " # تحويل أبعاد الصورة من (28x28) إلى (784) ونقلها إلى المعالج (CPU/GPU)\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) [32,10]\n", + " # حساب مقدار الخطأ بين توقع النموذج والرقم الحقيقي المكتوب في الصورة\n", + " loss = criterion(outputs, y_batch)\n", + "\n", + " # Backward pass & optimization\n", + " # مرحلة التعلم العكسي وتحسين الأوزان\n", + " optimizer.zero_grad() # Clear previous gradients | مسح حسابات الخطأ السابقة\n", + " loss.backward() # Compute gradients | حساب مقدار التغيير المطلوب لكل وزن\n", + " optimizer.step() # Update model parameters | تحديث أوزان النموذج فعلياً\n", + "\n", + " # ايبوك إضافة قيمة خسارة الدفعة الحالية للمجموع\n", + " running_loss += loss.item()\n", + "\n", + " # Average loss over all batches\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): # no optmizer cause .....\n", + " # Set the model to evaluation mode\n", + " # وضع النموذج في حالة التقييم (إيقاف تحديث الأوزان)\n", + " model.eval()\n", + "\n", + " running_loss = 0.0\n", + " correct = 0 # عداد للإجابات الصحيحة\n", + " total = 0 # إجمالي عدد الصور التي تم اختبارها\n", + "\n", + " # إيقاف حساب التدرجات لتوفير الذاكرة وسرعة التنفيذ\n", + " with torch.no_grad():\n", + " for X_batch, y_batch in test_loader:\n", + " # Move data to device\n", + " # تحويل أبعاد الصور (Flatten) ونقلها إلى المعالج أو كرت الشاشة\n", + " X_batch = X_batch.view(X_batch.size(0), -1).to(device) # MUST flatten in val & train\n", + " y_batch = y_batch.to(device)\n", + "\n", + " # Forward pass\n", + " # مرحلة التخمين: استخراج النتائج الخام (Logits) من النموذج\n", + " outputs = model(X_batch) # shape: (batch_size, 10)\n", + " # حساب مقدار الخطأ في الاختبار\n", + " loss = criterion(outputs, y_batch)\n", + " running_loss += loss.item()\n", + "\n", + " # Note : NO Backword in Val , prev code is the same as train loop ❌\n", + "\n", + " # Apply Softmax to get probabilities\n", + " # تحويل النتائج الخام إلى نسب مئوية (احتمالات) لكل رقم من 0 إلى 9\n", + " probabilities = F.softmax(outputs, dim=1) # دايمنشن 0 فيه الباتش، الكلاسات متخزنة في دايمنشن 1\n", + "\n", + " # Multiclass predictions\n", + " # اختيار الرقم صاحب أعلى نسبة احتمال كقرار نهائي للنموذج\n", + " # حطينا ارقماكس عشان ترجع انديكس؟؟\n", + " predicted = torch.argmax(probabilities, dim=1)\n", + "\n", + " # Accuracy calculation\n", + " # مقارنة توقع النموذج بالحقيقة وزيادة عداد الإجابات الصحيحة\n", + " correct += (predicted == y_batch).sum().item() #.item() cause sum return array [20]\n", + " total += y_batch.size(0)\n", + "\n", + " # حساب متوسط الخسارة في مرحلة الاختبار\n", + " avg_loss = running_loss / len(test_loader)\n", + " # حساب نسبة الدقة النهائية (عدد الإجابات الصحيحة ÷ الإجمالي)\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", + "# تحديد الجهاز: استخدام كرت الشاشة (CUDA) إذا كان متاحاً لتسريع العمل، وإلا الاعتماد على المعالج (CPU)\n", + "device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n", + "\n", + "# Model parameters\n", + "input_dim = 28 * 28 # MNIST images flattened | عدد المدخلات (784 بكسل) بعد فرد الصورة\n", + "hidden_dim = 14 # Design choice | عدد الخلايا في الطبقات المخفية (يمكنك زيادته لتحسين الدقة) انا اختار اي رقم هنا\n", + "output_dim = 10 # Digits 0–9 | عدد المخرجات (10 أصناف للأرقام من 0 إلى 9)\n", + "\n", + "# Instantiate model\n", + "# إنشاء نسخة من النموذج ونقل جميع أوزانه إلى الجهاز المختار (GPU أو CPU)\n", + "model = NN4Layer(input_dim, hidden_dim, output_dim).to(device)\n", + "# Define criterion (loss function) - using CrossEntropyLoss as model now outputs logits\n", + "criterion = nn.CrossEntropyLoss()\n", + "# Define optimizer\n", + "from torch.optim import Adam\n", + "learning_rate = 0.001\n", + "optimizer = Adam(model.parameters(), learning_rate)\n", + "print(model)\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", + "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", + "" + ], + "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/255/Q3.ipynb b/submissions_extracted/255/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..01ed7eac8628a8996b635a972f443a2d46782990 --- /dev/null +++ b/submissions_extracted/255/Q3.ipynb @@ -0,0 +1,274 @@ +{ + "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 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": [ + "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", + "# 2. Do we have missing values?\n", + "def check_missing_values(df):\n", + " missing_values = df.isnull().sum() # isnull= تحول الجدول الى T,F والقيمة المفقودة تكون true\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", + "# Define stat columns\n", + "#'stat_cols = ['hp', 'attack', 'defense', 'sp_attack', 'sp_defense', 'speed']\n", + "\n" + ], + "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", + "# 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) # 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", + "\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\") # 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]) # رسم باستخدام sns\n", + " plt.title(\"Target Distribution\")\n", + " plt.show()\n", + "\n", + "check_target_imbalance(df, \"Target\")\n", + "# there is imbalanced" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "from sklearn.model_selection import StratifiedKFold\n", + "n_splits = 5 # K=5 Folds\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": [ + "# Task 2,3,4,5: Write your code here:\n", + "from catboost import CatBoostClassifier\n", + "sklearn_models = {\"CatBoost\": CatBoostClassifier(\n", + " verbose=0,\n", + " n_estimators=320,\n", + " max_depth=4\n", + " )\n", + "}\n", + "np.zeros(n_samples)\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" + ], + "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/256/Q1.ipynb b/submissions_extracted/256/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..905cfb6c7b022506cf0804cce2f12b8473a7012c --- /dev/null +++ b/submissions_extracted/256/Q1.ipynb @@ -0,0 +1,268 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "import pandas as pd\n", + "import os\n", + "import matplotlib.pyplot as plt\n", + "import seaborn as sns\n", + "from sklearn.ensemble import RandomForestRegressor\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", + "\n", + "df_q1= pd.read_csv(q1_path)\n" + ], + "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", + "delivery_time_counts = df_q1['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('delivery_time Distribution')\n", + "plt.xlabel('delivery_time')\n", + "plt.ylabel('Count')\n", + "plt.xticks(rotation=45)\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "df_q1.dropna['Order_ID'] #df.drop(columns=['col'])\n", + "df_q1.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here: Handle missing values appropriately\n", + "df_q1.describe() # no missing values" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:Check and remove duplicates\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:Encode categorical variables\n", + "from sklearn.preprocessing import OneHotEncoder #import OneHotEncoder\n", + "print('data before encoding:\\n',Traffic_Level) #show before encoding\n", + "onehot_encoder = OneHotEncoder(sparse_output=False) # Instantiate OneHot\n", + "data_onehot_encoded = onehot_encoder.fit_transform(Traffic_Level) # Apply\n", + "print('\\nData after encoding:\\n', data_onehot_encoded)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:apply feature scaling for all features\n", + "from sklearn.preprocessing import StandardScaler #import StandardScaler\n", + "data_for_scale = pd.DataFrame(df_q1 ['Preparation_Time_min'],df_q1['Distance_km'])\n", + "tandard_scaler = StandardScaler()\n", + "data_standard_scaled = standard_scaler.fit_transform(data_for_scale)" + ], + "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", + "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", + "check_target_imbalance(df, \"status\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here: Order_ID\tDistance_km\tWeather\tTraffic_Level\tTime_of_Day\tVehicle_Type\tPreparation_Time_min\tCourier_Experience_yrs\tDelivery_Time\n", + "# Define features (X) and target (y)\n", + "feature_cols = ['Order_ID', 'Distance_km', 'Weather', 'Traffic_Level',\n", + "'Time_of_Day', 'Vehicle_Type', 'Preparation_Time_min', 'Courier_Experience_yrs'\n", + "]\n", + "X = df_q1[feature_cols]\n", + "y = df_q1['Delivery_Time']\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", + "from sklearn.model_selection import train_test_split\n", + "# Use previously generated random data (example: classification data)\n", + "X, y = X_clf.copy(), y_clf.copy()\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", + "from sklearn.model_selection import KFold\n", + "# Use previously generated random data (example: regression data)\n", + "X, y = X_reg.copy(), y_reg.copy()\n", + "# Define K-Fold Cross Validation\n", + "kf = KFold(n_splits=5, shuffle=True, random_state=42)\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(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", + "#3\n", + "sklearn_models = {\n", + "\"Random Forest\": RandomForestClassifier(\n", + "n_estimators=320, # Number of trees\n", + "max_depth=4)\n", + "\n", + "}\n", + "\n", + "\n", + "\n", + "#4\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)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\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", + "plt.tight_layout()\n", + "plt.show()" + ], + "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/256/Q2.ipynb b/submissions_extracted/256/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..d08925097dba9ae00109986e88d656d5825bec9a --- /dev/null +++ b/submissions_extracted/256/Q2.ipynb @@ -0,0 +1,230 @@ +{ + "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", + "data = load_Labels()\n", + "X = data.data\n", + "y = data.target\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", + "scaler = StandardScaler()\n", + "X_train = scaler.fit_transform(X_train)\n", + "X_test = scaler.transform(X_test)\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", + "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)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 4. Print shape of one batch\n", + "print(\"bath shape:\", train_loader.shape)\n" + ], + "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", + "plt.imshow(images[i].squeeze(), cmap='gray')\n", + "plt.title(f\"Label: {labels[i].item()}\")\n", + "plt.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:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your training loop here:\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}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your validation loop here:\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:" + ], + "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/256/Q3.ipynb b/submissions_extracted/256/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..e70ce50060aa41eb505d4aee55c6fee06a15bf2b --- /dev/null +++ b/submissions_extracted/256/Q3.ipynb @@ -0,0 +1,222 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "import pandas as pd\n", + "import os\n", + "from catboost import CatBoostRegresso\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", + "\n", + "df_q3= pd.read_csv(q3_path)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "df_q3.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "df_q3.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "df_q3.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here: # there are missing values so im going to fill in where col is not that empty\n", + "df_q3['D_43'].fillna(df_q3['D_43'].mean())\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "# no duplicatse" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "#no Categorical" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "from sklearn.preprocessing import StandardScaler #import StandardScaler\n", + "data_for_scale = pd.DataFrame({\"Feature_1\": [D_140\t],\"Feature_2\":[D_141\t]})\n", + "standard_scaler = StandardScaler()\n", + "data_standard_scaled = standard_scaler.fit_transform(data_for_scale)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:Check for target imbalance and state if it is imbalanced or not\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", + "check_target_imbalance(df, \"status\")" + ], + "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 = ['P_2', 'D_39', 'B_1', 'B_2']\n", + "X = df_q1[feature_cols]\n", + "y = df_q1['D_144']\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", + "from sklearn.model_selection import train_test_split\n", + "# Use previously generated random data (example: classification data)\n", + "X, y = X_clf.copy(), y_clf.copy()\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", + "from sklearn.model_selection import KFold\n", + "# Use previously generated random data (example: regression data)\n", + "X, y = X_reg.copy(), y_reg.copy()\n", + "# Define K-Fold Cross Validation\n", + "kf = KFold(n_splits=5, shuffle=True, random_state=42)\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(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", + "\"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:" + ], + "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/257/Q1.ipynb b/submissions_extracted/257/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..8a815f144bbe2123c04084ee550e9f0c3eec11d2 --- /dev/null +++ b/submissions_extracted/257/Q1.ipynb @@ -0,0 +1,180 @@ +{ + "cells": [ + { + "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": [ + " read_csv(delivery_time)" + ], + "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/257/Q2.ipynb b/submissions_extracted/257/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..bafdfc47325fa2323c31baec119b4fe9f22ac956 --- /dev/null +++ b/submissions_extracted/257/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 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.shape)\n", + "X_test= torch.tensor(X_test.shape)\n", + "y_train=torch.tensor(y_train.shape)\n", + "y_test=torch.tensor(y_test.shape)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 2. Create TensorDataset objects\n", + "\n", + "import torch\n", + "#creat tensors\n", + "X_train shape:(1600,3,36,36)\n", + "X_test shape:(400,3,36,36)\n", + "y_train shape:(1600,)\n", + "y_test shape:(400,)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 3. Create DataLoaders\n", + "\n", + "\n", + "train_loader\n", + "test_loader" + ], + "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/257/Q3.ipynb b/submissions_extracted/257/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..80ae8be96e86780f686e8f4deb65875d9b97b715 --- /dev/null +++ b/submissions_extracted/257/Q3.ipynb @@ -0,0 +1,161 @@ +{ + "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", + "path.read_csv()" + ], + "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/258/Q1.ipynb b/submissions_extracted/258/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..f28871dee7b0829474bba7d8bc2012ee684f99cd --- /dev/null +++ b/submissions_extracted/258/Q1.ipynb @@ -0,0 +1,300 @@ +{ + "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", + "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')\n", + "cars_path = os.path.join(path, 'Q1_data.csv')\n", + "df_cars = pd.read_csv(cars_path)\n", + "\n", + "print(f\"Dataset shape: {df_cars.shape}\")\n", + "df_cars.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code hereprint(\"First 5 rows of the dataset:\")\n", + "print(\"First 5 rows of the dataset:\")\n", + "#display(df.head)\n", + "df_cars.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "print(\"\\nDataset Information:\")\n", + "df_cars.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "print(\"\\nStatistical Description:\")\n", + "df_cars.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "plt.figure(figsize=(8, 5))\n", + "plt.hist(df_cars['Delivery_Time'].dropna(), bins=50, edgecolor='black')\n", + "plt.title('Distribution of Delivery Time')\n", + "plt.xlabel('Delivery_Time')\n", + "plt.ylabel('Order_ID')\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code\n", + "import pandas as pd\n", + "import numpy as np\n", + "\n", + "from sklearn.preprocessing import OneHotEncoder, StandardScaler\n", + "from sklearn.compose import ColumnTransformer\n", + "from sklearn.pipeline import Pipeline\n", + "if ['Order_ID'] in df.columns:\n", + " df = 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", + "numerical_cols = df.select_dtypes(include=['int64', 'float64']).columns\n", + "categorical_cols = df.select_dtypes(include=['object', 'category']).columns\n", + "df[numerical_cols] = df[numerical_cols].fillna(df[numerical_cols].median())\n", + "df[categorical_cols] = df[categorical_cols].fillna(df[categorical_cols].mode().iloc[0])" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code h\n", + "df.duplicated().sum()\n", + "df = df.drop_duplicates()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "X = df.drop(columns=['target'])\n", + "y = df['target']\n", + "preprocessor = ColumnTransformer(\n", + " transformers=[\n", + " ('num', StandardScaler(), numerical_cols.drop('target', errors='ignore')),\n", + " ('cat', OneHotEncoder(handle_unknown='ignore'), categorical_cols)\n", + " ]\n", + ")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "X_processed = preprocessor.fit_transform(X)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 6: Write your code here:\n", + "y.value_counts(normalize=True)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "feature_cols = ['Order_ID,\tDistance_km,\tWeather,\tTraffic_Level,\tTime_of_Day,\tVehicle_Type,\tPreparation_Time_min,\tCourier_Experience_yrs,\tDelivery_Time']\n", + "X = df_clean['Delivery_Time']\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", + "import numpy as np\n", + "from sklearn.model_selection import KFold\n", + "from sklearn.ensemble import RandomForestRegressor\n", + "from sklearn.metrics import mean_absolute_error\n", + "\n", + "X = np.array([[1], [2], [3], [4], [5], [6]])\n", + "y = np.array([1.1, 1.9, 3.0, 4.1, 4.9, 6.2])\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[train_idx], X[val_idx]\n", + " y_train, y_val = y[train_idx], y[val_idx]\n", + "\n", + " model = RandomForestRegressor(\n", + " n_estimators=100,\n", + " random_state=42\n", + " )\n", + " model.fit(X_train, y_train)\n", + "\n", + " preds = model.predict(X_val)\n", + " mae = mean_absolute_error(y_val, preds)\n", + " mae_scores.append(mae)\n", + "\n", + "print(f\"Average MAE across folds: {np.mean(mae_scores):.4f}\")\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", + "\n", + "importances = model.feature_importances_\n", + "\n", + "fi = pd.DataFrame({\n", + " \"feature\": X_train.columns,\n", + " \"importance\": importances\n", + "}).sort_values(by=\"importance\", ascending=False)\n", + "\n", + "plt.figure(figsize=(10, 6))\n", + "plt.barh(fi[\"feature\"], fi[\"importance\"])\n", + "plt.gca().invert_yaxis()\n", + "plt.title(\"Feature Importance\")\n", + "plt.xlabel(\"Importance Score\")\n", + "plt.ylabel(\"Feature\")\n", + "plt.tight_layout()\n", + "plt.show()\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "from sklearn.inspection import permutation_importance\n", + "import pandas as pd\n", + "import matplotlib.pyplot as plt\n", + "\n", + "r = permutation_importance(\n", + " model,\n", + " X_train,\n", + " y_train,\n", + " n_repeats=10,\n", + " random_state=42,\n", + " scoring=\"neg_mean_absolute_error\"\n", + ")\n", + "\n", + "fi = pd.DataFrame({\n", + " \"feature\": X_train.columns,\n", + " \"importance\": r.importances_mean\n", + "}).sort_values(by=\"importance\", ascending=False)\n", + "\n", + "plt.figure(figsize=(10, 6))\n", + "plt.barh(fi[\"feature\"], fi[\"importance\"])\n", + "plt.gca().invert_yaxis()\n", + "plt.title(\"Permutation Feature Importance\")\n", + "plt.xlabel(\"Importance\")\n", + "plt.ylabel(\"Feature\")\n", + "plt.tight_layout()\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/258/Q2.ipynb b/submissions_extracted/258/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..ee327a64eea9c5c037194e44ee09004c305a40d1 --- /dev/null +++ b/submissions_extracted/258/Q2.ipynb @@ -0,0 +1,316 @@ +{ + "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", + "import torch\n", + "from torch.utils.data import TensorDataset, DataLoader\n", + "import matplotlib.pyplot as plt\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.long)\n", + "y_test_tensor = torch.tensor(y_test, dtype=torch.long)\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", + "\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", + ")\n", + "\n", + "test_loader = DataLoader(\n", + " test_dataset,\n", + " batch_size=32,\n", + " shuffle=False\n", + ")\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 4. Print shape of one batch\n", + "\n", + "images, labels = next(iter(train_loader))\n", + "\n", + "print(\"Image batch shape:\", images.shape)\n", + "print(\"Label batch shape:\", labels.shape)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 5. Display sample images\n", + "# Display first 6 images in the batch\n", + "fig, axes = plt.subplots(1, 6, figsize=(12, 3))\n", + "\n", + "for i in range(6):\n", + " img = images[i]\n", + "\n", + " # If image has channel dimension, remove it for display\n", + " if img.dim() == 3:\n", + " img = img.squeeze(0)\n", + "\n", + " axes[i].imshow(img, cmap='gray')\n", + " axes[i].set_title(f\"Label: {labels[i].item()}\")\n", + " axes[i].axis('off')\n", + "\n", + "plt.show()\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your model class here:import torch\n", + "class FourLayerNN(nn.Module):\n", + " def __init__(self, input_size, hidden1, hidden2, hidden3, output_size):\n", + " super(FourLayerNN, self).__init__()\n", + " self.layer1 = nn.Linear(input_size, hidden1)\n", + " self.layer2 = nn.Linear(hidden1, hidden2)\n", + " self.layer3 = nn.Linear(hidden2, hidden3)\n", + " self.layer4 = nn.Linear(hidden3, output_size)\n", + " self.relu = nn.ReLU()\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", + " x = self.layer4(x) # Usually no activation on the output for regression\n", + " return x\n", + "\n", + "" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your training loop here:\n", + "def train_loop(model, dataloader, loss_fn, optimizer, device):\n", + " model.train()\n", + " total_loss = 0\n", + " for X, y in dataloader:\n", + " X, y = X.to(device), y.to(device)\n", + "\n", + " optimizer.zero_grad()\n", + " outputs = model(X)\n", + " loss = loss_fn(outputs, y)\n", + " loss.backward()\n", + " optimizer.step()\n", + "\n", + " total_loss += loss.item() * X.size(0) # sum loss over batch\n", + " avg_loss = total_loss / len(dataloader.dataset)\n", + " return avg_loss\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your validation loop here:\n", + "def val_loop(model, dataloader, loss_fn, device):\n", + " model.eval()\n", + " total_loss = 0\n", + " with torch.no_grad():\n", + " for X, y in dataloader:\n", + " X, y = X.to(device), y.to(device)\n", + " outputs = model(X)\n", + " loss = loss_fn(outputs, y)\n", + " total_loss += loss.item() * X.size(0)\n", + " avg_loss = total_loss / len(dataloader.dataset)\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", + "\n", + "input_size = 10 # Example input features\n", + "hidden1 = 64\n", + "hidden2 = 32\n", + "hidden3 = 16\n", + "output_size = 1 # Example output\n", + "\n", + "model = FourLayerNN(input_size, hidden1, hidden2, hidden3, output_size).to(device)\n", + "\n", + "loss_fn = nn.MSELoss() # Mean Squared Error for regression\n", + "optimizer = 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", + "from torch.utils.data import TensorDataset\n", + "X_train = torch.randn(500, input_size)\n", + "y_train = torch.randn(500, output_size)\n", + "X_val = torch.randn(100, input_size)\n", + "y_val = torch.randn(100, output_size)\n", + "\n", + "train_loader = DataLoader(TensorDataset(X_train, y_train), batch_size=32, shuffle=True)\n", + "val_loader = DataLoader(TensorDataset(X_val, y_val), batch_size=32)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "import matplotlib.pyplot as plt\n", + "\n", + "train_loss = [0.9, 0.7, 0.5, 0.4, 0.35]\n", + "val_loss = [1.0, 0.8, 0.6, 0.55, 0.5]\n", + "epochs = range(1, len(train_loss)+1)\n", + "\n", + "plt.figure(figsize=(8,5))\n", + "plt.plot(epochs, train_loss, 'o-', label='Training Loss')\n", + "plt.plot(epochs, val_loss, 's-', label='Validation Loss')\n", + "plt.xlabel('Epochs')\n", + "plt.ylabel('Loss')\n", + "plt.title('Training vs Validation Loss')\n", + "plt.legend()\n", + "plt.grid(True)\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/259/Q1.ipynb b/submissions_extracted/259/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..4d3db146d5617ccc12edc2097db4c4747047c484 --- /dev/null +++ b/submissions_extracted/259/Q1.ipynb @@ -0,0 +1,315 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import os\n", + "import pandas as pd\n", + "import matplotlib.pyplot as plt\n", + "import numpy as np\n", + "from sklearn.preprocessing import OneHotEncoder\n", + "from sklearn.preprocessing import StandardScaler\n", + "from sklearn.preprocessing import LabelEncoder\n", + "from sklearn.linear_model import LogisticRegression\n", + "from sklearn.model_selection import train_test_split, StratifiedKFold, cross_val_score\n", + "from sklearn.metrics import classification_report, confusion_matrix, accuracy_score\n", + "import matplotlib.pyplot as plt\n", + "import seaborn as sns # figs & visualisiton\n", + "import kagglehub\n", + "import os\n", + "from tqdm import tqdm # the loop bar\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": [ + "# 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", + "df = 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: 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", + "#delivery_time distribution\n", + "plt.figure(figsize=(10, 5))\n", + "plt.hist(df_delivery['Delivery_Time'].dropna(), bins=30, edgecolor='black', color='lightBlue')\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_clean = df_delivery.drop(columns=['Order_ID']).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:\n", + "print(\"Missing values:\")\n", + "print(df_delivery.isnull().sum())" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "stat_cols = ['Weather', 'Traffic_Level', 'Time_of_Day', 'Courier_Experience_yrs' ]\n", + "\n", + "df_clean = df_delivery.dropna(subset=stat_cols).copy()\n", + "print(f\"Shape after cleaning: {df_clean.shape}\")\n", + "\n", + "#df_clean['Delivery_Time'] = df_clean['Delivery_Time'].fillna('None')\n", + "df_mean = df.copy()\n", + "df_mean['Delivery_Time'] = df['Delivery_Time'].fillna(df['Delivery_Time'].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)\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", + "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", + "\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\")\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" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "feature_cols = ['Courier_Experience_yrs',\t'Delivery_Time', 'Traffic_Level',\t'Time_of_Day', 'Distance_km' ]\n", + "X = df_clean[feature_cols]\n", + "y = df_clean[df_mean.copy]\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", + "print(f\"Train: {X_train.shape}, Test: {X_test.shape}\")\n", + "print(f\"Delivery time in train in train: {y_train.sum()}, in test: {y_test.sum()}\")\n", + "\n", + "scaler = StandardScaler()\n", + "X_train_scaled = scaler.fit_transform(X_train)\n", + "X_test_scaled = scaler.transform(X_test)\n", + "\n", + "model = LogisticRegression()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:\n", + "#StratifiedKFold\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}\")" + ], + "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:\n", + "cm = confusion_matrix(y_test,y_pred)\n", + "\n", + "plt.figure(figsize=(6, 4))\n", + "plt.imshow(cm, cmap='Pastel1')\n", + "plt.title('Confusion Matrix')\n", + "plt.colorbar()\n", + "plt.xticks([0, 1], ['Delivery time', 'distance'])\n", + "plt.yticks([0, 1], ['Delivery time', 'distance'])\n", + "for i in range(2):\n", + " for j in range(2):\n", + " plt.text(j, i, cm[i, j], ha='center', va='center', color='red')\n", + "plt.ylabel('Actual')\n", + "plt.xlabel('Predicted')\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/259/Q2.ipynb b/submissions_extracted/259/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..9b0041c5145be81f27249cc34ef2bf1fe1d6757d --- /dev/null +++ b/submissions_extracted/259/Q2.ipynb @@ -0,0 +1,450 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "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 #organize dataset\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": [ + "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 #function with the softmax\n", + "import matplotlib.pyplot as plt" + ], + "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) #long has no decimal\n", + "y_test = torch.tensor(y_test, dtype=torch.long)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 2. Create TensorDataset objects\n", + "# Training dataset\n", + "train_dataset = MNIST(\n", + " root='./datasets',\n", + " train=True,\n", + " transform=to_tensor,\n", + " download=True\n", + ")\n", + "\n", + "# Testing dataset\n", + "test_dataset = MNIST(\n", + " root='./datasets',\n", + " train=False,\n", + " transform=to_tensor,\n", + " download=True\n", + ")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 3. Create DataLoaders\n", + "#load for train\n", + "train_loader = DataLoader(\n", + " train_dataset,\n", + " batch_size=32,\n", + " shuffle=True,\n", + " num_workers=2 #how many cores allowed fore the shuffle,,,, best to always use 2,,,,, not very imp\n", + ")\n", + "\n", + "#load for test\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)) #functions to take only one chunck\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", + "\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", + " 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", + " # 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", + " # Second hidden layer\n", + " z3 = self.layer2(a2)\n", + " a3 = self.relu(z3)\n", + "\n", + "\n", + " #we dont use segmoid because the function takes the crossintrupy takes it(notes)\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", + "\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.view(X_batch.size(0), -1).to(device) #only diffrence,, the view here makes it a one layerd input,, its simillar to flatten\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()\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", + "\n", + "def validate(model, criterion, test_loader, device):\n", + "\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", + " X_batch = X_batch.view(X_batch.size(0), -1).to(device)\n", + " y_batch = y_batch.to(device)\n", + "\n", + "\n", + " outputs = model(X_batch)\n", + " loss = criterion(outputs, y_batch)\n", + " running_loss += loss.item()\n", + "\n", + "\n", + " probabilities = F.softmax(outputs, dim=1) #the outputs gives u logits not probabilities, softmax fix them into prob,,, dim=0 takes every column image for each class\n", + "\n", + "\n", + " predicted = torch.argmax(probabilities, dim=1)\n", + "\n", + "\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\n", + "device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n", + "\n", + "# Model\n", + "input_dim = 28 * 28\n", + "hidden_dim = 14\n", + "output_dim = 10\n", + "\n", + "# Instantiate model\n", + "model = NN4Layer(input_dim, hidden_dim, output_dim).to(device) #can say: .to('cuda')\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", + "#Loss\n", + "criterion = nn.CrossEntropyLoss()\n", + "\n", + "#Num of epoch\n", + "num_epochs = 20\n", + "learning_rate = 0.001\n", + "\n", + "#Optemizer\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", + "# 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:\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 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') #squeez or view shape to avoid error\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/259/Q3.ipynb b/submissions_extracted/259/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..411b8ad917d15809a3d202d902a84bdb67296fa5 --- /dev/null +++ b/submissions_extracted/259/Q3.ipynb @@ -0,0 +1,284 @@ +{ + "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", + "\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", + "\n", + "data_path = os.path.join(path, 'Q3_data.csv')\n", + "df_data = pd.read_csv(data_path)\n", + "df = pd.read_csv(data_path)\n", + "print(f\"Dataset shape: {df_data.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\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 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", + "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", + "# NO CATIGORICAL VALUES" + ], + "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\") # 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", + "print(\"Missing values:\")\n", + "print(df_data.isnull().sum())\n", + "#imbalanced" + ], + "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": [ + "# 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 # 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", + "for fold_idx, (train_index, test_index) in enumerate(skf.split(X, y)): #enumarte gives index w/value\n", + " print(f\"\\nFold {fold_idx + 1}/{n_splits}\")\n", + "\n", + " X_train, X_test = X.iloc[train_index], X.iloc[test_index] # gives the machine indexes of objects to use in each fold\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) # if it equalls 0, mark it as a 0 not unknwon\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", + " # 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 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/26/Q1.ipynb b/submissions_extracted/26/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..965e4f96d65851cc63ef886b5d02b7f6600f0622 --- /dev/null +++ b/submissions_extracted/26/Q1.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/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", + "\n", + "df = pd.read_csv(read_csv_path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import pandas as pd\n", + "print(df.head())" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import pandas as pd\n", + "print(df.info())" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "print(df.describe())" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "df.hist(bins=30, figsize=(12, 10))" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import pandas as pd\n", + "print(df.drop('Order_ID', axis=1))" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "\n", + "df.dropna()\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "df.drop_duplicates(subset=None, keep='first', inplace=False)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "from sklearn.preprocessing import OneHotEncoder\n", + "encoder = OneHotEncoder(sparse_output=False)\n", + "df_encoded = encoder.fit_transform(df)\n", + "print(df_encoded)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "from sklearn.preprocessing import StandardScaler\n", + "\n", + "scaler = StandardScaler()\n", + "df_scaled = scaler.fit_transform(df)\n", + "print(df_scaled)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "from sklearn.preprocessing import StandardScaler\n", + "\n", + "scaler = StandardScaler()\n", + "df_scaled = scaler.fit_transform(df)\n", + "print(df_scaled)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "from sklearn.model_selection import train_test_split, KFold, StratifiedKFold\n", + "split = StratifiedKFold(n_splits=10, shuffle=True, random_state=42)\n", + "x = np.array(df.drop('delivery_time', axis=1))\n", + "y = np.array(df['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:" + ], + "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/26/Q2.ipynb b/submissions_extracted/26/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..32f854d388d080e35d9fa56884c05450e929522f --- /dev/null +++ b/submissions_extracted/26/Q2.ipynb @@ -0,0 +1,197 @@ +{ + "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": [ + "\n", + "import torch\n", + "import numpy as np\n", + "\n", + "x_train = torch.tensor(X_train, dtype=torch.float32)\n", + "y_train = torch.tensor(y_train, dtype=torch.float32)\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "from torch.utils.data import TensorDataset\n", + "train_dataset = TensorDataset(x_train, y_train)\n", + "test_dataset = TensorDataset(x_train, y_train)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "from torch.utils.data import TensorDataset\n", + "train_loader = TensorDataset(x_train, y_train)\n", + "test_loader = TensorDataset(x_train, y_train)\n", + "\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "print()\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/260/Q1.ipynb b/submissions_extracted/260/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..43e3ef25a303a478adeb3b9377cfffc4a2159fc5 --- /dev/null +++ b/submissions_extracted/260/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": [ + "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", + "# plot\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": [ + "# Task1 : drop order id\n", + "df.columns.drop(\"Order_ID\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here: 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": [ + "# drop mising values :\n", + "\n", + "df.dropna(subset=['Weather'])\n", + "df.dropna(subset=['Delivery_Time']) # target value\n", + "df.dropna(subset=['Traffic_Level'])\n", + "df.dropna(subset=['Courier_Experience_yrs'])\n", + "df.dropna(subset=['Time_of_Day'])\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here: remove duplicate\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": [ + "from sklearn.preprocessing import StandardScaler, LabelEncoder , OneHotEncoder" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here: encode categorical : Weather\tTraffic_Level\tTime_of_Day\tVehicle_Type\n", + "\n", + "# first find them\n", + "\n", + "categorical_cols = df.select_dtypes(include=[\"object\"]).columns\n", + "\n", + "print(\"Categorical Columns:\", list(categorical_cols))\n", + "\n", + "# 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", + " 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: Apply feature scaling for all features (Use StandardScaler)\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\n" + ], + "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", + "\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 5: Write your code here:\n", + "# plot\n", + "df[\"Delivery_Time\"].hist(bins=30, edgecolor='black')\n", + "\n", + "plt.xlabel(\"Delivery_Time\")\n", + "plt.ylabel(\"Frequency\")\n", + "plt.grid(False)\n", + "\n", + "plt.show()\n", + "\n" + ], + "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": [ + "# Task 1: Write your code here:\n", + "# first define the x , y\n", + "\n", + "# Define features (X) and target (y)\n", + "feature_cols = ['Distance_km', 'Weather', 'Traffic_Level', 'Time_of_Day',\n", + " 'Vehicle_Type', 'Preparation_Time_min', 'Courier_Experience_yrs']\n", + "X = df[feature_cols]\n", + "y = df['Delivery_Time']\n", + "\n", + "#split into train and test\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" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:\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, y_train)\n", + "print(\"Model trained!\")\n", + "\n", + "#evlauate\n", + "y_pred = model.predict(X_test)\n", + "\n", + "mae = mean_absolute_error(y_test, y_pred)\n", + "\n", + "\n", + "print(f\"MAE: ${mae:,.2f}\")\n", + "\n", + "#print\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()\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/260/Q3.ipynb b/submissions_extracted/260/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..78825a78e79741d18f2a470a74bf90ae908d05e8 --- /dev/null +++ b/submissions_extracted/260/Q3.ipynb @@ -0,0 +1,344 @@ +{ + "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 os\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here: read\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: handel missing\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" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here: duplicate\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: encode\n", + "\n", + "#first list the categorical column\n", + "\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: scale\n", + "from sklearn.preprocessing import MinMaxScaler\n", + "\n", + "features = df.columns.drop(\"Target\") # 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": [ + "# Task 5: Write your code here: imblance" + ], + "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 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" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "from sklearn.model_selection import StratifiedKFold" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:\n", + "\n", + "# 2 split using StratifiedKFold\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", + "# model :\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", + "# eval\n", + "\n", + "\n", + "lr_accuracy = []\n", + "\n", + "\n", + "lr_f1 = []" + ], + "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]\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_accuracy.append(accuracy)\n", + " lr_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", + "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:" + ], + "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/261/Q1.ipynb b/submissions_extracted/261/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..d164bfa76582f9d924086fce283e9fbc3529cae7 --- /dev/null +++ b/submissions_extracted/261/Q1.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/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", + "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, 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": [ + "# Task 1: Write your code here:\n", + "\n", + "path2= os.path.join(path, 'Q1_data.csv')\n", + "df_food = pd.read_csv(path2)\n", + "\n", + "print(f\"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()\n", + "cat=['Weather','Traffic_Level','Time_of_Day','Vehicle_Type']" + ], + "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:حرجع اتفاهم done\n", + "#plt.figure(figsize=(10000, 500))\n", + "#plt.hist(df_food['delivery_time'].dropna(), bins=50, edgecolor='black')\n", + "#plt.title('delivery_time')\n", + "#plt.xlabel('Price')\n", + "#plt.ylabel('Frequency')\n", + "#plt.show()\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_clean = df_food.copy()\n", + "df_clean = df_clean.drop(columns='Order_ID')\n", + "\n", + "\n", + "c=['Weather','Traffic_Level','Time_of_Day','Courier_Experience_yrs']" + ], + "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)\n", + "c=['Weather','Traffic_Level','Time_of_Day','Courier_Experience_yrs']\n", + "for i in c:\n", + " df_clean[i]=df_clean[i].fillna(df_clean[i].mean())\n", + "\n", + "\n", + "\n", + "df_clean=df_clean.dropna(subset=[\"Delivery_Time\"])" + ], + "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 = ['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", + "df_clean.info()" + ], + "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\"]) # DON'T SCALE THE TARGET\n", + "numerical_cols=['Distance_km','Distance_km','Traffic_Level','Time_of_Day','Vehicle_Type','Preparation_Time_min',\n", + " 'Courier_Experience_yrs']\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", + "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": [ + "# the target clear imbalance" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "df=df_clean\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", + "from sklearn.tree import DecisionTreeRegressor\n", + "from sklearn.ensemble import RandomForestRegressor\n", + "\n", + "from sklearn.model_selection import KFold\n", + "from sklearn.metrics import mean_squared_error as sklearn_mse, mean_absolute_error, r2_score\n", + "def gradient_descent(X, y, learning_rate, n_iters=500):#########مافهمتها 1\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", + "def mean_squared_error(y, y_hat):\n", + " return (1 / (2 * len(y))) * np.sum((y_hat - y) ** 2)\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_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", + " # 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", + "\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", + "import pandas as pd\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", + "m = confusion_matrix(y_test, y_pred)\n", + "\n", + "plt.figure(figsize=(6, 4))\n", + "plt.imshow(cm, cmap='Blues')\n", + "plt.title('Confusion Matrix')\n", + "plt.colorbar()\n", + "plt.xticks([0, 1], ['Normal', 'Legendary'])\n", + "plt.yticks([0, 1], ['Normal', 'Legendary'])\n", + "for i in range(2):\n", + " for j in range(2):\n", + " plt.text(j, i, cm[i, j], ha='center', va='center', color='red')\n", + "plt.ylabel('Actual')\n", + "plt.xlabel('Predicted')\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/261/Q2.ipynb b/submissions_extracted/261/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..3945789a47f1260a975561d926fa4914f7b976f1 --- /dev/null +++ b/submissions_extracted/261/Q2.ipynb @@ -0,0 +1,375 @@ +{ + "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", + "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", + "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", + "\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", + "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", + "\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", + "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))\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\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}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Start training for 20 epochs:\n", + "from torch.optim import AdamW\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", + "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", + "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/261/Q3.ipynb b/submissions_extracted/261/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..29ff6cc0f126909310a758179714807ff50cbdcb --- /dev/null +++ b/submissions_extracted/261/Q3.ipynb @@ -0,0 +1,295 @@ +{ + "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", + "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", + "\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", + "path2= os.path.join(path, 'Q3_data.csv')\n", + "df_q3 = pd.read_csv(path2)\n", + "\n", + "print(f\"Shape: {df_q3.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "df_q3.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "df_q3.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "df_q3.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "df_clean = df_q3.copy()\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_clean)\n", + "\n", + "df_clean=df_clean.dropna(subset=[\"Target\"])\n", + "c=df_clean.select_dtypes(include=[\"int64\", \"float64\"])\n", + "\n", + "\n", + "\n", + "print(c)\n", + "for i in c:\n", + " df_clean[i]=df_clean[i].fillna(df_clean[i].mean())\n", + "\n" + ], + "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", + "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", + "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))\n", + "\n", + "df_clean.head()\n" + ], + "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\"]) # 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", + "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, \"Target\")\n", + "\n", + "\n", + "# the target clear imbalance" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "df=df_clean\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_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", + "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", + " 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 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/262/Q1.ipynb b/submissions_extracted/262/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..f91a9ff6301ea91e1828ce0cb7e0dbd8ff3b480d --- /dev/null +++ b/submissions_extracted/262/Q1.ipynb @@ -0,0 +1,262 @@ +{ + "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, 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", + "# 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", + "plt.hist('delivery_time')" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "X = df_q1.drop('Order_ID', axis=1)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "print(\"Missing values:\")\n", + "print(df_q1.isnull().sum())\n", + "\n", + "\n", + "print(f\"Before: {df_q1.shape}\")\n", + "stat_cols = ['Weather', 'Traffic_Level', 'Time_of_Day', 'Courier_Experience_yrs', 'Delivery_Time']\n", + "df_q1 = df_q1.dropna(subset=stat_cols).copy()\n", + "print(f\"After dropping: {df_q1.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "def check_duplicates(df_q1):\n", + " duplicates = df_q1.duplicated().sum()\n", + " print(f\"Number of Duplicate Samples: {duplicates}\")\n", + " if duplicates > 0:\n", + " print(\"Dropping Duplicates...\")\n", + " df_q1.drop_duplicates(inplace=True)\n", + " print(\"Duplicates Dropped.\")\n", + " else:\n", + " print(\"No Duplicate Samples Found.\")\n", + "\n", + "check_duplicates(df_q1)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "from sklearn.preprocessing import OneHotEncoder\n", + "\n", + "print('data before encoding:\\n', df_q1)\n", + "\n", + "onehot_encoder = OneHotEncoder(sparse_output=False)\n", + "data_onehot_encoded = onehot_encoder.fit_transform(df_q1)\n", + "\n", + "print('\\nData after encoding:\\n', 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", + "scaler = StandardScaler()\n", + "data_onehot_encoded = scaler.fit_transform(data_onehot_encoded)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 6: Write your code here:\n", + "def check_target_imbalance(df_q1, target_column):\n", + " print(\"Target Distribution:\")\n", + "\n", + " df_q1[target_column].hist()\n", + " plt.show()\n", + "\n", + "check_target_imbalance(df_q1, 'Delivery_Time')\n", + "\n", + "\n", + "# Not imbalanced." + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "X = df_q1.drop(\"Delivery_Time\",axis=1)\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 train_test_split, StratifiedKFold, cross_val_score\n", + "from sklearn.ensemble import RandomForestClassifier\n", + "from sklearn.metrics import mean_absolute_error\n", + "\n", + "\n", + "n_splits = 5\n", + "skf = StratifiedKFold(n_splits=n_splits, shuffle=True, random_state=42)\n", + "model = RandomForestClassifier(n_estimators=200, max_depth=10)\n", + "\n", + "baseline_pred = df_q1['Delivery_Time'].median()\n", + "baseline_mae = mean_absolute_error(df_q1['Delivery_Time'], [baseline_pred] * len(df_q1))\n", + "print(f\"Baseline MAE: {baseline_mae:.4f}\")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "feature_importance = pd.DataFrame({\n", + " 'feature': features,\n", + " 'importance': 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, 6))\n", + "plt.hist(data['Delivery_Time'], bins=60, edgecolor='black')\n", + "plt.xlabel('Distance_km')\n", + "plt.ylabel('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/262/Q2.ipynb b/submissions_extracted/262/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..481f87a6ed90492d3bf2897c6a12f68ea1aea746 --- /dev/null +++ b/submissions_extracted/262/Q2.ipynb @@ -0,0 +1,340 @@ +{ + "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 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", + "\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_tensor = torch.tensor(X_train, dtype=torch.float32)\n", + "y_train_tensor = torch.tensor(y_train, dtype=torch.float32)\n", + "X_test_tensor = torch.tensor(X_test, 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", + "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", + "train_loader = DataLoader(train_dataset, batch_size=64, shuffle=True)\n", + "test_loader = DataLoader(test_dataset, batch_size=64, shuffle=False)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 4. Print shape of one batch\n", + "images, labels = next(iter(train_loader))" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 5. Display sample images\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, output_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", + " 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", + " 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", + " 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", + " # 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).long()\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" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Define device, model, loss, optimizer:\n", + "input_dim = 3888\n", + "hidden_dim = 512\n", + "output_dim = 10\n", + "\n", + "device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n", + "model = NN4Layer(input_dim, hidden_dim, output_dim).to(device)\n", + "\n", + "num_epochs = 20\n", + "learning_rate = 0.001\n", + "criterion = nn.MSELoss()\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}')\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", + "\n", + "\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" + ], + "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/262/Q3.ipynb b/submissions_extracted/262/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..7f4109f3084938799e4e62bfeba429c4699858ac --- /dev/null +++ b/submissions_extracted/262/Q3.ipynb @@ -0,0 +1,215 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "dqimport kagglehub\n", + "import os\n", + "import pandas as pd\n", + "\n", + "\n", + "\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": [ + "# Task 1: Write your code here:\n", + "q3_path = os.path.join(path, 'Q3_data.csv')\n", + "df_q3 = pd.read_csv(q3_path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "df_q3.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "df_q3.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "df_q3.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "print(\"Missing values:\")\n", + "print(df_q3.isnull().sum())" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "def check_duplicates(df_q3):\n", + " duplicates = df_q3.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)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "from sklearn.preprocessing import LabelEncoder\n", + "\n", + "print('data before encoding:\\n', df_q3)\n", + "\n", + "label_encoder = LabelEncoder()\n", + "data_label_encoded = label_encoder.fit_transform(df_q3)\n", + "\n", + "print('\\nData after encoding:\\n', data_label_encoded)" + ], + "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", + "data_onehot_encoded = scaler.fit_transform(data_label_encoded)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "def check_target_imbalance(df_q3, target_column):\n", + " print(\"Target Distribution:\")\n", + "\n", + " df_q3[target_column].hist()\n", + " plt.show()\n", + "\n", + "check_target_imbalance(df_q3, 'P_2')" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "X = df_q1.drop(\"P_2\",axis=1)\n", + "y = df_q1['P_2']" + ], + "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, StratifiedKFold, cross_val_score\n", + "from catboost import CatBoostClassifier\n", + "cat = CatBoostClassifier(\n", + " verbose=0,\n", + " n_estimators=200,\n", + " max_depth=4)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "import matplotlib.pyplot as plt\n", + "\n", + "feature_importance = pd.DataFrame({\n", + " 'feature': features,\n", + " 'importance': 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/263/Q1.ipynb b/submissions_extracted/263/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..6bf5c1a754cfda573ddc5d1362ce5cf77cab5c77 --- /dev/null +++ b/submissions_extracted/263/Q1.ipynb @@ -0,0 +1,292 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "import pandas as pd\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", + "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", + "# 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": [ + "# Task d1: 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()\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()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "plt.plot(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", + "df.isnull().sum()\n", + "cols = ['Weather', 'Traffic_Level', 'Time_of_Day',\"Courier_Experience_yrs\", 'Distance_km', 'Vehicle_Type',\"Preparation_Time_min\",\"Delivery_Time\"]\n", + "df_clean = df[cols].copy()\n", + "df_clean = df_clean.dropna(subset=['Weather', 'Traffic_Level', 'Time_of_Day',\"Courier_Experience_yrs\"])" + ], + "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", + "check_duplicates(df_clean)\n", + "df.drop_duplicates(inplace=True)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "from sklearn.preprocessing import OneHotEncoder, LabelEncoder,StandardScaler" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "df_clean" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "lb = LabelEncoder()\n", + "col =['Weather','Traffic_Level','Time_of_Day','Vehicle_Type']\n", + "df_clean['Weather'] = lb.fit_transform(df_clean['Weather'])\n", + "df_clean['Traffic_Level'] = lb.fit_transform(df_clean['Traffic_Level'])\n", + "df_clean['Time_of_Day'] = lb.fit_transform(df_clean['Time_of_Day'])\n", + "df_clean['Vehicle_Type'] = lb.fit_transform(df_clean['Vehicle_Type'])\n", + "df" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "scaler = StandardScaler()\n", + "\n", + "df_clean = scaler.fit_transform(df_clean.drop(columns='Delivery_Time'))\n", + "df_clean.shape" + ], + "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", + "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[0:len(df_clean),:-1]\n", + "y = df_clean[:,0:len(df_clean)-1]\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n", + "X_train = X_train.astype(\"float32\")\n", + "X_test = X_test.astype(\"float32\")\n", + "y_train = y_train.astype(\"float32\")\n", + "y_test = y_test.astype(\"float32\")" + ], + "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", + "model = RandomForestRegressor()\n", + "\n", + "kfold = KFold(n_splits=5, shuffle=True, random_state=42)\n", + "\n", + "mae_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[train_idx], y_train[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)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "plt.plot(model.feature_importances_)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "feature_importance = pd.DataFrame({\n", + " 'feature': model.feature_importances_,\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.plot(model.predict(X_test))" + ], + "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/263/Q2.ipynb b/submissions_extracted/263/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..42cda240c32893057a607220eb219855cf6327a2 --- /dev/null +++ b/submissions_extracted/263/Q2.ipynb @@ -0,0 +1,220 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "import matplotlib.pyplot as plt\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 torch.utils.data import DataLoader, TensorDataset" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 1. Convert Numpy arrays to PyTorch Tensors\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)" + ], + "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 batc\n", + "X_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", + "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:" + ], + "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/263/Q3.ipynb b/submissions_extracted/263/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..6aa4f1f4509900e1fd13d7e5ed976d5cabe669c5 --- /dev/null +++ b/submissions_extracted/263/Q3.ipynb @@ -0,0 +1,199 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\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", + "# 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", + "cars_path = os.path.join(path, 'Q3_data.csv')\n", + "df = pd.read_csv(cars_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", + "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", + "check_duplicates(df)\n", + "# df.drop_duplicates(inplace=True)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "# no need" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "s = StandardScaler()\n", + "df = s.fit_transform(df.drop(columns=\"Target\"))\n", + "df" + ], + "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", + "check_target_imbalance(df,'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/264/Q1.ipynb b/submissions_extracted/264/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..ffafb7ed846406385385f535349c6df88955acc7 --- /dev/null +++ b/submissions_extracted/264/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": [ + "# Task 1: Write your code here:\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": [ + "# Task 2: Write your code here:\n", + " #1. Read the dataset\n", + "# Build the full CSV path\n", + "csv_path = os.path.join(path, \"Q1_data.csv\")\n", + "\n", + "df = pd.read_csv(csv_path)\n", + "df.head()\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "\n", + "# Task 3: Write your code here:\n", + "df.info()\n", + "\n", + "\n", + "\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 5: Write your code here:\n", + "plt.figure(figsize=(8, 5))\n", + "sns.histplot(df[\"Delivery_Time\"], bins=30, kde=True)\n", + "plt.xlabel(\"Delivery Time (minutes)\")\n", + "plt.ylabel(\"Frequency\")\n", + "plt.title(\"Distribution of Delivery Time\")\n", + "plt.show()\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "\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 df.isnull().sum()\n", + "df.isnull().sum()\n", + "# Identify numeric and categorical columns\n", + "numeric_cols = df.select_dtypes(include=[\"int64\", \"float64\"]).columns\n", + "categorical_cols = df.select_dtypes(include=[\"object\"]).columns\n", + "\n", + "# Fill numeric missing values with median\n", + "df[numeric_cols] = df[numeric_cols].fillna(df[numeric_cols].median())\n", + "\n", + "# Fill categorical missing values with mode\n", + "for col in categorical_cols:\n", + " df[col] = df[col].fillna(df[col].mode()[0])\n", + "\n", + "df.isnull().sum()\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "# Check duplicates\n", + "print(\"Duplicates before:\", df.duplicated().sum())\n", + "\n", + "# Remove duplicates\n", + "df = df.drop_duplicates()\n", + "\n", + "print(\"Duplicates after:\", df.duplicated().sum())\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "# One Hot Encode categorical columns\n", + "df_encoded = pd.get_dummies(df, columns=categorical_cols, drop_first=True)\n", + "\n", + "df_encoded.head()\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "from sklearn.preprocessing import StandardScaler\n", + "\n", + "# 1. Identify the target column\n", + "target_col = \"Delivery_Time\"\n", + "\n", + "# 2. Separate features and target\n", + "X = df.drop(columns=[target_col])\n", + "y = df[target_col]\n", + "\n", + "# 3. One-Hot Encode categorical columns\n", + "categorical_cols = X.select_dtypes(include=[\"object\"]).columns\n", + "X = pd.get_dummies(X, columns=categorical_cols, drop_first=True)\n", + "\n", + "# 4. Apply StandardScaler to numeric features\n", + "scaler = StandardScaler()\n", + "X_scaled = scaler.fit_transform(X)\n", + "\n", + "X_scaled[:5]\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 6: Write your code here:\n", + "# Plot to visually inspect imbalance\n", + "sns.histplot(y, kde=True)\n", + "plt.show()\n", + "\n", + "# If the distribution looks continuous (which it does),\n", + "# the target is NOT imbalanced.\n" + ], + "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", + "import numpy as np\n", + "\n", + "# Features and target\n", + "X = X_scaled # from previous scaling step\n", + "y = y # Delivery_Time\n" + ], + "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", + "mae_scores = []\n", + "\n", + "for train_index, test_index in kf.split(X):\n", + " X_train, X_test = X[train_index], X[test_index]\n", + " y_train, y_test = y.iloc[train_index], y.iloc[test_index]\n", + "\n", + " model = RandomForestRegressor(random_state=42)\n", + " model.fit(X_train, y_train)\n", + "\n", + " preds = model.predict(X_test)\n", + " mae = mean_absolute_error(y_test, preds)\n", + " mae_scores.append(mae)\n", + "\n", + "print(\"MAE scores for each fold:\", mae_scores)\n", + "print(\"Average MAE:\", np.mean(mae_scores))\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Train final model on scaled features\n", + "final_model = RandomForestRegressor(random_state=42)\n", + "final_model.fit(X_scaled, y)\n", + "\n", + "# Use the original DataFrame to get feature names\n", + "feature_names = X.columns\n", + "importances = final_model.feature_importances_\n", + "\n", + "plt.figure(figsize=(10,6))\n", + "sns.barplot(x=importances, y=feature_names)\n", + "plt.title(\"Feature Importance\")\n", + "plt.xlabel(\"Importance Score\")\n", + "plt.ylabel(\"Feature\")\n", + "plt.show()\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "y_pred = final_model.predict(X_scaled)\n", + "\n", + "plt.figure(figsize=(8,5))\n", + "sns.histplot(y_pred, kde=True, bins=30)\n", + "plt.title(\"Predicted Delivery Time Distribution\")\n", + "plt.xlabel(\"Predicted Delivery Time (minutes)\")\n", + "plt.ylabel(\"Frequency\")\n", + "plt.show()\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "!pip install catboost\n", + "from catboost import CatBoostRegressor\n", + "\n", + "# 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", + "\n", + "mae_scores = []\n", + "\n", + "for train_idx, test_idx in kf.split(X_scaled):\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", + " # Model 1: Random Forest\n", + " rf = RandomForestRegressor(random_state=42)\n", + " rf.fit(X_train, y_train)\n", + " rf_pred = rf.predict(X_test)\n", + "\n", + " # Model 2: CatBoost\n", + " cb = CatBoostRegressor(verbose=0, random_state=42)\n", + " cb.fit(X_train, y_train)\n", + " cb_pred = cb.predict(X_test)\n", + "\n", + " # Average predictions\n", + " avg_pred = (rf_pred + cb_pred) / 2\n", + "\n", + " # MAE on averaged predictions\n", + " mae = mean_absolute_error(y_test, avg_pred)\n", + " mae_scores.append(mae)\n", + "\n", + "# Print results\n", + "print(\"MAE scores for each fold:\", mae_scores)\n", + "print(\"Average MAE:\", 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/264/Q2.ipynb b/submissions_extracted/264/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..53f91d820ccfb09076ad419f9a172af9824b49f9 --- /dev/null +++ b/submissions_extracted/264/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", + "\n", + "import torch\n", + "\n", + "X_train_tensor = torch.tensor(X_train, dtype=torch.float32)\n", + "X_test_tensor = torch.tensor(X_test, dtype=torch.float32)\n", + "\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", + "from torch.utils.data import TensorDataset\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", + "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" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 4. Print shape of one batch\n", + "\n", + "images, labels = next(iter(train_loader))\n", + "print(\"Image batch shape:\", images.shape)\n", + "print(\"Label batch shape:\", labels.shape)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 5. Display sample images\n", + "\n", + "import matplotlib.pyplot as plt\n", + "\n", + "# Convert first 6 images back to HWC format for plotting\n", + "plt.figure(figsize=(10, 6))\n", + "\n", + "for i in range(6):\n", + " img = images[i].permute(1, 2, 0).numpy() # C,H,W → H,W,C\n", + " plt.subplot(2, 3, i+1)\n", + " plt.imshow(img)\n", + " plt.title(f\"Age: {labels[i].item():.0f}\")\n", + " plt.axis(\"off\")\n", + "\n", + "plt.show()\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your model class here:\n", + "\n", + "class AgeRegressor(nn.Module):\n", + " def __init__(self, input_dim):\n", + " super(AgeRegressor, self).__init__()\n", + "\n", + " self.fc1 = nn.Linear(input_dim, 512)\n", + " self.fc2 = nn.Linear(512, 256)\n", + " self.fc3 = nn.Linear(256, 128)\n", + " self.fc4 = nn.Linear(128, 1)\n", + "\n", + " def forward(self, x):\n", + " x = x.view(x.size(0), -1)\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" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your training loop here:\n", + "def train_one_epoch(model, loader, loss_fn, optimizer, device):\n", + " model.train()\n", + " total_loss = 0\n", + "\n", + " for images, labels in loader:\n", + " images, labels = images.to(device), labels.to(device)\n", + "\n", + " optimizer.zero_grad()\n", + " outputs = model(images).squeeze()\n", + " loss = loss_fn(outputs, labels)\n", + " loss.backward()\n", + " optimizer.step()\n", + "\n", + " total_loss += loss.item()\n", + "\n", + " return total_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, loss_fn, device):\n", + " model.eval()\n", + " total_loss = 0\n", + "\n", + " with torch.no_grad():\n", + " for images, labels in loader:\n", + " images, labels = images.to(device), labels.to(device)\n", + "\n", + " outputs = model(images).squeeze()\n", + " loss = loss_fn(outputs, labels)\n", + " total_loss += loss.item()\n", + "\n", + " return total_loss / len(loader)\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n", + "\n", + "# Determine input dimension automatically\n", + "sample_batch, _ = next(iter(train_loader))\n", + "input_dim = sample_batch.view(sample_batch.size(0), -1).shape[1]\n", + "\n", + "model = AgeRegressor(input_dim).to(device)\n", + "\n", + "loss_fn = nn.MSELoss()\n", + "optimizer = torch.optim.Adam(model.parameters(), lr=1e-4)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Train for 20 epochs and track losses\n", + "#x = F.relu(self)\n", + "\n", + "train_losses = []\n", + "val_losses = []\n", + "\n", + "epochs = 20\n", + "\n", + "for epoch in range(epochs):\n", + " train_loss = train_one_epoch(model, train_loader, loss_fn, optimizer, device)\n", + " val_loss = validate(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}\")\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.figure(figsize=(10,6))\n", + "plt.plot(train_losses, label=\"Training Loss\", marker='o')\n", + "plt.plot(val_losses, label=\"Validation Loss\", marker='o')\n", + "plt.title(\"Training vs Validation Loss Over Epochs\")\n", + "plt.xlabel(\"Epoch\")\n", + "plt.ylabel(\"Loss\")\n", + "plt.legend()\n", + "plt.grid(True)\n", + "plt.show()\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2 (Bonus): Write your code here:\n", + "import matplotlib.pyplot as plt\n", + "import torch\n", + "\n", + "model.eval()\n", + "\n", + "images, labels = next(iter(test_loader))\n", + "images, labels = images.to(device), labels.to(device)\n", + "\n", + "with torch.no_grad():\n", + " preds = model(images).squeeze()\n", + "\n", + "# Move to CPU for plotting\n", + "images = images.cpu()\n", + "labels = labels.cpu()\n", + "preds = preds.cpu()\n", + "\n", + "plt.figure(figsize=(12, 8))\n", + "\n", + "for i in range(6):\n", + " img = images[i].permute(1, 2, 0).numpy() # C,H,W → H,W,C\n", + " plt.subplot(2, 3, i+1)\n", + " plt.imshow(img)\n", + " plt.title(f\"Pred: {preds[i].item():.1f} | Actual: {labels[i].item():.1f}\")\n", + " plt.axis(\"off\")\n", + "\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/264/Q3.ipynb b/submissions_extracted/264/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..273b0bd757cb1ce5400e7a1593c4ab6f03cd4f6c --- /dev/null +++ b/submissions_extracted/264/Q3.ipynb @@ -0,0 +1,289 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "import os\n", + "import pandas as pd\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", + "# Build the full CSV path\n", + "csv_path = os.path.join(path, \"Q3_data.csv\")\n", + "\n", + "df = pd.read_csv(csv_path)\n", + "df.head()\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "\n", + "# 2. Inspect the first few rows\n", + "print(\"HEAD:\")\n", + "display(df.head())\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "# 3. Display dataset information\n", + "print(\"\\nINFO:\")\n", + "df.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "# 4. Statistical description\n", + "print(\"\\nDESCRIBE:\")\n", + "display(df.describe())" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "# Check how many missing values exist in each column df.isnull().sum()\n", + "df.isnull().sum()\n", + "df = df.fillna(df.median(numeric_only=True))" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "duplicates = df.duplicated().sum()\n", + "print(\"Number of duplicate rows:\", duplicates)\n", + "df = df.drop_duplicates()\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "# Identify categorical columns\n", + "cat_cols = df.select_dtypes(include=['object']).columns\n", + "print(\"Categorical columns:\", cat_cols)\n", + "\n", + "# Apply one-hot encoding if categorical columns exist\n", + "if len(cat_cols) > 0:\n", + " df = pd.get_dummies(df, columns=cat_cols, drop_first=True)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "from sklearn.preprocessing import StandardScaler\n", + "\n", + "# Separate features and target\n", + "X = df.drop(columns='Target')\n", + "y = df['Target']\n", + "\n", + "# Apply StandardScaler to numerical features\n", + "scaler = StandardScaler()\n", + "X_scaled = scaler.fit_transform(X)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "print(\"Target distribution (percentage):\")\n", + "print(y.value_counts(normalize=True))\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "\n", + "X = df.drop(columns=\"Target\") # all features\n", + "y = df[\"Target\"] # target column\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:\n", + "!pip install catboost\n", + "\n", + "# Split features and target\n", + "X = df.drop(columns=\"Target\")\n", + "y = df[\"Target\"]\n", + "\n", + "# Use StratifiedKFold\n", + "from sklearn.model_selection import StratifiedKFold\n", + "skf = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)\n", + "\n", + "from catboost import CatBoostClassifier\n", + "from sklearn.metrics import f1_score\n", + "import numpy as np\n", + "\n", + "f1_scores = []\n", + "\n", + "for train_index, test_index in skf.split(X, y):\n", + "\n", + " X_train, X_test = X.iloc[train_index], X.iloc[test_index]\n", + " y_train, y_test = y.iloc[train_index], y.iloc[test_index]\n", + "\n", + " model = CatBoostClassifier(verbose=0, random_state=42)\n", + " model.fit(X_train, y_train)\n", + "\n", + " y_pred = model.predict(X_test)\n", + "\n", + " f1 = f1_score(y_test, y_pred)\n", + " f1_scores.append(f1)\n", + "\n", + "print(\"Average F1 Score across folds:\", np.mean(f1_scores))\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "# Plot Feature Importance\n", + "\n", + "import matplotlib.pyplot as plt\n", + "import numpy as np\n", + "\n", + "# Get feature importance values from the last trained model\n", + "importances = model.get_feature_importance()\n", + "feature_names = X.columns\n", + "\n", + "# Sort features by importance\n", + "sorted_idx = np.argsort(importances)[::-1]\n", + "\n", + "plt.figure(figsize=(10, 6))\n", + "plt.barh(feature_names[sorted_idx][:20], importances[sorted_idx][:20])\n", + "plt.gca().invert_yaxis()\n", + "plt.title(\"Top 20 Most Important Features (CatBoost)\")\n", + "plt.xlabel(\"Importance Score\")\n", + "plt.show()\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "# Identify the Golden Feature\n", + "\n", + "# Find index of the most important feature\n", + "golden_idx = np.argmax(importances)\n", + "\n", + "# Print the name of the golden feature\n", + "golden_feature = feature_names[golden_idx]\n", + "print(\"The Golden Feature is:\", golden_feature)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:\n", + "# Create X using only the golden feature\n", + "X_golden = df[[golden_feature]]\n", + "y = df[\"Target\"]\n", + "\n", + " # Use StratifiedKFold again\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", + "skf = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)\n", + "\n", + "golden_f1_scores = []\n", + "\n", + "# Cross-validation loop using only the golden feature\n", + "for train_index, test_index in skf.split(X_golden, y):\n", + "\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", + " model_golden = CatBoostClassifier(verbose=0, random_state=42)\n", + " model_golden.fit(X_train, y_train)\n", + "\n", + " y_pred = model_golden.predict(X_test)\n", + "\n", + " f1 = f1_score(y_test, y_pred)\n", + " golden_f1_scores.append(f1)\n", + "\n", + "# Print comparison\n", + "print(\"Average F1 Score (Full Model):\", np.mean(f1_scores))\n", + "print(\"Average F1 Score (Golden Feature Only):\", np.mean(golden_f1_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/265/Q1.ipynb b/submissions_extracted/265/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..ab7662df181f5307ec8ee8ac022f14010c65f363 --- /dev/null +++ b/submissions_extracted/265/Q1.ipynb @@ -0,0 +1,273 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "from sklearn.preprocessing import StandardScaler, LabelEncoder\n", + "from sklearn.model_selection import train_test_split, KFold\n", + "import seaborn as sns\n", + "from sklearn.preprocessing import MinMaxScaler\n", + "from sklearn.model_selection import KFold\n", + "from sklearn.metrics import mean_absolute_error\n", + "from sklearn.ensemble import RandomForestRegressor\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", + "import numpy as np\n", + "import pandas as pd\n", + "import matplotlib.pyplot as plt\n", + "import os\n", + "import kagglehub\n", + "path = os.path.join(path, 'Q1_data.csv')\n", + "df_exam = pd.read_csv(path)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "df_exam.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "df_exam.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "df_exam.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 Distro')\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_exam\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "for col in ['Weather', 'Traffic_Level', 'Time_of_Day']:\n", + " df_exam[col] = df_exam[col].fillna('unknown')\n", + "\n", + "for num_col in ['Courier_Experience_yrs', 'Delivery_Time']:\n", + " df_exam[num_col]=df_exam[num_col].fillna(df_exam[num_col].mean())\n", + "\n", + "print(\"Missing values remaining:\", df_exam.isnull().sum().sum())\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "def check_duplicates(df_exam):\n", + " duplicates = df_exam.duplicated().sum()\n", + " print(f\"Number of Duplicate Samples: {duplicates}\")\n", + " if duplicates > 0:\n", + " print(\"Dropping Duplicates...\")\n", + " df_exam.drop_duplicates(inplace=True)\n", + " print(\"Duplicates Dropped.\")\n", + " else:\n", + " print(\"No Duplicate Samples Found.\")\n", + "\n", + "check_duplicates(df_exam)" + ], + "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_exam[col] = le.fit_transform(df_exam[col].astype(str))\n", + "\n", + "df_exam.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "X = df_exam.drop(\"Delivery_Time\", axis=1).astype(float)\n", + "y = df_exam['Delivery_Time'].astype(float)\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\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", + "\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" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 6: Write your code here:\n", + "def check_target_imbalance(df_exam, target_column):\n", + " print(\"Target Distribution:\")\n", + " print(df_exam[target_column].value_counts(normalize=True))\n", + " sns.countplot(x=df_exam[target_column])\n", + " plt.title(\"Target Distribution\")\n", + " plt.show()\n", + "\n", + "check_target_imbalance(df_exam, \"Delivery_Time\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "X = df_exam.drop(\"Delivery_Time\", axis=1).astype(float)\n", + "y = df_exam['Delivery_Time'].astype(float)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "#Task2\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", + "#Task3 , 4 and 5\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", + "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", + "\n" + ], + "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" + ], + "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/265/Q2.ipynb b/submissions_extracted/265/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..ce3a31deb8e07d5e1258ad2f004f1fdff98a8514 --- /dev/null +++ b/submissions_extracted/265/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 torch\n", + "import torch.nn as nn\n", + "from torch.optim import AdamW\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.datasets import MNIST\n", + "from torch.utils.data import DataLoader\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", + "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", + "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", + "\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", + "import matplotlib.pyplot as plt\n", + "images, labels = next(iter(train_loader))\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()\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your model class here:\n", + "class NN4Layers(nn.Module):\n", + "\n", + " def __init__(self, input_dim, hidden_dim, output_dim):\n", + " super(NN4Layers, 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", + " 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? :)" + ], + "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).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 = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n", + "# Model parameters\n", + "input_dim = 36 * 36 #\n", + "hidden_dim = 14 # Design choice\n", + "output_dim = 1 # here 1\n", + "\n", + "# Instantiate model\n", + "model = NN4Layers(input_dim, hidden_dim, output_dim).to(device)\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", + "# 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": [ + "# Task 5: Start training for 20 epochs:\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", + "### i think i need to squeeze but i dont know where exactly! HELP" + ], + "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()\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/265/Q3.ipynb b/submissions_extracted/265/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..7d0d4433b1cbeef78d0ef16913d793b71d1ab7af --- /dev/null +++ b/submissions_extracted/265/Q3.ipynb @@ -0,0 +1,313 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "from IPython.display import clear_output\n", + "\n", + "%pip install kagglehub catboost xgboost 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", + "# 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()\n", + "## NOTE: THERE IS SOMETHING HERE AS YOU CAN SEE I CAN'T SEE THE TABLE SO I CANT\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", + "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", + "### I CAN'T FIGURE THAT COLUMNS CUZ AS I SAID, DF.INFO IS NOT SHOWING !!!\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", + "print(\"Categorical Columns:\", list(categorical_cols))\n", + "# NO NEED" + ], + "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\") # DON'T 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 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", + "# Task 2:\n", + "from sklearn.model_selection import StratifiedKFold\n", + "from sklearn.metrics import accuracy_score, f1_score\n", + "n_splits = 5 # K=5 Folds\n", + "# Stratified 5-Fold Cross-Validation, shuffled\n", + "skf = StratifiedKFold(n_splits=n_splits, shuffle=True, random_state=42)\n", + "# Task 3\n", + "from catboost import CatBoostClassifier\n", + "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': []}\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", + " 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)\n", + "\n", + "\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\" F1-Score: {np.mean(all_results[model_name]['f1']):.4f}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "majority_class = y.value_counts().idxmax()\n", + "baseline_pred = [majority_class] * len(y)\n", + "\n", + "# Evaluate the baseline\n", + "baseline_accuracy = accuracy_score(y, baseline_pred)\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 F1-Score: {baseline_f1:.4f}\")\n" + ], + "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", + " if i == 1:\n", + " break\n", + "\n", + "plt.tight_layout()\n", + "plt.show()\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "print(\"The important feature is P_43\")" + ], + "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/266/Q1.ipynb b/submissions_extracted/266/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..69cc73652ff6b4fd321ad8451ab1bfa42300c60e --- /dev/null +++ b/submissions_extracted/266/Q1.ipynb @@ -0,0 +1,400 @@ +{ + "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", + "import zipfile\n", + "from lightgbm import LGBMRegressor\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", + "df = pd.read_csv(os.path.join(path, \"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", + "\n", + "plt.figure(figsize=(8, 5))\n", + "sns.histplot(df[\"Delivery_Time\"], bins=30, edgecolor='black')\n", + "plt.title(\"Target Distribution: delivery_time\")\n", + "plt.xlabel(\"delivery_time (minutes)\")\n", + "plt.ylabel(\"Count\")\n", + "plt.tight_layout()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "if \"Order_ID\" in df.columns: df = df.drop(\"Order_ID\", axis=1)\n", + "df.head() #see there is no Order_ID anymore" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "\n", + "#to check what type of misssing values we have\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", + "print(\"Missing values before handeling:\", df.isnull().sum().sum()) #output = 311\n", + "\n", + "#handeling them:\n", + "#simply any numarical null fill with median\n", + "#any categorical fill with mode the most repeated\n", + "num_cols_all = df.select_dtypes(include=[\"int64\", \"float64\"]).columns\n", + "cat_cols_all = df.select_dtypes(include=[\"object\", \"category\"]).columns\n", + "\n", + "for col in num_cols_all:\n", + " if df[col].isna().any():\n", + " df[col] = df[col].fillna(df[col].median())\n", + "\n", + "for col in cat_cols_all:\n", + " if df[col].isna().any():\n", + " df[col] = df[col].fillna(df[col].mode()[0])\n", + "\n", + "print(\"Missing values after handeling:\", df.isnull().sum().sum()) #output = 311\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\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", + "\n", + "df = df.drop_duplicates()\n", + "after_dupes = df.duplicated().sum()\n", + "print(f\"after drop: {after_dupes}\")\n" + ], + "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", + "#Apply feature scaling for all features (Use StandardScaler)\n", + "#Check for target imbalance and state if it is imbalanced or not (keep this cell empty if not needed)\n", + "\n", + "\n", + "# Task 4: Write your code here:\n", + "# Encode categorical variables using One-Hot Encoding\n", + "\n", + "categorical_cols = df.select_dtypes(include=[\"object\", \"category\"]).columns\n", + "df = pd.get_dummies(df, columns=categorical_cols, drop_first=True)\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", + "scaler = StandardScaler()\n", + "feature_cols = df.columns.drop(\"Delivery_Time\") #not including the target\n", + "df[feature_cols] = scaler.fit_transform(df[feature_cols])\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 6: Write your code here:\n", + "\n", + "# Regression target so not treated as imbalanced like classification" + ], + "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": [], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:\n", + "\n", + "num_cols = X.columns.tolist()\n", + "\n", + "# K-Fold Cross Validation\n", + "kf = KFold(n_splits=5, shuffle=True, random_state=42)\n", + "mae_scores = []\n", + "\n", + "for fold, (train_idx, val_idx) in enumerate(kf.split(X), start=1):\n", + " # Split data\n", + " X_train_fold = X.iloc[train_idx]\n", + " y_train_fold = y.iloc[train_idx]\n", + " X_val_fold = X.iloc[val_idx]\n", + " y_val_fold = y.iloc[val_idx]\n", + "\n", + " # Scale features\n", + " scaler = StandardScaler()\n", + " X_train_final = scaler.fit_transform(X_train_fold)\n", + " X_val_final = scaler.transform(X_val_fold)\n", + "\n", + " # Train Random Forest model\n", + " model = RandomForestRegressor(\n", + " n_estimators=300,\n", + " random_state=42,\n", + " n_jobs=-1\n", + " )\n", + "\n", + " model.fit(X_train_final, y_train_fold)\n", + "\n", + " # Predict on validation set\n", + " preds = model.predict(X_val_final)\n", + "\n", + " # Evaluate using MAE\n", + " mae = mean_absolute_error(y_val_fold, preds)\n", + " mae_scores.append(mae)\n", + "\n", + " print(f\"Fold {fold} MAE: {mae:.4f}\")\n", + "\n", + "# Print average MAE across folds\n", + "print(f\"\\nAverage MAE across folds: {np.mean(mae_scores):.4f}\")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "\n", + "final_model = RandomForestRegressor(n_estimators=300, random_state=42,n_jobs=-1)\n", + "final_model.fit(X, y)\n", + "importances = final_model.feature_importances_\n", + "\n", + "plt.figure(figsize=(10, 6))\n", + "sns.barplot(x=importances, y=X.columns)\n", + "plt.title(\"Feature Importance (RandomForest)\")\n", + "plt.xlabel(\"Importance\")\n", + "plt.ylabel(\"Feature\")\n", + "plt.tight_layout()\n", + "plt.show()\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "y_pred = final_model.predict(X)\n", + "\n", + "plt.figure(figsize=(8, 5))\n", + "sns.histplot(y_pred, bins=30)\n", + "plt.xlabel(\"Predicted Delivery Time\")\n", + "plt.ylabel(\"Count\")\n", + "plt.tight_layout()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:\n", + "# Part 5: Bonus - Ensemble\n", + "\n", + "from catboost import CatBoostRegressor\n", + "\n", + "kf = KFold(n_splits=5, shuffle=True, random_state=42)\n", + "mae_scores_ensemble = []\n", + "\n", + "for fold, (train_idx, val_idx) in enumerate(kf.split(X), start=1):\n", + " # Split data\n", + " X_train_fold = X.iloc[train_idx]\n", + " y_train_fold = y.iloc[train_idx]\n", + " X_val_fold = X.iloc[val_idx]\n", + " y_val_fold = y.iloc[val_idx]\n", + "\n", + " # Scale features (same scaler for both models)\n", + " scaler = StandardScaler()\n", + " X_train_scaled = scaler.fit_transform(X_train_fold)\n", + " X_val_scaled = scaler.transform(X_val_fold)\n", + "\n", + " # this is the Random Forest\n", + " rf_model = RandomForestRegressor(\n", + " n_estimators=40,\n", + " random_state=42,\n", + " n_jobs=-1\n", + " )\n", + "\n", + " # his is the CatBoost\n", + " cb_model = CatBoostRegressor(\n", + " iterations=40,\n", + " learning_rate=0.05,\n", + " depth=8,\n", + " random_seed=42,\n", + " verbose=False\n", + " )\n", + "\n", + " # Train both models\n", + " rf_model.fit(X_train_scaled, y_train_fold)\n", + " cb_model.fit(X_train_scaled, y_train_fold)\n", + "\n", + " # Predict using both models\n", + " rf_preds = rf_model.predict(X_val_scaled)\n", + " cb_preds = cb_model.predict(X_val_scaled)\n", + "\n", + " # Average predictions\n", + " avg_preds = (rf_preds + cb_preds) / 2\n", + "\n", + " # Evaluate using MAE\n", + " mae = mean_absolute_error(y_val_fold, avg_preds)\n", + " mae_scores_ensemble.append(mae)\n", + "\n", + " print(f\"Fold {fold} Ensemble MAE: {mae:.4f}\")\n", + "\n", + "# Print average ensemble MAE\n", + "print(f\"\\nAverage Ensemble MAE across folds: {np.mean(mae_scores_ensemble):.4f}\")\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/266/Q2.ipynb b/submissions_extracted/266/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..b68b8d5726c721c7e55ba498f9e4ab496fa220eb --- /dev/null +++ b/submissions_extracted/266/Q2.ipynb @@ -0,0 +1,367 @@ +{ + "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.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", + "\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 matplotlib.pyplot as plt\n", + "from torch.utils.data import DataLoader, TensorDataset\n", + "from torch.optim import Adam\n", + "import numpy as np\n", + "\n", + "\n", + "# 1. Convert Numpy arrays to PyTorch Tensors\n", + "X_train_t = torch.tensor(X_train, dtype=torch.float32)\n", + "X_test_t = torch.tensor(X_test, dtype=torch.float32)\n", + "y_train_t = torch.tensor(y_train, dtype=torch.float32)\n", + "y_test_t = 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_t, y_train_t)\n", + "test_dataset = TensorDataset(X_test_t, y_test_t)\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(\"Batch X shape:\", X_batch.shape)\n", + "print(\"Batch y shape:\", y_batch.shape)\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 5. Display sample images\n", + "plt.figure(figsize=(8, 4))\n", + "for i in range(6):\n", + " plt.subplot(2, 3, i + 1)\n", + " img = X_batch[i].permute(1, 2, 0)\n", + " plt.imshow(img)\n", + " plt.title(f\"Age: {y_batch[i].item()}\")\n", + " plt.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", + "\n", + "class NN4Layer(nn.Module):\n", + "\n", + " def __init__(self, input_dim, hidden_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, 1)\n", + "\n", + " # activation\n", + " self.relu = nn.ReLU()\n", + "\n", + " def forward(self, x):\n", + " # flatten image\n", + " x = x.view(x.size(0), -1)\n", + "\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", + " # output layer\n", + " output = self.layer4(a3)\n", + "\n", + " return output" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "\n", + "def train_one_epoch(model, optimizer, criterion, train_loader, device):\n", + " # Set the model to training mode\n", + "\n", + " model.train()\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.view(-1, 1).to(device) # FIX shape\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", + " return running_loss / len(train_loader)\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", + "\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.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", + " return running_loss / len(test_loader) #\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", + "input_dim = X_train.shape[1] * X_train.shape[2] * X_train.shape[3]\n", + "hidden_dim = 256\n", + "output_dim = 10 # CIFAR-10 classes\n", + "\n", + "model = NN4Layer(input_dim, hidden_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.MSELoss() #because it is regrission not classification\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", + "\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", + " 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": [ + "# Task 1: Write your code here:\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 (MSE)\")\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\n", + "\n", + "\n", + "# Show some test images with predicted age vs actual age\n", + "\n", + "model.eval()\n", + "with torch.no_grad():\n", + " X_vis, y_vis = next(iter(test_loader)) # take one batch\n", + " X_vis = X_vis.to(device)\n", + "\n", + " preds = model(X_vis).cpu().numpy().flatten() # get model predictions\n", + "\n", + "# plot examples\n", + "plt.figure(figsize=(8, 4))\n", + "for i in range(6):\n", + " plt.subplot(2, 3, i + 1)\n", + " # change image shape to h, w, c for plotting\n", + " img = X_vis[i].cpu().permute(1, 2, 0)\n", + "\n", + " plt.imshow(img)\n", + " plt.title(f\"prediciotn: {preds[i]:.1f} | actual: {y_vis[i].item()}\")\n", + " plt.axis(\"off\")\n", + "\n", + "plt.tight_layout()\n", + "plt.show()\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/266/Q3.ipynb b/submissions_extracted/266/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..ca05beb89499621c550eccb2eb987e0d1eb7796a --- /dev/null +++ b/submissions_extracted/266/Q3.ipynb @@ -0,0 +1,317 @@ +{ + "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", + "\n", + "from sklearn.model_selection import StratifiedKFold\n", + "from sklearn.preprocessing import StandardScaler, LabelEncoder\n", + "from sklearn.metrics import accuracy_score, f1_score\n", + "!pip install catboost\n", + "\n", + "from catboost import CatBoostClassifier\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", + "\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()\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", + "# Task 2: Write your code here:\n", + "\n", + "#to check what type of misssing values we have\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", + "print(\"Missing values before handeling:\", df.isnull().sum().sum()) #output = 311\n", + "\n", + "#handeling them:\n", + "#simply any numarical null fill with median\n", + "#any categorical fill with mode the most repeated\n", + "num_cols_all = df.select_dtypes(include=[\"int64\", \"float64\"]).columns\n", + "cat_cols_all = df.select_dtypes(include=[\"object\", \"category\"]).columns\n", + "\n", + "for col in num_cols_all:\n", + " if df[col].isna().any():\n", + " df[col] = df[col].fillna(df[col].median())\n", + "\n", + "for col in cat_cols_all:\n", + " if df[col].isna().any():\n", + " df[col] = df[col].fillna(df[col].mode()[0])\n", + "\n", + "print(\"Missing values after handeling:\", df.isnull().sum().sum()) #output = 311\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\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", + "\n", + "df = df.drop_duplicates()\n", + "after_dupes = df.duplicated().sum()\n", + "print(f\"after drop: {after_dupes}\")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "cat_cols = df.select_dtypes(include=[\"object\", \"category\"]).columns\n", + "for col in cat_cols:\n", + " le = LabelEncoder()\n", + " df[col] = le.fit_transform(df[col])" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "num_cols = df.select_dtypes(include=[\"int64\", \"float64\"]).columns.drop(\"Target\")\n", + "scaler = StandardScaler()\n", + "df[num_cols] = scaler.fit_transform(df[num_cols])" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "target_ratio = df[\"Target\"].value_counts(normalize=True)\n", + "print(\"Target distribution:\\n\", target_ratio)\n", + "print(\"it is imbalanced so ganna use F1-score\")" + ], + "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" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:\n", + "#ganna use StratifiedKFold because it is imbalanced\n", + "skf = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)\n", + "f1_scores = []\n", + "\n", + "for fold, (train_idx, val_idx) in enumerate(skf.split(X, y), start=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 = CatBoostClassifier(\n", + " iterations=40,\n", + " learning_rate=0.05,\n", + " depth=8,\n", + " random_seed=42,\n", + " verbose=False\n", + " )\n", + "\n", + " model.fit(X_train, y_train)\n", + " preds = model.predict(X_val)\n", + "\n", + " f1 = f1_score(y_val, preds)\n", + " f1_scores.append(f1)\n", + " print(f\"Fold {fold} F1-score: {f1:.4f}\")\n", + "\n", + "print(f\"\\nAverage F1-score across folds: {np.mean(f1_scores):.4f}\")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "model.fit(X, y)\n", + "\n", + "importances = model.get_feature_importance()\n", + "feature_names = X.columns\n", + "\n", + "fi = pd.DataFrame({\n", + " \"feature\": feature_names,\n", + " \"importance\": importances\n", + "}).sort_values(\"importance\", ascending=False)\n", + "\n", + "plt.figure(figsize=(10, 6))\n", + "sns.barplot(data=fi.head(20), x=\"importance\", y=\"feature\")\n", + "plt.title(\"Top 20 Feature Importances (CatBoost)\")\n", + "plt.tight_layout()\n", + "plt.show()\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "golden_feature = fi.iloc[0][\"feature\"]\n", + "print(\"Golden Feature:\", golden_feature)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:\n", + "X_golden = X[[golden_feature]]\n", + "f1_scores_golden = []\n", + "\n", + "for fold, (train_idx, val_idx) in enumerate(skf.split(X_golden, y), start=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_golden = CatBoostClassifier(\n", + " iterations=40,\n", + " learning_rate=0.05,\n", + " depth=6,\n", + " random_seed=42,\n", + " verbose=False\n", + " )\n", + "\n", + " model_golden.fit(X_train, y_train)\n", + " preds = model_golden.predict(X_val)\n", + "\n", + " f1 = f1_score(y_val, preds)\n", + " f1_scores_golden.append(f1)\n", + " print(f\"Fold {fold} Golden Feature F1-score: {f1:.4f}\")\n", + "\n", + "print(f\"\\nAverage Golden Feature F1-score: {np.mean(f1_scores_golden):.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/267/Q1.ipynb b/submissions_extracted/267/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..d1b4c7f4680c06eefb6ab9fc9422a94725a4049e --- /dev/null +++ b/submissions_extracted/267/Q1.ipynb @@ -0,0 +1,294 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "import pandas as pd\n", + "import matplotlib.pyplot as plt\n", + "from sklearn.preprocessing import StandardScaler\n", + "from sklearn.preprocessing import StandardScaler, LabelEncoder\n", + "from sklearn.preprocessing import LabelEncoder\n", + "\n", + "from sklearn.model_selection import KFold, cross_val_score\n", + "from sklearn.ensemble import RandomForestRegressor\n", + "from sklearn.metrics import make_scorer, mean_absolute_error\n", + "import numpy as np\n", + "%pip install kagglehub catboost lightgbm tqdm -q\n", + "\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", + "import matplotlib.pyplot as plt\n", + "import numpy as np\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", + "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(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": [], + "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()\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "\n", + "df = df.drop(\"Order_ID\", axis=1)\n", + "\n", + "# df = df.dropna()\n", + "\n", + "# df = df.drop_duplicates()\n", + "\n", + "# scaler = StandardScaler()\n", + "# features = df.drop(\"Delivery_Time\", axis=1)\n", + "# df[features.columns] = scaler.fit_transform(features)\n", + "\n", + "# df[\"Delivery_Time\"].value_counts(normalize=True)\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "df.isnull().sum()\n", + "df = df.dropna()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "df = df.drop_duplicates()" + ], + "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", + "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'])\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "scaler = StandardScaler()\n", + "scaled_features = scaler.fit_transform(df.drop(\"Delivery_Time\", axis=1))\n", + "df[df.drop(\"Delivery_Time\", axis=1).columns] = scaled_features" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 6: Write your code here:\n", + "df[\"Delivery_Time\"].value_counts(normalize=True)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "\n", + "X = df.drop(\"Delivery_Time\", axis=1)\n", + "y = df[\"Delivery_Time\"]\n" + ], + "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", + "\n", + "model = RandomForestRegressor(random_state=42)\n", + "\n", + "mae_scorer = make_scorer(mean_absolute_error, greater_is_better=False)\n", + "\n", + "scores = cross_val_score(model, X, y, cv=kf, scoring=mae_scorer)\n", + "\n", + "print(np.mean(-scores))" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "model.fit(X, y)\n", + "\n", + "importances = model.feature_importances_\n", + "indices = np.argsort(importances)\n", + "\n", + "plt.figure()\n", + "plt.title(\"Feature Importance\")\n", + "plt.barh(range(len(indices)), importances[indices])\n", + "plt.yticks(range(len(indices)), X.columns[indices])\n", + "plt.show()\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "\n", + "preds = model.predict(X)\n", + "\n", + "plt.figure()\n", + "plt.hist(preds)\n", + "plt.title(\"Predicted Delivery Time Distribution\")\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:\n", + "\n", + "\n", + "\n", + "X = df.drop(\"Delivery_Time\", axis=1)\n", + "y = df[\"Delivery_Time\"]\n", + "\n", + "kf = KFold(n_splits=5, shuffle=True, random_state=42)\n", + "\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", + " rf = RandomForestRegressor(random_state=42)\n", + " cb = CatBoostRegressor(random_state=42, verbose=0)\n", + "\n", + " rf.fit(X_train, y_train)\n", + " cb.fit(X_train, y_train)\n", + "\n", + " pred_rf = rf.predict(X_val)\n", + " pred_cb = cb.predict(X_val)\n", + "\n", + " pred_avg = (pred_rf + pred_cb) / 2\n", + " mae_scores.append(mean_absolute_error(y_val, pred_avg))\n", + "\n", + "print(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/267/Q2.ipynb b/submissions_extracted/267/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..b3cde57acb95933f61937174d0885df2a2307e10 --- /dev/null +++ b/submissions_extracted/267/Q2.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/q2-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import os\n", + "import matplotlib.pyplot as plt\n", + "import pandas as pd\n", + "import numpy as np\n", + "from PIL import Image\n", + "from sklearn.preprocessing import LabelEncoder\n", + "from sklearn.model_selection import train_test_split\n", + "import torch\n", + "from torch.utils.data import TensorDataset, DataLoader\n", + "import matplotlib.pyplot as plt\n", + "import torch\n", + "import torch.nn as nn\n", + "import numpy as np\n", + "import torch\n", + "import torch.nn as nn\n", + "import torch.nn.functional as F\n", + "from torch.utils.data import TensorDataset, DataLoader\n", + "import torch\n", + "import torch.nn as nn\n", + "import torch.nn.functional as F\n", + "\n", + "# Load Labels\n", + "labels_df = pd.read_csv(os.path.join(path, \"labels.csv\"))\n", + "\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": [ + "# 1. Convert Numpy arrays to PyTorch Tensors\n", + "\n", + "X_train_t = torch.tensor(X_train, dtype=torch.float32)\n", + "X_test_t = torch.tensor(X_test, dtype=torch.float32)\n", + "y_train_t = torch.tensor(y_train, dtype=torch.long)\n", + "y_test_t = torch.tensor(y_test, dtype=torch.long)\n", + "\n", + "y_train = y_train.astype(int)\n", + "y_test = y_test.astype(int)\n", + "\n", + "m = int(np.max(y_train))\n", + "y_train = np.clip(y_train, 0, m)\n", + "y_test = np.clip(y_test, 0, m)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 2. Create TensorDataset objects\n", + "\n", + "train_dataset = TensorDataset(X_train_t, y_train_t)\n", + "test_dataset = TensorDataset(X_test_t, y_test_t)\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", + "images, labels = next(iter(train_loader))\n", + "output_dim = m + 1\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 4. Print shape of one batch\n", + "\n", + "print(images.shape, labels.shape)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 5. Display sample images\n", + "\n", + "fig, axes = plt.subplots(1, 6, figsize=(12, 3))\n", + "for i, ax in enumerate(axes):\n", + " img = images[i]\n", + " if img.ndim == 3 and img.shape[0] in (1, 3):\n", + " if img.shape[0] == 1:\n", + " ax.imshow(img.squeeze(0), cmap=\"gray\")\n", + " else:\n", + " ax.imshow(img.permute(1, 2, 0))\n", + " elif img.ndim == 2:\n", + " ax.imshow(img, cmap=\"gray\")\n", + " else:\n", + " ax.imshow(img.view(int(img.numel() ** 0.5), -1), cmap=\"gray\")\n", + " ax.set_title(str(labels[i].item()))\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", + "class NN4Layer(nn.Module):\n", + " def __init__(self, input_dim, hidden_dim, output_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, output_dim)\n", + " self.relu = nn.ReLU()\n", + "\n", + " def forward(self, x):\n", + " x = x.view(x.size(0), -1)\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", + " 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", + " model.train()\n", + " running_loss = 0.0\n", + " for X_batch, y_batch in train_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", + " optimizer.zero_grad()\n", + " loss.backward()\n", + " optimizer.step()\n", + " running_loss += loss.item()\n", + " avg_loss = running_loss / len(train_loader)\n", + " return avg_loss" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "\n", + "def validate(model, criterion, test_loader, device):\n", + " model.eval()\n", + " running_loss = 0.0\n", + " correct = 0\n", + " total = 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", + " probabilities = F.softmax(outputs, dim=1)\n", + " predicted = torch.argmax(probabilities, dim=1)\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": [ + "device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n", + "input_dim = X_train_t[0].numel()\n", + "hidden_dim = 256\n", + "output_dim = int(y_train_t.max().item()) + 1\n", + "\n", + "model = NN4Layer(input_dim, hidden_dim, output_dim).to(device)\n", + "criterion = nn.CrossEntropyLoss()\n", + "optimizer = torch.optim.Adam(model.parameters(), lr=1e-3)" + ], + "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", + "for epoch in range(20):\n", + " train_loss = train_one_epoch(model, optimizer, criterion, train_loader, device)\n", + " val_loss, val_acc = validate(model, criterion, test_loader, device)\n", + " train_losses.append(train_loss)\n", + " val_losses.append(val_loss)\n", + " val_accuracies.append(val_acc)\n", + "\n", + "print(train_losses)\n", + "print(val_losses)\n", + "print(val_accuracies)\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "\n", + "plt.figure()\n", + "plt.plot(train_losses)\n", + "plt.plot(val_losses)\n", + "plt.legend([\"train_loss\", \"val_loss\"])\n", + "plt.xlabel(\"epoch\")\n", + "plt.ylabel(\"loss\")\n", + "plt.show()\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2 (Bonus): Write your code here:\n", + "\n", + "\n", + "# no time" + ], + "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/267/Q3.ipynb b/submissions_extracted/267/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..dea2ef8a67ef099ae1f3c20116388111b22c61a2 --- /dev/null +++ b/submissions_extracted/267/Q3.ipynb @@ -0,0 +1,235 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "import pandas as pd\n", + "from sklearn.preprocessing import StandardScaler, LabelEncoder\n", + "import pandas as pd\n", + "from sklearn.model_selection import StratifiedKFold, cross_val_score\n", + "\n", + "%pip install kagglehub catboost lightgbm tqdm -q\n", + "\n", + "from catboost import CatBoostClassifier\n", + "from sklearn.metrics import make_scorer, f1_score, accuracy_score\n", + "import numpy as np\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", + "\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(10)\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", + "\n", + "df.isnull().sum()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "df = df.drop_duplicates()\n" + ], + "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", + "label_encoders = {}\n", + "for col in categorical_cols:\n", + " le = LabelEncoder()\n", + " df[col] = le.fit_transform(df[col].astype(str))\n", + " label_encoders[col] = le" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "\n", + "target_col = \"Target\"\n", + "num_cols = df.drop(columns=[target_col]).select_dtypes(include=[\"number\"]).columns\n", + "\n", + "scaler = StandardScaler()\n", + "df[num_cols] = scaler.fit_transform(df[num_cols])" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "\n", + "df[\"Target\"].value_counts(normalize=True)\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", + "X = df.drop(\"Target\", axis=1)\n", + "y = df[\"Target\"]\n", + "\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", + "\n", + "model = CatBoostClassifier(verbose=0, random_state=42)\n", + "\n", + "if y.value_counts(normalize=True).max() > 0.7:\n", + " scorer = make_scorer(f1_score, average=\"weighted\")\n", + "else:\n", + " scorer = make_scorer(accuracy_score)\n", + "\n", + "scores = cross_val_score(model, X, y, cv=skf, scoring=scorer)\n", + "\n", + "print(np.mean(scores))" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "\n", + "model.fit(X, y)\n", + "\n", + "importances = model.get_feature_importance()\n", + "features = X.columns\n", + "\n", + "import matplotlib.pyplot as plt\n", + "import numpy as np\n", + "\n", + "indices = np.argsort(importances)\n", + "\n", + "plt.figure()\n", + "plt.title(\"Feature Importance\")\n", + "plt.barh(range(len(indices)), importances[indices])\n", + "plt.yticks(range(len(indices)), features[indices])\n", + "plt.show()\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "\n", + "golden_feature = features[np.argmax(importances)]\n", + "print(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/268/Q1.ipynb b/submissions_extracted/268/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..65ddcbe8982e3b83e19168105e6d99258d4cfe4b --- /dev/null +++ b/submissions_extracted/268/Q1.ipynb @@ -0,0 +1,364 @@ +{ + "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 # to read the data\n", + "import kagglehub\n", + "from sklearn.preprocessing import OneHotEncoder\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", + "\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", + "# Load the dataset\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.hist(df['Delivery_Time'].dropna(), bins=30, edgecolor='black')\n", + "plt.title(\"Deliver Time Distribution\")\n", + "plt.xlabel(\"price\")\n", + "plt.ylabel(\"Frequency\")\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "df_clean = df.copy()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "df_clean = df_clean.drop('Order_ID',axis=1)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "null_cat_cols = list(df_clean.select_dtypes(include='object').isnull())\n", + "null_num_cols = list(df_clean.select_dtypes(include='number').drop(\"Delivery_Time\", axis=1).isnull())\n", + "null_num_cols" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# fill missing values in catigorical columns with the mode of that column\n", + "for col in null_cat_cols:\n", + " df_clean[col] = df_clean[col].fillna(df_clean[col].mode()[0])\n", + "\n", + "# fill missing values in numerical columns with the mean of that column\n", + "for col in null_num_cols:\n", + " avg = np.mean(df_clean[col])\n", + " df_clean[col] = df_clean[col].fillna(avg)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "df_clean.isnull().sum()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# i will drop the rows that do not have a value for the target\n", + "df_clean = df_clean.dropna(subset='Delivery_Time')" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "df_clean.isnull().sum()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "\n", + "df_clean.duplicated().any()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# i will drop all the duplicated data\n", + "df_clean = df_clean.drop_duplicates()\n", + "df_clean.duplicated().any()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "cat_cols = df_clean.select_dtypes(include='object').columns\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "for col in cat_cols:\n", + " enc = LabelEncoder()\n", + " df_clean[col] = enc.fit_transform(df_clean[col])\n", + "df_clean.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "feature_cols = df_clean.columns.drop(\"Delivery_Time\")\n", + "feature_cols" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "scale = StandardScaler()\n", + "df_clean[feature_cols] = scale.fit_transform(df_clean[feature_cols])\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "df_clean.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 6: Write your code here:\n", + "# the targets are mainly between 30 and 95\n", + "# so to ensure that the model will not get affected i will treat it as imbalanced\n", + "plt.hist(df['Delivery_Time'].dropna(), bins=30, edgecolor='black')\n", + "plt.title(\"Deliver Time 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_clean[feature_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", + "skf = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)\n", + "model = RandomForestRegressor(n_estimators=200)\n", + "all_mae = []\n", + "predicted_time = []\n", + "\n", + "\n", + "for fold, (train_idx, test_idx) in enumerate(skf.split(X, y), 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", + "\n", + " # Train\n", + " model.fit(X_train, y_train)\n", + "\n", + " # Predict\n", + " y_pred = model.predict(X_test)\n", + "\n", + " # mae\n", + " mae = mean_absolute_error(y_test, y_pred)\n", + " all_mae.append(mae)\n", + "\n", + " # for the plot later\n", + " predicted_time.append(y_pred)\n", + "\n", + "\n", + "print(f\"avg MAE: {np.mean(all_mae)}\")\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "importance = model.feature_importances_\n", + "plt.barh(feature_cols, importance)\n", + "plt.title(f\"Random Forst Importance\")\n", + "plt.xlabel(\"Coefficient (Importance)\")\n", + "plt.tight_layout()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "plt.hist(predicted_time, edgecolor='black')\n", + "plt.title(\"predicted Deliver 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:" + ], + "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/268/Q2.ipynb b/submissions_extracted/268/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..1cbe84111ebf5e8992cc0c864d0af40cceb7f4c9 --- /dev/null +++ b/submissions_extracted/268/Q2.ipynb @@ -0,0 +1,381 @@ +{ + "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\n", + "from torch.utils.data import TensorDataset\n", + "from torch.optim import AdamW\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", + "\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)\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", + ") # to get one batch (32 samples) the dataloader will go to the train dataset 32 to time\n", + "\n", + "\n", + "# DataLoader for test/validation data\n", + "test_loader = DataLoader(\n", + " test_dataset,\n", + " batch_size=32,\n", + " shuffle=False, # to validate or model perfectly\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", + "# iter makes the train_loader iterable\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()" + ], + "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", + " self.l1 = nn.Linear(input_dim, hidden_dim)\n", + " self.l2 = nn.Linear(hidden_dim, hidden_dim)\n", + " self.l3 = nn.Linear(hidden_dim, hidden_dim)\n", + " self.l4 = nn.Linear(hidden_dim, output_dim)\n", + "\n", + " self.relu = nn.ReLU()\n", + "\n", + " def forward(self, x):\n", + " # First hidden layer\n", + " z1 = self.l1(x)\n", + " a1 = self.relu(z1)\n", + "\n", + " # Second hidden layer\n", + " z2 = self.l2(a1)\n", + " a2 = self.relu(z2)\n", + "\n", + " # third hidden layer\n", + " z3 = self.l3(a2)\n", + " a3 = self.relu(z3)\n", + "\n", + " # forth hidden layer\n", + " output = self.l4(a3)\n", + "\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).to(device)\n", + "\n", + " # Forward pass --> making the prediction and calculating the loss\n", + " outputs = model(X_batch) # --> the current 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.view(X_batch.size(0), -1).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", + " 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", + "\n", + "# Device configuration\n", + "device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\n", + "print(f\"Using device: {device}\")\n", + "\n", + "#learning rate and num of epochs\n", + "learning_rate = 0.001\n", + "num_epochs = 20\n", + "\n", + "# define dims\n", + "input_dim = X_train.flatten(start_dim=1).shape[1]\n", + "hidden_dim = 64\n", + "output_dim = 1\n", + "\n", + "# Model, Criterion,lmizer\n", + "\n", + "\n", + "model = NN4Layer(input_dim, hidden_dim, output_dim).to(device)\n", + "criterion = nn.MSELoss()\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", + "# Run Training\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", + "\n", + " # save for every epoch\n", + " train_losses.append(train_loss)\n", + " val_losses.append(val_loss)\n", + "\n", + "\n", + "\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", + "# 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", + "\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" + ], + "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/268/Q3.ipynb b/submissions_extracted/268/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..1f60d500275a8eac187cb15f6588fe4e768b931d --- /dev/null +++ b/submissions_extracted/268/Q3.ipynb @@ -0,0 +1,286 @@ +{ + "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 # to read the data\n", + "import kagglehub\n", + "from sklearn.preprocessing import OneHotEncoder\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 f1_score\n", + "\n", + "from sklearn.model_selection import StratifiedKFold\n", + "\n", + "\n", + "import warnings\n", + "warnings.filterwarnings('ignore')\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "import os # to read the data\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 dataset\n", + "data_path = os.path.join(path, 'Q3_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": [ + "df_clean = df.copy()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "df_clean[\"Target\"].isnull().sum()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "null_cols = list(df_clean.drop(\"Target\", axis=1).isnull())\n", + "\n", + "# i will fill the missing values with the median\n", + "# from what i understand the each feature is a code for something (categorical) so for that i think the median makes more sense ;\n", + "\n", + "df_clean[null_cols] = df_clean[null_cols].fillna(df_clean[null_cols].median())" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "df_clean.duplicated().sum().any()\n", + "# there aren't any duplicated rows" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "df_clean.select_dtypes(include='object').columns\n", + "\n", + "# there are not any categorical columns" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "feature_cols = df_clean.columns.drop(\"Target\")\n", + "feature_cols\n", + "\n", + "scaler = StandardScaler()\n", + "df[feature_cols] = scaler.fit_transform(df[feature_cols])" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "\n", + "df['Target'].value_counts(normalize=True)\n", + "\n", + "# the target is imbalanced" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "X = df_clean[feature_cols]\n", + "y = df_clean['Target']" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "%pip install catboost -q\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", + "skf = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)\n", + "model = CatBoostClassifier(verbose=0, n_estimators=320, max_depth=4)\n", + "all_f1 = []\n", + "\n", + "for fold, (train_idx, test_idx) in enumerate(skf.split(X, y), 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", + "\n", + " # Train\n", + " model.fit(X_train, y_train)\n", + "\n", + " # Predict\n", + " y_pred = model.predict(X_test)\n", + "\n", + " # f1 : because the data is imbalanced\n", + " f1 = f1_score(y_test, y_pred)\n", + " all_f1.append(f1)\n", + "\n", + "\n", + "\n", + "print(f\"avg f1: {np.mean(all_f1)}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "\n", + "# Task 1: Write your code here:\n", + "importance = model.feature_importances_\n", + "sorted_imp = np.argsort(importance)\n", + "\n", + "\n", + "feature_cols = feature_cols[sorted_imp]\n", + "importance = importance[sorted_imp]\n", + "\n", + "\n", + "plt.figure(figsize=(10, 50))\n", + "plt.barh(feature_cols, importance)\n", + "plt.title(f\"Random Forst Importance\")\n", + "plt.xlabel(\"Coefficient (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 the feature importance plot above\n", + "print(\"The most important feature is D_136\")\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/269/Q1.ipynb b/submissions_extracted/269/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..d78ab3e0565a0646cb70f616697908d13e6224e4 --- /dev/null +++ b/submissions_extracted/269/Q1.ipynb @@ -0,0 +1,222 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import numpy as np\n", + "import pandas as pdpd\n", + "import matplotlib.pyplot as plt\n", + "import os\n", + "import pandas as pd\n", + "\n", + "\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 herehere:\n", + "# LLoadoad the datasodatasoss\n", + "delivery_path = os.path.join(path, 'Q1_data.csv')\n", + "df= pd.read_csv(delivery_path)\n", + "\n", + "df" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "print(f\"dataset shape: {df_delivery.shape}\")\n", + "df.head()\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", + "# 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 5: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"bumba5341/advertisingcsv\")\n", + "\n", + "print(\"Path to dataset files:\", path)\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 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/269/Q2.ipynb b/submissions_extracted/269/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..c8937ff34d658b6340ef5c82e1d71e84083e0ea8 --- /dev/null +++ b/submissions_extracted/269/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/269/Q3.ipynb b/submissions_extracted/269/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..c97832709061629f03a86d1f40306ca8a3e2a744 --- /dev/null +++ b/submissions_extracted/269/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/27/Q1.ipynb b/submissions_extracted/27/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..e05ecde2335fc18fbc7173781935097a421a5cb4 --- /dev/null +++ b/submissions_extracted/27/Q1.ipynb @@ -0,0 +1,174 @@ +{ + "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", + ");" + ], + "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/27/Q2.ipynb b/submissions_extracted/27/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..064322bf98039138f936d52a95fa68ca5126514c --- /dev/null +++ b/submissions_extracted/27/Q2.ipynb @@ -0,0 +1,191 @@ +{ + "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" + ], + "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/27/Q3.ipynb b/submissions_extracted/27/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..7329ba22007094de25daf2c1ed8f3fe810274b25 --- /dev/null +++ b/submissions_extracted/27/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/270/Q1.ipynb b/submissions_extracted/270/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..37ac153d6e3edf7a7295cd7f689ab91cd0e24847 --- /dev/null +++ b/submissions_extracted/270/Q1.ipynb @@ -0,0 +1,439 @@ +{ + "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", + "#fileName=os.listdir(path)\n", + "#full_path = os.path.join(path, fileName[0])\n", + "#csv_path = os.path.join(full_path)\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", + "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_clean = df.copy()\n", + "df_clean = df_clean.drop(columns=\"Order_ID\", axis=1)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "# Analyze missing values\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", + "# Delete the missing values\n", + "missData = missing_data['Column'].copy().tolist()\n", + "print(f'The missing values columns: \\n{missData}\\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 = missData)\n", + "print(f\"After dropping missing values: {df_clean.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "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", + "# 1. Identify all categorical columns in X (features).\n", + "def encode_categorical_columns(dataframe):\n", + " categorical_cols = dataframe.select_dtypes(include=[\"object\"]).columns\n", + " print(\"Categorical Columns:\", list(categorical_cols))\n", + "\n", + "onehot_encoders = encode_categorical_columns(df_clean)\n", + "\n", + "# 2. Apply One-Hot Encoding to the categorical feature columns in X.\n", + "from sklearn.preprocessing import OneHotEncoder\n", + "categorical_cols = df_clean.select_dtypes(include=[\"object\"]).columns.tolist()\n", + "\n", + "X_obj = df_clean[categorical_cols]\n", + "categorical_cols.append('Delivery_Time')\n", + "X_rem = df_clean.drop(categorical_cols, axis=1)\n", + "target = df_clean['Delivery_Time']\n", + "\n", + "print(categorical_cols)\n", + "le = OneHotEncoder(sparse_output=False)\n", + "X_obj_encoded = pd.DataFrame(le.fit_transform(X_obj), columns=le.get_feature_names_out(X_obj.columns))\n", + "X_obj_encoded" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5:\n", + "from sklearn.preprocessing import StandardScaler\n", + "numerical_cols = X_rem.select_dtypes(include=[\"int64\", \"float64\"]).columns ### DON'T SCALE THE TARGET\n", + "scaler = StandardScaler()\n", + "X_rem[numerical_cols] = scaler.fit_transform(X_rem[numerical_cols])" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "features = X_obj_encoded\n", + "X_rem_cols = X_rem.columns.to_list()\n", + "\n", + "for col in X_rem_cols:\n", + " features[col] = X_rem[col]\n", + "\n", + "features.shape\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "features" + ], + "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 = features\n", + "y = target\n", + "X" + ], + "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 KFold\n", + "from sklearn.metrics import mean_squared_error as mean_absolute_error\n", + "\n", + "lr_mae = []\n", + "models = {\n", + " \"Random Forest Regressor\": RandomForestRegressor(n_estimators=200),\n", + " \"Ridge Regression\": Ridge(alpha=1.0, max_iter=10000),\n", + " \"LASSO Regression\": Lasso(alpha=1.0, max_iter=10000),\n", + "}\n", + "\n", + "# Storage for results\n", + "all_results = {}\n", + "\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 # K=5 Folds\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", + " # Store results\n", + " all_results[model_name][\"mae\"].append(mae)\n", + " lr_mae.append(mae)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import numpy as np\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}\")" + ], + "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())\n", + "\n", + "# Evaluate the baseline\n", + "baseline_mae = mean_absolute_error(y, baseline_pred)\n", + "\n", + "print(f\"Baseline MAE (using mean target): {baseline_mae:.4f}\")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "from sklearn.linear_model import Ridge, Lasso\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:\n", + "# Task 5: Write your code here:\n", + "import matplotlib.pyplot as plt\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(y_pred, \"Delivery_Time\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "! pip install CatBoost" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:\n", + "# Task 2,3,4,5: Write your code here:\n", + "from sklearn.ensemble import RandomForestRegressor\n", + "from catboost import CatBoostRegressor\n", + "from sklearn.model_selection import KFold\n", + "from sklearn.metrics import mean_squared_error as mean_absolute_error\n", + "\n", + "lr_mae = []\n", + "models = {\n", + " \"Random Forest Regressor\": RandomForestRegressor(n_estimators=200),\n", + " \"CatBoost\": CatBoostRegressor(verbose=0)\n", + "}\n", + "\n", + "# Storage for results\n", + "all_results = {}\n", + "\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 # K=5 Folds\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", + " # Store results\n", + " all_results[model_name][\"mae\"].append(mae)\n", + " lr_mae.append(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/270/Q2.ipynb b/submissions_extracted/270/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..6532a86d124259227808e0c411c79de368f02368 --- /dev/null +++ b/submissions_extracted/270/Q2.ipynb @@ -0,0 +1,398 @@ +{ + "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.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", + "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", + "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", + "# 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", + "# 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", + "# 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", + " # 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", + " 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", + " # 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", + "input_dim = 36 * 36 * 3 # MNIST images flattened\n", + "hidden_dim = 32 # Design choice\n", + "output_dim = 1\n", + "\n", + "# Instantiate model\n", + "model = NN4Layer(input_dim, hidden_dim, output_dim).to(device)\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", + "# TODO: Define criterion (loss function) (hint: what loss do we use for multiclass ?)\n", + "criterion = nn.MSELoss()\n", + "# TODO: Define optimizer(what is updated during training?)\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": [ + "# 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", + "# :)" + ], + "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/270/Q3.ipynb b/submissions_extracted/270/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..806057b7bf4ae94f3c0c1662aaed1d1e4bff0aea --- /dev/null +++ b/submissions_extracted/270/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", + "\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", + "df_clean = df.copy()\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(25)\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "# 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 3: Write your code here:\n", + "\n", + "# All types are int and float, so no need to encode" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "from sklearn.preprocessing import MinMaxScaler\n", + "numerical_cols = df_clean.select_dtypes(include=[\"int64\", \"float64\"]).columns.drop('Target')\n", + "scaler = MinMaxScaler()\n", + "df_clean[numerical_cols] = scaler.fit_transform(df_clean[numerical_cols])" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "print(df_clean['Target'].sum())\n", + "print(df_clean['Target'].count()-(df_clean['Target'].sum()))\n", + "\n", + "# Imbalanced" + ], + "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/271/Q1.ipynb b/submissions_extracted/271/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..831697c0e5cf9f1439a1a7b87469f0ffd3d33485 --- /dev/null +++ b/submissions_extracted/271/Q1.ipynb @@ -0,0 +1,281 @@ +{ + "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 os\n", + "\n", + "#Read the dataset\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", + "#Inspect the first few rows\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "#Display information\n", + "df.info() #Deliverytime have miss data" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "#describe the data\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", + "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", + "#check data after drop column \"Order_ID\"\n", + "df.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)\n", + "miss_data = ['Weather', 'Traffic_Level', 'Time_of_Day', 'Courier_Experience_yrs', 'Delivery_Time']\n", + "\n", + "df['Delivery_Time'] = df['Delivery_Time'].fillna(df['Delivery_Time'].mean())\n", + "df['Courier_Experience_yrs'] = df['Courier_Experience_yrs'].fillna(df['Courier_Experience_yrs'].mean())\n", + "df = df.fillna({'Weather': 'Unknown', 'Traffic_Level': 'Unknown','Time_of_Day':'Unknown'})\n", + "df.sample(10)" + ], + "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)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:Encode categorical variables if needed (Bonus if used One Hot Encoding) #import OneHotEncoder\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", + "#encoder categorical_cols with Onehot incoder\n", + "encoder = LabelEncoder()\n", + "for col in df.select_dtypes(include=[\"object\"]).columns:\n", + " df[col] = encoder.fit_transform(df[col])\n" + ], + "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\n", + "standerd_scaler = StandardScaler()\n", + "data_standerd_scaler = standerd_scaler.fit_transform(df)\n" + ], + "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", + "from sklearn.model_selection import train_test_split\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(\n", + " X, y,\n", + " test_size=0.2, # 20% for test, remaining 80% for train\n", + " random_state=42, # reproducible output\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 RandomForestRegressor\n", + "from sklearn.metrics import mean_absolute_error\n", + "\n", + "kfold = KFold(n_splits=5, shuffle=True, random_state=42)\n", + "model = RandomForestRegressor()\n", + "mae_scores = []\n", + "rmse_scores = []\n", + "\n", + "for train_idx, val_idx in kfold.split(X):\n", + " X_fold_train, X_fold_val = X_train.iloc[train_idx], X_train.iloc[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" + ], + "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:" + ], + "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/271/Q2.ipynb b/submissions_extracted/271/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..9e683dfddacb1bd173b28ae915483bd60c6e1500 --- /dev/null +++ b/submissions_extracted/271/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", + "\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", + "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", + "\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": [ + "# 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", + "\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", + "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/271/Q3.ipynb b/submissions_extracted/271/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..c247d94176568d2dd5a3a52179b947ac697656b8 --- /dev/null +++ b/submissions_extracted/271/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 pandas as pd\n", + "import numpy as np\n", + "import os\n", + "\n", + "#Read the dataset\n", + "\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(\"\\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", + "from sklearn.preprocessing import OneHotEncoder\n", + "categorical_cols = list(df.select_dtypes(include=[\"object\"]).columns)\n", + "\n", + "print(\"Categorical Columns:\", list(categorical_cols))" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\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_scale = scaler.fit_transform()" + ], + "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" + ], + "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/272/Q1.ipynb b/submissions_extracted/272/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..dd09b397c5de4b29032a76d577147901ef423074 --- /dev/null +++ b/submissions_extracted/272/Q1.ipynb @@ -0,0 +1,280 @@ +{ + "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, RandomForestRegressor\n", + "from sklearn.metrics import classification_report, confusion_matrix, accuracy_score\n", + "from sklearn.preprocessing import StandardScaler\n", + "import warnings\n", + "from sklearn.model_selection import KFold\n", + "from sklearn.metrics import mean_absolute_error\n", + "import numpy as np\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": [ + "df = pd.read_csv(os.path.join(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": [ + "import matplotlib.pyplot as plt\n", + "import seaborn as sns\n", + "\n", + "plt.figure(figsize=(10, 6))\n", + "sns.histplot(df['Delivery_Time'], kde=True, color='blue')\n", + "plt.title('Distribution of Delivery Time')\n", + "plt.xlabel('Delivery Time (minutes)')\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": [ + "# Task 2: Write your code here:\n", + "print(df.isnull().sum())\n", + "\n", + "for col in df.columns:\n", + " if df[col].dtype == 'object':\n", + " df[col] = df[col].fillna(df[col].mode()[0])\n", + " else:\n", + " df[col] = df[col].fillna(df[col].median())" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "df = df.drop_duplicates()" + ], + "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 = pd.get_dummies(df, columns=categorical_cols, drop_first=True)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "scaler = StandardScaler()\n", + "features = df.drop('Delivery_Time', axis=1).columns\n", + "df[features] = scaler.fit_transform(df[features])" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 6: Write your code here:\n", + "#will leave it empty" + ], + "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", + "\n", + "kf = KFold(n_splits=5, shuffle=True, random_state=42)\n", + "mae_scores = []\n", + "\n", + "# Initialization for the model\n", + "rf_model = RandomForestRegressor(n_estimators=100, random_state=42)\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", + " predictions = rf_model.predict(X_test)\n", + "\n", + " mae = mean_absolute_error(y_test, predictions)\n", + " mae_scores.append(mae)\n", + "\n", + "print(f\"Average MAE across folds: {np.mean(mae_scores):.4f}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "importances = rf_model.feature_importances_\n", + "feature_names = X.columns\n", + "feature_importance_df = pd.DataFrame({'Feature': feature_names, 'Importance': importances})\n", + "feature_importance_df = feature_importance_df.sort_values(by='Importance', ascending=False)\n", + "\n", + "plt.figure(figsize=(12, 8))\n", + "sns.barplot(x='Importance', y='Feature', data=feature_importance_df.head(10))\n", + "plt.title('Top 10 Feature Importances')\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "# Using the model from the last fold to show distribution\n", + "plt.figure(figsize=(10, 6))\n", + "sns.histplot(predictions, kde=True, color='green')\n", + "plt.title('Distribution of Predicted Delivery Times')\n", + "plt.xlabel('Predicted Delivery Time (minutes)')\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:\n", + "\n", + "#YOU SHOULD INSTALL THE LIBRARY\n", + "\n", + "%pip install kagglehub catboost lightgbm tqdm -q\n", + "\n", + "from catboost import CatBoostRegressor\n", + "\n", + "kf = KFold(n_splits=5, shuffle=True, random_state=42)\n", + "ensemble_mae_scores = []\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", + " #1:Random Forest\n", + " rf = RandomForestRegressor(n_estimators=100, random_state=42)\n", + " rf.fit(X_train, y_train)\n", + " rf_preds = rf.predict(X_test)\n", + "\n", + " #2:CatBoost\n", + " cb = CatBoostRegressor(iterations=500, learning_rate=0.1, depth=6, verbose=0, random_seed=42)\n", + " cb.fit(X_train, y_train)\n", + " cb_preds = cb.predict(X_test)\n", + "\n", + " # the avg of the prediction\n", + "\n", + " avg_preds = (rf_preds + cb_preds) / 2\n", + "\n", + " mae = mean_absolute_error(y_test, avg_preds)\n", + " ensemble_mae_scores.append(mae)\n", + "\n", + "print(f\"Ensemble Average MAE: {np.mean(ensemble_mae_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/272/Q2.ipynb b/submissions_extracted/272/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..5ead65dacbab23d79b73f0c98502aa553508f0eb --- /dev/null +++ b/submissions_extracted/272/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", + "\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": [ + "#ESSENCIAL libraries you did not import\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", + "import torch.nn.functional as F\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 1. Convert Numpy arrays to PyTorch Tensors\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).view(-1, 1)\n", + "y_test_tensor = torch.tensor(y_test, dtype=torch.float32).view(-1, 1)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 2. Create TensorDataset objects\n", + "#IDK WHY DIDNT YOU IMPORT THESE LIBRARIES, IT'S ESSENSIAL, NOW I WILL NEED TO IMPORT THEM IN EACH ROW... OR MAYBE NEVERMIND I WILL MAKE A NEW CELL FOR IMPORTS\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", + "data_iter = iter(train_loader)\n", + "images_batch, labels_batch = next(data_iter)\n", + "print(f\"Batch Images shape: {images_batch.shape}\")\n", + "print(f\"Batch Labels shape: {labels_batch.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 5. Display sample images\n", + "plt.figure(figsize=(10, 5))\n", + "for i in range(5):\n", + " plt.subplot(1, 5, i+1)\n", + " # from (C, H, W) back to (H, W, C) to plot it.\n", + " img = images_batch[i].permute(1, 2, 0).numpy()\n", + " plt.imshow(img)\n", + " plt.title(f\"Age: {int(labels_batch[i].item())}\")\n", + " plt.axis('off')\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your model class here:\n", + "\n", + "class AgePredictor(nn.Module):\n", + " def __init__(self):\n", + " super(AgePredictor, self).__init__()\n", + "\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, 64)\n", + " self.fc4 = nn.Linear(64, 1) # 1 output - regression\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" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your training loop here:\n", + "def train_epoch(model, loader, criterion, 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", + " optimizer.zero_grad()\n", + " outputs = model(images)\n", + " loss = criterion(outputs, labels)\n", + " loss.backward()\n", + " optimizer.step()\n", + "\n", + " running_loss += loss.item() * images.size(0)\n", + " return running_loss / len(loader.dataset)\n", + "" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your validation loop here:\n", + "def validate_epoch(model, loader, criterion, 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 = criterion(outputs, labels)\n", + " running_loss += loss.item() * images.size(0)\n", + " return running_loss / len(loader.dataset)" + ], + "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().to(device)\n", + "criterion = nn.MSELoss()\n", + "optimizer = torch.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", + "#Importatn, fix the dimetions for multiplication and everything should be working well even the bounas. I did not know how to fix it and im running out of time rn.\n", + "\n", + "train_dataset = TensorDataset(X_train_tensor, y_train_tensor)\n", + "test_dataset = TensorDataset(X_test_tensor, y_test_tensor)\n", + "\n", + "train_losses = []\n", + "val_losses = []\n", + "epochs = 20\n", + "\n", + "\n", + "for epoch in range(epochs):\n", + " train_loss = train_epoch(model, train_loader, criterion, optimizer, device)\n", + " val_loss = validate_epoch(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}/{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, 6))\n", + "plt.plot(range(1, epochs+1), train_losses, label='Training Loss')\n", + "plt.plot(range(1, epochs+1), val_losses, label='Validation Loss')\n", + "plt.xlabel('Epochs')\n", + "plt.ylabel('MSE Loss')\n", + "plt.title('Training and Validation Loss Over Epochs')\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", + "images, labels = next(iter(test_loader))\n", + "images, labels = images.to(device), labels.to(device)\n", + "preds = model(images).detach()\n", + "\n", + "plt.figure(figsize=(15, 7))\n", + "for i in range(5):\n", + " plt.subplot(1, 5, i+1)\n", + " img = images[i].cpu().permute(1, 2, 0).numpy()\n", + " plt.imshow(img)\n", + " plt.title(f\"Act: {int(labels[i].item())}\\nPred: {preds[i].item():.1f}\")\n", + " plt.axis('off')\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/272/Q3.ipynb b/submissions_extracted/272/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..1d82bd03e7995a8a355a1048c173bd674be08474 --- /dev/null +++ b/submissions_extracted/272/Q3.ipynb @@ -0,0 +1,265 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\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": [ + "#imports\n", + "%pip install kagglehub catboost lightgbm tqdm -q\n", + "import pandas as pd\n", + "import os\n", + "from sklearn.preprocessing import StandardScaler\n", + "from sklearn.model_selection import StratifiedKFold\n", + "from catboost import CatBoostClassifier\n", + "from sklearn.metrics import f1_score, accuracy_score\n", + "import numpy as np" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "df = pd.read_csv(os.path.join(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", + "# you guys are repeating the same steps in Q1 file." + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "print(df.isnull().sum())\n", + "\n", + "num_cols = df.select_dtypes(include=['float64', 'int64']).columns\n", + "df[num_cols] = df[num_cols].fillna(df[num_cols].median())\n", + "\n", + "cat_cols = df.select_dtypes(include=['object']).columns\n", + "for col in cat_cols:\n", + " df[col] = df[col].fillna(df[col].mode()[0])\n", + "\n", + "# note: if you are ever asking why is this, it showing this becuase I have already handled it by a diffrent function and run it again" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "df = df.drop_duplicates()\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "categorical_features = df.select_dtypes(include=['object']).columns\n", + "df = pd.get_dummies(df, columns=categorical_features, drop_first=True)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "scaler = StandardScaler()\n", + "features_to_scale = df.drop('Target', axis=1).columns\n", + "df[features_to_scale] = scaler.fit_transform(df[features_to_scale])\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "imbalance = df['Target'].value_counts(normalize=True)\n", + "print(\"the target distribution:\\n\", imbalance)\n", + "\n", + "if imbalance.max() > 0.6:\n", + " print(\"The dataset is imbalanced.\")\n", + "else:\n", + " print(\"The dataset is balanced.\")\n", + "\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" + ], + "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", + "scores = []\n", + "\n", + "# Using F1-score becuase its imbalanced\n", + "is_imbalanced = y.value_counts(normalize=True).min() < 0.4\n", + "\n", + "for train_index, test_index in skf.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", + "\n", + " model = CatBoostClassifier(iterations=500, learning_rate=0.1, depth=6, verbose=0, random_seed=42)\n", + " model.fit(X_train, y_train)\n", + "\n", + " preds = model.predict(X_test)\n", + "\n", + " if is_imbalanced:\n", + " score = f1_score(y_test, preds)\n", + " metric_name = \"F1-Score\"\n", + " else:\n", + " score = accuracy_score(y_test, preds)\n", + " metric_name = \"Accuracy\"\n", + "\n", + " scores.append(score)\n", + "\n", + "print(f\"Average {metric_name} across folds: {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", + "\n", + "importances = model.get_feature_importance()\n", + "feature_names = X.columns\n", + "feature_importance_df = pd.DataFrame({'Feature': feature_names, 'Importance': importances})\n", + "feature_importance_df = feature_importance_df.sort_values(by='Importance', ascending=False)\n", + "\n", + "plt.figure(figsize=(10, 8))\n", + "plt.barh(feature_importance_df['Feature'][:10], feature_importance_df['Importance'][:10])\n", + "plt.gca().invert_yaxis()\n", + "plt.title('Top 10 Feature Importances')\n", + "plt.show()\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "golden_feature = feature_importance_df.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", + "# 1. first we create new golden_X\n", + "X_golden = X[[golden_feature]]\n", + "\n", + "golden_scores = []\n", + "\n", + "# 2. training with kfold again\n", + "for train_index, test_index in skf.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", + " model_golden = CatBoostClassifier(iterations=500, verbose=0, random_seed=42)\n", + " model_golden.fit(X_train, y_train)\n", + "\n", + " preds = model_golden.predict(X_test)\n", + " # Acc becuase the Q saaid want acc\n", + " golden_scores.append(accuracy_score(y_test, preds))\n", + "\n", + "# 3. comparing\n", + "full_model_accuracy = np.mean(scores) if not is_imbalanced else accuracy_score(y, model.predict(X))\n", + "print(f\"Full Model Performance: {full_model_accuracy:.4f}\")\n", + "print(f\"Golden Feature Only Performance: {np.mean(golden_scores):.4f}\")\n", + "#btw, it's taking too long to train.\n", + "#also idk but i think we should have used the 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/273/Q1.ipynb b/submissions_extracted/273/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..d78374ce89a2aa0938b0bcab83acdf2b17abbf0d --- /dev/null +++ b/submissions_extracted/273/Q1.ipynb @@ -0,0 +1,312 @@ +{ + "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", + "\n", + "\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 RandomForestClassifier\n", + "from sklearn.metrics import classification_report, confusion_matrix, accuracy_score\n", + "\n", + "import warnings\n", + "warnings.filterwarnings('ignore')\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", + "path = os.path.join(path, 'Q1_data.csv')\n", + "df = pd.read_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=50, edgecolor='black')\n", + "plt.title('delivery time Distribution')\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 = df.drop(['Order_ID'], axis=1)\n", + "df_clean = df.copy()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: 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", + "missing_data.head(10)\n", + "df_clean = df_clean.dropna(missing_data.columns)\n", + "print(f\"After dropping missing: {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", + " #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_clean)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "cols = df_clean.select_dtypes(include=[\"object\"]).columns\n", + "\n", + "print(\"Categorical Columns:\", list(cols))\n", + "le = LabelEncoder()\n", + "\n", + "# Encode the target column\n", + "label_encoders = {}\n", + "for col in cols:\n", + " le = LabelEncoder()\n", + " df_clean[col] = le.fit_transform(df_clean[col])\n", + "\n", + "df_clean.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\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_clean.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 6: Write your code here:\n", + "Ratio = df_clean['Delivery_Time'].value_counts(normalize=True)\n", + "Ratio\n", + "#as we can see from the graph 📊 above the date is inbalisd" + ], + "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" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:\n", + "# TODO: Split data with stratification (test_size=0.2, random_state=42)\n", + "from sklearn.ensemble import RandomForestRegressor\n", + "from sklearn.metrics import mean_absolute_error\n", + "\n", + "model = RandomForestRegressor(n_estimators=100, max_depth=20, random_state=42, n_jobs=-1)\n", + "kfold = KFold(\n", + " n_splits=5,\n", + " shuffle=True,\n", + " random_state=42\n", + ")\n", + "\n", + "msn_s = []\n", + "\n", + "for train_idx, val_idx in kfold.split(X):\n", + " X_fold_train = X[train_idx]\n", + " X_fold_val = X[val_idx]\n", + "\n", + " y_fold_train = y.iloc[train_idx]\n", + " y_fold_val = y.iloc[val_idx]\n", + "\n", + "\n", + "\n", + " model.fit(X_fold_train, y_fold_train)\n", + " y_fold_pred = model.predict(X_fold_val)\n", + "\n", + " f1 = mean_absolute_error(y_fold_val, y_fold_pred, pos_label=1)\n", + " msn_s.append(f1)\n", + "mae_scores = np.array(msn_s)\n", + "\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": [ + "\n", + "# Task 1: Write your code here:\n", + "\n", + "coeffs = model.coef_\n", + "\n", + "\n", + "fig, axes = plt.subplots(1, 1, figsize=(15, 6))\n", + "axes = axes.flatten()\n", + "features = X.columns\n", + "i =0\n", + "for coef in 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\"random forst 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": [], + "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('time')\n", + "plt.ylabel('delivery')\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/273/Q2.ipynb b/submissions_extracted/273/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..0284e65da3e747b4dc7c1094633a7c0fbe9926c6 --- /dev/null +++ b/submissions_extracted/273/Q2.ipynb @@ -0,0 +1,404 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\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", + "# 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", + "\n", + "from PIL import Image\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", + "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", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 3. Create DataLoaders\n", + "\n", + "# TODO: Create DataLoaders with batch_size=32\n", + "# [HINT]: shuffle=True for training, shuffle=False for testing\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", + "\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", + " 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 output layer: hidden_dim -> 1 (single value for regression)\n", + " self.layer3 = nn.Linear(hidden_dim,hidden_dim)\n", + "\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", + "\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: Second hidden layer with ReLU\n", + " a3 = self.relu(self.layer3(a2))\n", + "\n", + " # TODO: Output layer (no activation for regression)\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", + " # TODO: 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", + " # TODO: 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", + " # 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", + " optimizer.zero_grad() # Clear previous gradients\n", + "\n", + " # Step 2: Compute gradients (backward pass)\n", + " loss.backward()\n", + "\n", + " # Step 3: Update model parameters\n", + " optimizer.step() # Compute gradients\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", + " # TODO: Set the model to evaluation mode\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.view(X_batch.size(0), -1).to(device)\n", + " y_batch = y_batch.to(device)\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", + "device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\n", + "\n", + "input_dim = 3 *36* 36 # Number of tabular features\n", + "print(input_dim)\n", + "hidden_dim = 32 # Design choice (feel free to experiment!)\n", + "\n", + "# TODO: Instantiate the model and move it to the device\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.001\n", + "\n", + "criterion = nn.MSELoss()\n", + "\n", + "# TODO: Define optimizer - use AdamW with the model parameters and learning rate\n", + "optimizer = AdamW(model.parameters(),learning_rate)\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 5: Start training for 20 epochs:\n", + "\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, train_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:\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", + "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", + "\n", + "\n", + "# Move tensors back to CPU for plotting\n", + "images = images.cpu()\n", + "labels = labels.cpu()\n", + "outputs = outputs.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].permute(1, 2, 0), cmap='gray')\n", + " plt.title(f\"True: {labels[i]} | Pred: {outputs[i].numpy()}\")\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/273/Q3.ipynb b/submissions_extracted/273/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..3de51bbf75d288ddda4e2ccac70cc0712f065b08 --- /dev/null +++ b/submissions_extracted/273/Q3.ipynb @@ -0,0 +1,291 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "\n", + "import numpy as np\n", + "import pandas as pd\n", + "import matplotlib.pyplot as plt\n", + "import os\n", + "\n", + "\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 RandomForestClassifier\n", + "from sklearn.metrics import classification_report, confusion_matrix, accuracy_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": [ + "path = os.path.join(path, 'Q3_data.csv')\n", + "df = pd.read_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", + "# 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", + "df = df.fillna(df[missing_data.Column].mean())\n", + "print(f\"After dropping missing : {df.shape}\")" + ], + "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", + "cols = df.select_dtypes(include=[\"object\"]).columns\n", + "\n", + "print(\"Categorical Columns:\", list(cols))\n", + "le = LabelEncoder()\n", + "\n", + "# Encode the target column\n", + "label_encoders = {}\n", + "for col in 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 4: Write your code here:\n", + "\n", + "from sklearn.preprocessing import StandardScaler\n", + "\n", + "numerical_cols = df.select_dtypes(include=[\"int64\", \"float64\"]).columns.drop(\"Target\") # DON'T SCALE THE TARGET\n", + "numerical_cols\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", + "plt.figure(figsize=(10, 5))\n", + "plt.hist(df['Target'], bins=50, edgecolor='black')\n", + "plt.title('delivery time Distribution')\n", + "plt.xlabel('Target')\n", + "plt.ylabel('fr')\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": [ + "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 # i dont know why dose it not import\n", + "from sklearn.model_selection import StratifiedKFold\n", + "from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:\n", + "\n", + "model = CatBoostClassifier(n_estimators=100, max_depth=20, random_state=42, n_jobs=-1)\n", + "kfold = KFold(\n", + " n_splits=5,\n", + " shuffle=True,\n", + " random_state=42\n", + ")\n", + "\n", + "msn_s = []\n", + "\n", + "for train_idx, val_idx in StratifiedKFold.split(X.y):\n", + " X_fold_train = X[train_idx]\n", + " X_fold_val = X[val_idx]\n", + "\n", + " y_fold_train = y.iloc[train_idx]\n", + " y_fold_val = y.iloc[val_idx]\n", + "\n", + "\n", + "\n", + " model.fit(X_fold_train, y_fold_train)\n", + " y_fold_pred = model.predict(X_fold_val)\n", + "\n", + " f1 = f1_score(y_fold_val, y_fold_pred, pos_label=1)\n", + " msn_s.append(f1)\n", + "mae_scores = np.array(msn_s)\n", + "\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", + "coeffs = model.coef_\n", + "\n", + "\n", + "fig, axes = plt.subplots(1, 1, figsize=(15, 6))\n", + "axes = axes.flatten()\n", + "features = X.columns\n", + "i =0\n", + "for coef in 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\"random forst 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", + "i cant becase of the CatBoostClassifier" + ], + "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/274/Q1.ipynb b/submissions_extracted/274/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..87050934acdb5f984bf758f1e1658c9089875a9c --- /dev/null +++ b/submissions_extracted/274/Q1.ipynb @@ -0,0 +1,456 @@ +{ + "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", + "# Load the dataset\n", + "csv_path = os.path.join(path, 'Q1_data.csv')\n", + "data = pd.read_csv(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 5: Write your code here:\n", + "def check_target_distribution(df, target_column):\n", + " df[target_column].hist(bins=20, edgecolor='yellow')\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(data, \"Delivery_Time\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "df = data.drop('Order_ID', axis=1)\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "df.isnull().sum(0)\n", + "\n", + "from sklearn.preprocessing import LabelEncoder\n", + "\n", + "col_with_missing_values = [\"Weather\" , \"Traffic_Level\" , \"Time_of_Day\" , \"Courier_Experience_yrs\"]\n", + "\n", + "for col in col_with_missing_values:\n", + " df[col] = df[col].fillna('unknown')\n", + "\n", + "\n", + "df = df.dropna(subset=[\"Delivery_Time\"])\n", + "\n", + "df.head()\n", + "df.isnull().sum()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "\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", + " df.drop_duplicates(inplace=True)\n", + " print(\"Duplicates Dropped.\")\n", + "\n", + " else:\n", + " print(\"No Duplicate Samples Found.\")\n", + "\n", + "check_duplicates(df)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "df.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "df." + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "df.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [], + "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", + " le = LabelEncoder()\n", + " df[col] = le.fit_transform(df[[col]])\n", + "\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "df['Courier_Experience_yrs'] = df['Courier_Experience_yrs'].replace(\"unknown\" , 0.0)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "df['Courier_Experience_yrs']" + ], + "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:" + ], + "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": [ + "from sklearn.model_selection import StratifiedKFold\n", + "from sklearn.ensemble import RandomForestRegressor\n", + "from sklearn.metrics import mean_squared_error" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:\n", + "model = RandomForestRegressor(max_depth=5)\n", + "n_plits = 4\n", + "skf = StratifiedKFold(n_splits=n_plits, shuffle=True, random_state=42)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "mse = []" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "df.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "for fold_idx, (train_index, test_index) in enumerate(skf.split(X, y)):\n", + "\n", + " print(f\"\\nFold {fold_idx + 1}/{n_plits}\")\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", + " 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", + " mse.append(mean_squared_error(y_test, y_pred))" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Gather importances from the models (from the last fold)\n", + "importances = {\n", + " \"RandomForest\" : model.feature_importances_\n", + "}\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", + "df['Delivery_Time'].hist()" + ], + "execution_count": null, + "outputs": [] + }, + { + "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, 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 catboost import CatBoostRegressor\n", + "\n", + "import warnings\n", + "warnings.filterwarnings('ignore')\n", + "\n", + "rf_model = RandomForestRegressor(max_depth=5, random_state=42)\n", + "cat_model = CatBoostRegressor(iterations=100, learning_rate=0.1, depth=5, random_seed=42, verbose=0)\n", + "\n", + "mae_scores = []\n", + "\n", + "n_splits = 4\n", + "kf = KFold(n_splits=n_splits, shuffle=True, random_state=42)\n", + "\n", + "categorical_features_indices = np.where(X.dtypes == 'object')[0]\n", + "\n", + "for fold_idx, (train_index, test_index) in enumerate(kf.split(X, y)):\n", + " print(f\"\\nFold {fold_idx + 1}/{n_splits}\")\n", + "\n", + " # 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", + " print(\"Training RandomForest...\")\n", + " rf_model.fit(X_train, y_train)\n", + " rf_preds = rf_model.predict(X_test)\n", + "\n", + " print(\"Training CatBoost...\")\n", + " cat_features = X_train.select_dtypes(include=['object']).columns.tolist()\n", + " if cat_features:\n", + " cat_model.fit(X_train, y_train, cat_features=cat_features, verbose=0)\n", + " else:\n", + " cat_model.fit(X_train, y_train, verbose=0)\n", + " cat_preds = cat_model.predict(X_test)\n", + "\n", + " # Average predictions\n", + " avg_preds = (rf_preds + cat_preds) / 2\n", + "\n", + " # Calculate MAE\n", + " mae = mean_absolute_error(y_test, avg_preds)\n", + " mae_scores.append(mae)\n", + " print(f\"MAE for Fold {fold_idx + 1}: {mae:.2f}\")\n", + "\n", + "print(f\"\\nAverage MAE across all folds: {np.mean(mae_scores):.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/274/Q2.ipynb b/submissions_extracted/274/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..0c30f41e753a4670705e30e9be99ed9e91b04228 --- /dev/null +++ b/submissions_extracted/274/Q2.ipynb @@ -0,0 +1,354 @@ +{ + "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": [ + "# 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.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", + "# Create TensorDatasets for training and testing\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", + "# 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(\"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": [ + "num_images = 5\n", + "\n", + "plt.figure(figsize=(15, 5))\n", + "for i in range(num_images):\n", + " # Get image and label\n", + " image = X_batch[i].permute(1, 2, 0).numpy() # Convert from (C, H, W) to (H, W, C)\n", + " label = y_batch[i].item()\n", + "\n", + " plt.subplot(1, num_images, i + 1)\n", + " plt.imshow(image)\n", + " plt.title(f\"Age: {label}\")\n", + " plt.axis('off')\n", + "plt.suptitle('Sample Training Images and their Ages')\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", + " # 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": [ + "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.float().unsqueeze(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": [ + "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.float().unsqueeze(1).to(device)\n", + "\n", + " outputs = model(X_batch)\n", + " loss = criterion(outputs, y_batch)\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": [ + "device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n", + "\n", + "input_dim = 36 * 36 * 3\n", + "hidden_dim = 14\n", + "output_dim = 1\n", + "\n", + "model = NN4Layer(input_dim, hidden_dim, output_dim).to(device)\n", + "\n", + "print(\"Model Architecture:\\n\")\n", + "print(model)\n", + "\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\n", + "\n", + "criterion = nn.MSELoss()\n", + "\n", + "# W ADAM\n", + "optimizer = AdamW(model.parameters(), learning_rate)\n", + "\n", + "\n", + "train_losses = []\n", + "val_losses = []\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", + " 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": [], + "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')\n", + "plt.plot(range(1, num_epochs + 1), val_losses, label='Validation Loss')\n", + "plt.xlabel('Epoch')\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": [], + "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/274/Q3.ipynb b/submissions_extracted/274/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..4a979ad6e3ebc59c4f5971c5d47df2117f66a315 --- /dev/null +++ b/submissions_extracted/274/Q3.ipynb @@ -0,0 +1,330 @@ +{ + "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", + "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", + "columns_with_nan = df.columns[df.isnull().any()].tolist()\n", + "if 'Target' in columns_with_nan:\n", + " columns_with_nan.remove('Target')\n", + "\n", + "print(f\"Columns with missing values (excluding 'Target'): {columns_with_nan}\")\n", + "\n", + "for col in columns_with_nan:\n", + " median_val = df[col].median()\n", + " df[col].fillna(median_val, inplace=True)\n", + "\n", + "print(\"Missing values after median imputation:\")\n", + "print(df[columns_with_nan].isnull().sum().sum())\n", + "\n", + "for col in columns_with_nan:\n", + " median_val = df[col].median()\n", + " df[col] = df[col].fillna(median_val)\n", + "\n", + "print(\"Missing values after median imputation:\")\n", + "print(df[columns_with_nan].isnull().sum().sum())" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "print(f\"Number of duplicate rows before removal: {df.duplicated().sum()}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "import pandas as pd\n", + "\n", + "d_columns_int = [col for col in df.columns if col.startswith('D_') and df[col].dtype == 'int64']\n", + "\n", + "print(f\"'D_'-prefixed integer columns: {d_columns_int}\")\n", + "\n", + "categorical_d_columns = []\n", + "threshold_unique_values = min(50, int(len(df) * 0.05)) # Example: max 50 unique values or 5% of total rows\n", + "\n", + "print(\"Candidate 'D_'-prefixed integer columns and their unique value counts:\")\n", + "for col in d_columns_int:\n", + " unique_count = df[col].nunique()\n", + " print(f\" Column '{col}': {unique_count} unique values\")\n", + " if unique_count <= threshold_unique_values:\n", + " categorical_d_columns.append(col)\n", + "\n", + "print(f\"\\nColumns identified as categorical (unique values <= {threshold_unique_values}): {categorical_d_columns}\")\n", + "\n", + "for col in categorical_d_columns:\n", + " df[col] = df[col].astype('category')\n", + "\n", + "print(\"Data types of identified categorical 'D_'-prefixed columns after conversion:\")\n", + "print(df[categorical_d_columns].dtypes)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "import numpy as np\n", + "from sklearn.preprocessing import StandardScaler\n", + "\n", + "numerical_cols = df.select_dtypes(include=np.number).columns.tolist()\n", + "\n", + "if 'Target' in numerical_cols:\n", + " numerical_cols.remove('Target')\n", + "\n", + "numerical_features_for_scaling = df.select_dtypes(include=np.number).columns.tolist()\n", + "if 'Target' in numerical_features_for_scaling:\n", + " numerical_features_for_scaling.remove('Target')\n", + "\n", + "print(f\"Numerical columns to be scaled (excluding 'Target'): {numerical_features_for_scaling}\")\n", + "\n", + "scaler = StandardScaler()\n", + "df[numerical_features_for_scaling] = scaler.fit_transform(df[numerical_features_for_scaling])\n", + "\n", + "print(\"Numerical features after scaling (first 5 rows):\")\n", + "print(df[numerical_features_for_scaling].head())" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "target_counts = df['Target'].value_counts()\n", + "target_percentages = df['Target'].value_counts(normalize=True) * 100\n", + "\n", + "print(\"Target variable value counts:\\n\", target_counts)\n", + "print(\"\\nTarget variable percentages:\\n\", target_percentages)\n", + "\n", + "if target_percentages.min() < 30:\n", + " print(\"\\nConclusion: The target variable 'Target' appears to be imbalanced.\")\n", + "else:\n", + " print(\"\\nConclusion: The target variable 'Target' appears to be balanced.\")" + ], + "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", + "from sklearn.metrics import f1_score\n", + "import numpy as np\n", + "\n", + "categorical_features_indices = [X.columns.get_loc(col) for col in X.select_dtypes(include='category').columns]\n", + "\n", + "skf = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)\n", + "f1_scores = []\n", + "\n", + "for fold, (train_index, val_index) in enumerate(skf.split(X, y)):\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 = CatBoostClassifier(\n", + " iterations=100,\n", + " learning_rate=0.1,\n", + " depth=6,\n", + " l2_leaf_reg=3,\n", + " loss_function='Logloss',\n", + " eval_metric='F1',\n", + " random_seed=42,\n", + " verbose=0,\n", + " cat_features=categorical_features_indices\n", + " )\n", + "\n", + " model.fit(X_train, y_train, early_stopping_rounds=10, eval_set=(X_val, y_val), verbose=0)\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+1} F1 Score: {f1:.4f}\")\n", + "\n", + "print(f\"\\nAveraged F1 Score across all folds: {np.mean(f1_scores):.4f}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "import matplotlib.pyplot as plt\n", + "\n", + "feature_importances = model.get_feature_importance()\n", + "feature_names = X.columns\n", + "\n", + "importance_df = pd.Series(feature_importances, index=feature_names)\n", + "\n", + "sorted_importance_df = importance_df.sort_values(ascending=False)\n", + "\n", + "plt.figure(figsize=(12, 8))\n", + "sorted_importance_df.head(20).plot(kind='barh')\n", + "plt.title('Top 20 Feature Importances')\n", + "plt.xlabel('Importance')\n", + "plt.ylabel('Feature')\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 = sorted_importance_df.index[0]\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", + "\n", + "print(f\"Shape of new features (X_golden) with only '{golden_feature}': {X_golden.shape}\")\n", + "print(f\"First 5 rows of X_golden:\\n{X_golden.head()}\")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "skf_golden = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)\n", + "f1_scores_golden = []\n", + "\n", + "for fold, (train_index, val_index) in enumerate(skf_golden.split(X_golden, y)):\n", + " X_train_golden, X_val_golden = X_golden.iloc[train_index], X_golden.iloc[val_index]\n", + " y_train, y_val = y.iloc[train_index], y.iloc[val_index]\n", + "\n", + " model_golden = CatBoostClassifier(\n", + " iterations=100, # Same as full model\n", + " learning_rate=0.1,\n", + " depth=6,\n", + " l2_leaf_reg=3,\n", + " loss_function='Logloss',\n", + " eval_metric='F1',\n", + " random_seed=42,\n", + " verbose=0,\n", + " cat_features=[]\n", + " )\n", + "\n", + " model_golden.fit(X_train_golden, y_train, early_stopping_rounds=10, eval_set=(X_val_golden, y_val), verbose=0)\n", + " y_pred_golden = model_golden.predict(X_val_golden)\n", + " f1_golden = f1_score(y_val, y_pred_golden)\n", + " f1_scores_golden.append(f1_golden)\n", + " print(f\"Fold {fold+1} F1 Score (Golden Feature Only): {f1_golden:.4f}\")\n", + "\n", + "averaged_f1_golden = np.mean(f1_scores_golden)\n", + "print(f\"\\nAveraged F1 Score (Golden Feature Only) across all folds: {averaged_f1_golden:.4f}\")\n", + "print(f\"Averaged F1 Score (Full Model) across all folds: {np.mean(f1_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/275/Q1.ipynb b/submissions_extracted/275/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..cf795e5300cccae7a86acf974fa92287fb3cf3fb --- /dev/null +++ b/submissions_extracted/275/Q1.ipynb @@ -0,0 +1,431 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "import kagglehub\n", + "import os\n", + "import pandas as pd\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", + "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", + "# 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", + "path = os.path.join(path, 'Q1_data.csv')\n", + "df = pd.read_csv(path)\n", + "\n", + "print(f\"Dataset shape: {df.shape}\")\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", + "plt.figure(figsize=(10, 5))\n", + "plt.hist(df['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": [ + "# Task 1: Write your code here:\n", + "df = 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", + "\n", + "print(\"Missing Data Analysis:\")\n", + "missing_data.head(10)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "df['Delivery_Time'] = df['Delivery_Time'].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('none')\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", + " # if theres any dublicts df.drop_duplicates(inplace=True)\n", + "\n", + "check_duplicates(df)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "check_duplicates(df)" + ], + "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", + "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[col] = le.fit_transform(df[col].astype(str))\n", + "\n", + "df.head()\n", + "\n", + "#print('data before encoding:\\n', categories) #show before encoding\n", + "\n", + "#onehot_encoder = OneHotEncoder(sparse_output=False) # Instantiate OneHotEncoder\n", + "#data_onehot_encoded = onehot_encoder.fit_transform(categories) # 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 MinMaxScaler, StandardScaler\n", + "numerical_cols = df.select_dtypes(include=[\"number\"]).columns.drop(\"Delivery_Time\")\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", + "# we dont have to check for balance because its reggration but we can check for skweenes to see how 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, \"Delivery_Time\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "X = df.drop(columns=['Delivery_Time'])\n", + "y = df['Delivery_Time']\n", + "X_train, X_test, y_train, y_test = train_test_split(\n", + " X, y, test_size=0.2, random_state=42\n", + ")\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", + "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", + "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", + "\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": [ + "\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", + " 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" + ], + "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", + "feature_importance = pd.DataFrame({\n", + " 'feature': X.columns,\n", + " 'importance': model.feature_importances_\n", + "}).sort_values('importance', ascending=False)\n", + "\n", + "plt.figure(figsize=(30, 10))\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 (Ground Truth)\")\n", + "plt.ylabel(\"Predicted \")\n", + "plt.title(\"Linear Regression: Predictions vs Ground Truth\")\n", + "plt.grid(True)\n", + "\n", + "plt.tight_layout()\n", + "plt.show()\n", + "# sorry for the model ):" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "! pip install catboost" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:\n", + "from sklearn.ensemble import RandomForestClassifier\n", + "\n", + "from catboost import CatBoostRegressor\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", + "models = {\n", + " \"Random Forest Regressor\": RandomForestRegressor(n_estimators=200),\n", + " \"CatBoost\": CatBoostRegressor(verbose=0)\n", + "}\n", + "\n", + "all_results = {}\n", + "\n", + "for name in models:\n", + " all_results[name] = {'mse': [], '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", + "\n", + "\n", + " mae = mean_absolute_error(y_test, y_pred)\n", + "\n", + "\n", + " # Store results\n", + " all_results[model_name][\"mae\"].append(mae)\n", + "# i dont have the time but itheres the models i im suppost to use\n", + "#from catboost import CatBoostRegressor\n", + "#model = CatBoostRegressor(iterations=100, learning_rate=0.1, random_state=42, verbose=False # عشان ما يطلع logs)\n", + "# and i have to pip install it like i did in the other qustion when i had the time" + ], + "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/275/Q2.ipynb b/submissions_extracted/275/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..98731431b57c1073af618d94109cb78da4c3fafd --- /dev/null +++ b/submissions_extracted/275/Q2.ipynb @@ -0,0 +1,381 @@ +{ + "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", + "\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", + "# 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" + ], + "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))\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", + "# 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", + " 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 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", + " 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", + " a3 = self.relu(self.layer2(a2))\n", + "\n", + " # Output layer (regression output)\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.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", + "# Set up the device(use GPU if available, otherwise CPU\n", + "device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n", + "# Model parameters\n", + "input_dim = X_train.shape[1] # Number of 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", + "\n", + "num_epochs = 20\n", + "learning_rate = 0.001\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!')\n", + "\n", + "#i got this eror so i think i hafe to reshibe it by ( view ) RuntimeError: mat1 and mat2 shapes cannot be multiplied (3456x36 and 3x64)\n", + "\n", + "mat1 = mat1.view(3456x36 )\n", + "mat2 = mat2.view(3x64)\n", + "\n", + "# Flatten all except batch اوتوماتكلي يختار الرقم اللي نحتاجه\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:\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/275/Q3.ipynb b/submissions_extracted/275/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..a962cf7a1a7584ecdf5adb0c2dde9f3141ffc245 --- /dev/null +++ b/submissions_extracted/275/Q3.ipynb @@ -0,0 +1,377 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "import kagglehub\n", + "import kagglehub\n", + "import os\n", + "import pandas as pd\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", + "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", + "# Download latest version\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", + "path = os.path.join(path, 'Q3_data.csv')\n", + "df = pd.read_csv(path)\n", + "\n", + "print(f\"Dataset shape: {df.shape}\")\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": [ + "df.info()\n", + "# Task 3: Write your code here:" + ], + "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": [ + "missing_cols = missing_data[missing_data['Missing_Percentage'] > 80]['Column']\n", + "df.drop(columns=missing_cols, inplace=True)\n", + "# coloms that has more then 80 i guess its better to drop them because imputing thim dosnt make since" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Fill missing values for the remaining columns\n", + "for col in df.columns:\n", + " if df[col].isnull().sum() > 0:\n", + " df[col].fillna(df[col].median(), inplace=True)" + ], + "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", + " # if theres any dublicts df.drop_duplicates(inplace=True)\n", + "\n", + "check_duplicates(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", + "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[col] = le.fit_transform(df[col].astype(str))\n", + "\n", + "df.head()\n", + "#theres no catigoracle coloms in our data" + ], + "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:\n", + "from sklearn.preprocessing import MinMaxScaler, StandardScaler\n", + "numerical_cols = df.select_dtypes(include=[\"number\"]).columns.drop(\"Target\") # i didnot scale the target because its wrong and it will cause leacage then the moodl is gonna cheat\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 5: 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, \"Target\")\n", + "#the results shows huge inbalance we need stratifid k fold to make sure its distrubuted right" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "X = df.drop(columns=['Target'])\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": [ + "# Task 2,3,4,5: Write your code here:\n", + "! pip install catboost\n", + "\n", + "from catboost import CatBoostClassifier\n", + "model = CatBoostClassifier(\n", + " iterations=100,\n", + " learning_rate=0.1,\n", + " random_state=42,\n", + " verbose=False # عشان ما يطلع logs\n", + ")\n", + "\n", + "model.fit(X_train, y_train)\n", + "print(\"Model trained!\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "from sklearn.model_selection import KFold\n", + "from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score\n", + "y_pred = model.predict(X_test)\n", + "\n", + "print(f\"Accuracy: {accuracy_score(y_test, y_pred):.4f}\\n\")\n", + "print(f\"f1_score: {f1_score(y_test, y_pred):.4f}\\n\")\n", + "# f1 = f1_score(y_fold_val, y_fold_pred, average='macro')\n", + "print(classification_report(y_test, y_pred))\n", + "# i printed the whole report if you want it" + ], + "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=(90, 40))\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", + "# this may not be the brettist plot but u can see all of the feachers if you click on them (it does the gob)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "#P_2 and D_42 and D_45 are one of rhe most importanat features\n", + "# the golden feature is P_2\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:\n", + "X = df['P_2']" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# im supossed to do it in the golden feature but there is no time\n", + "\n", + "from sklearn.model_selection import KFold\n", + "from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score\n", + "\n", + "kfold = KFold(n_splits=5, shuffle=True, random_state=42)\n", + "\n", + "accuracy_scores = []\n", + "precision_scores = []\n", + "recall_scores = []\n", + "f1_scores = []\n", + "\n", + "for fold, (train_idx, val_idx) in enumerate(kfold.split(X_train), 1):\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", + " acc = accuracy_score(y_fold_val, y_fold_pred)\n", + " prec = precision_score(y_fold_val, y_fold_pred, average='macro')\n", + " rec = recall_score(y_fold_val, y_fold_pred, average='macro')\n", + " f1 = f1_score(y_fold_val, y_fold_pred, average='macro')\n", + "\n", + " accuracy_scores.append(acc)\n", + " precision_scores.append(prec)\n", + " recall_scores.append(rec)\n", + " f1_scores.append(f1)\n", + "\n", + " print(f\"Fold {fold} - Accuracy: {acc:.4f}, Precision: {prec:.4f}, Recall: {rec:.4f}, F1: {f1:.4f}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "from sklearn.model_selection import KFold\n", + "from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score\n", + "y_pred = model.predict(X_test)\n", + "\n", + "print(f\"Accuracy: {accuracy_score(y_test, y_pred):.4f}\\n\")\n", + "print(f\"f1_score: {f1_score(y_test, y_pred):.4f}\\n\")\n", + "# f1 = f1_score(y_fold_val, y_fold_pred, average='macro')\n", + "print(classification_report(y_test, y_pred))\n", + "# i printed the whole report if you want it" + ], + "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/276/Q1.ipynb b/submissions_extracted/276/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..5c5d9ef83bd6516e066505d6cfb5288384ded625 --- /dev/null +++ b/submissions_extracted/276/Q1.ipynb @@ -0,0 +1,632 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# import needed lib\n", + "import kagglehub\n", + "import os\n", + "import pandas as pd\n", + "import numpy as np\n", + "import plotly.express as px\n", + "\n", + "state = 42" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "\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_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", + "y_dist = px.histogram(\n", + " df,\n", + " x=\"Delivery_Time\"\n", + ")\n", + "y_dist.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "df.drop(\"Order_ID\", axis=1, inplace= True)\n", + "\n", + "# confirm\n", + "df.columns" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "\n", + "# cheack nulls\n", + "display(df.isnull().sum().sort_values(ascending=False))" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# clooser look at ctagoral ones\n", + "df[\"Time_of_Day\"].value_counts(), df[\"Weather\"].value_counts(), df[\"Traffic_Level\"].value_counts()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# clooser look at numaric ones\n", + "df[[\"Delivery_Time\", \"Courier_Experience_yrs\"]].describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Actions\n", + "# for ctagoral :\n", + "# fillna with \"Unkown\"\n", + "# except the 'Weather' with \"Clear\" (assume it in saudi + 700 compare to 100 is a huge)\n", + "# for numaric :\n", + "# 'Courier_Experience_yrs' fillna with mean\n", + "# but for the 'Delivery_Time' dropna since we cant fill it with approxmation it will heart our model very much\n", + "\n", + "\n", + "\n", + "df[\"Time_of_Day\"] = df[\"Time_of_Day\"].fillna(\"Unkown\")\n", + "df[\"Traffic_Level\"] = df[\"Traffic_Level\"].fillna(\"Unkown\")\n", + "df[\"Weather\"] = df[\"Weather\"].fillna(df[\"Weather\"].mode()[0])\n", + "\n", + "\n", + "df[\"Courier_Experience_yrs\"] = df[\"Courier_Experience_yrs\"].fillna(df[\"Courier_Experience_yrs\"].mean())\n", + "\n", + "df = df.dropna(subset=[\"Delivery_Time\"])\n", + "\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# confirm\n", + "display(df.isnull().sum().sort_values(ascending=False))" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "df[\"Time_of_Day\"].value_counts(), df[\"Weather\"].value_counts(), df[\"Traffic_Level\"].value_counts()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "df[[\"Delivery_Time\", \"Courier_Experience_yrs\"]].describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "\n", + "# cheack\n", + "df.duplicated().sum()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# action drop them\n", + "df = df.drop_duplicates()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# confirm\n", + "df.duplicated().sum()" + ], + "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 OneHotEncoder #import OneHotEncoder\n", + "\n", + "onehot_encoder = OneHotEncoder(sparse_output=False)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Weather\n", + "one_hot = onehot_encoder.fit_transform(df[[\"Weather\"]]) # save the array of one hot\n", + "\n", + "print('\\ncol befor encoding:\\n', df[\"Weather\"]) # get the befor shape\n", + "for i in range(df[\"Weather\"].nunique()) :\n", + " df[f\"Weather_{i}\"] = one_hot[:,i] # assign each appropriate one hot columns with numbered column in df\n", + "\n", + "\n", + "\n", + "df[[f\"Weather_{i}\"for i in range(df[\"Weather\"].nunique())]] # show the new columns\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "df = df.drop(\"Weather\", axis=1)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Traffic_Level\n", + "one_hot = onehot_encoder.fit_transform(df[[\"Traffic_Level\"]]) # save the array of one hot\n", + "\n", + "print('\\ncol befor encoding:\\n', df[\"Traffic_Level\"]) # get the befor shape\n", + "for i in range(df[\"Traffic_Level\"].nunique()) :\n", + " df[f\"Traffic_Level_{i}\"] = one_hot[:,i] # assign each appropriate one hot columns with numbered column in df\n", + "\n", + "\n", + "\n", + "df[[f\"Traffic_Level_{i}\"for i in range(df[\"Traffic_Level\"].nunique())]] # show the new columns\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "df = df.drop(\"Traffic_Level\", axis=1)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Time_of_Day\n", + "one_hot = onehot_encoder.fit_transform(df[[\"Time_of_Day\"]]) # save the array of one hot\n", + "\n", + "print('\\ncol befor encoding:\\n', df[\"Time_of_Day\"]) # get the befor shape\n", + "for i in range(df[\"Time_of_Day\"].nunique()) :\n", + " df[f\"Time_of_Day_{i}\"] = one_hot[:,i] # assign each appropriate one hot columns with numbered column in df\n", + "\n", + "\n", + "\n", + "df[[f\"Time_of_Day_{i}\"for i in range(df[\"Time_of_Day\"].nunique())]] # show the new columns\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "\n", + "df = df.drop(\"Time_of_Day\", axis=1)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "\n", + "\n", + "# Vehicle_Type\n", + "one_hot = onehot_encoder.fit_transform(df[[\"Vehicle_Type\"]]) # save the array of one hot\n", + "\n", + "print('\\ncol befor encoding:\\n', df[\"Vehicle_Type\"]) # get the befor shape\n", + "for i in range(df[\"Vehicle_Type\"].nunique()) :\n", + " df[f\"Vehicle_Type_{i}\"] = one_hot[:,i] # assign each appropriate one hot columns with numbered column in df\n", + "\n", + "\n", + "\n", + "df[[f\"Vehicle_Type_{i}\"for i in range(df[\"Vehicle_Type\"].nunique())]] # show the new columns\n", + "\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "df = df.drop(\"Vehicle_Type\", axis=1)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# confirm\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "\n", + "# split the target and the features before scalling (so we dont scale the target)\n", + "\n", + "features = [col for col in df.columns if col != 'Delivery_Time']\n", + "\n", + "X = df[features]\n", + "y = df[\"Delivery_Time\"]" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "from sklearn.preprocessing import StandardScaler\n", + "scaler = StandardScaler()\n", + "df_scaled = scaler.fit_transform(df)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# confirm before and after\n", + "print(df.head().values) # before\n", + "print(df_scaled[0:5]) # after" + ], + "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", + "from sklearn.model_selection import train_test_split\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=state, # reproducible output\n", + " shuffle=True # representative splits\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)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:\n", + "\n", + "from sklearn.ensemble import RandomForestRegressor\n", + "\n", + "model = RandomForestRegressor(random_state=state, n_estimators=200)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "from sklearn.model_selection import KFold\n", + "from sklearn.metrics import mean_absolute_error\n", + "\n", + "# Define K-Fold Cross Validation\n", + "kf = KFold(n_splits=5, shuffle=True, random_state=42)\n", + "\n", + "\n", + "maes = []\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", + " # Training\n", + " model.fit(X_train, y_train)\n", + "\n", + " # Predict\n", + " y_pred = model.predict(X_test)\n", + "\n", + " # evaluation matrecs\n", + " mae = mean_absolute_error(y_test, y_pred)\n", + "\n", + " maes.append(mae)\n", + "\n", + "maes = np.array(maes)\n", + "avg_mse = maes.mean()\n", + "print(avg_mse)\n", + "\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "\n", + "import matplotlib.pyplot as plt\n", + "\n", + "importance = pd.DataFrame({\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:\n", + "\n", + "# Y_Hat\n", + "plt.figure(figsize=(10, 6))\n", + "plt.hist(y_pred)\n", + "\n", + "plt.title('predected y_hat distrbuation')\n", + "\n", + "plt.tight_layout()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# THE ORIGIONAL Y\n", + "y_dist.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:\n", + "\n", + "# why not try another state ?? I will do it :)\n", + "\n", + "state_1, state_2 = 220,112\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "from sklearn.ensemble import RandomForestRegressor\n", + "\n", + "model_1 = RandomForestRegressor(random_state=state_1, n_estimators=200)\n", + "model_2 = RandomForestRegressor(random_state=state_2, n_estimators=200)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "kf = KFold(n_splits=5, shuffle=True, random_state=42)\n", + "\n", + "maes = []\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", + " # Training\n", + " model_1.fit(X_train, y_train)\n", + " model_2.fit(X_train, y_train)\n", + "\n", + " # Predict\n", + " y_pred_1 = model_1.predict(X_test)\n", + " y_pred_2 = model_2.predict(X_test)\n", + "\n", + "\n", + " avg_y_hat = (y_pred_1 + y_pred_2) / 2\n", + "\n", + " # evaluation matrecs\n", + " mae = mean_absolute_error(y_test, avg_y_hat)\n", + "\n", + " maes.append(mae)\n", + "\n", + "maes = np.array(maes)\n", + "avg_mse = maes.mean()\n", + "print(avg_mse)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# not much diffrent (maybe worest than the singal one) but first time i think in that way when building a model\n", + "print(\"DONE!!\")" + ], + "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/276/Q2.ipynb b/submissions_extracted/276/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..4d0b7d8450bc7383b6670223da629876fb7ecb55 --- /dev/null +++ b/submissions_extracted/276/Q2.ipynb @@ -0,0 +1,371 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "\n", + "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 AdamW\n", + "import matplotlib.pyplot as plt\n", + "from torch.utils.data import DataLoader, TensorDataset\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", + "X_train = torch.tensor(X_train, dtype=torch.float32) # in multiclass classficiton you have to make (int)\n", + "X_test = torch.tensor(X_test, dtype=torch.float32)\n", + "y_train = torch.tensor(y_train, dtype=torch.float32) # in multiclass classficiton you have to make (int)\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", + "\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", + "# DataLoader for training data\n", + "train_loader = DataLoader(\n", + " train_dataset,\n", + " batch_size=32,\n", + " shuffle=True\n", + ")\n", + "\n", + "# DataLoader for test/validation data\n", + "test_loader = DataLoader(\n", + " test_dataset,\n", + " batch_size=32,\n", + " 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" + ], + "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": [ + "# 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", + " # 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", + "\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", + " # Thrid hidden layer\n", + " a3 = self.relu(self.layer3(a2))\n", + "\n", + " # Output layer (regression output)\n", + " output = self.layer4(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) # 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.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", + "\n", + "# device\n", + "device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n", + "\n", + "\n", + "# data shapes and hidden dimm\n", + "input_dim = 36 # Number of features\n", + "hidden_dim = 64 # re visit\n", + "\n", + "\n", + "# model\n", + "model = NN4Layer(input_dim, hidden_dim).to(device)\n", + "\n", + "# Hyperparameters (LR)\n", + "learning_rate = 0.001\n", + "\n", + "# loss\n", + "criterion = nn.MSELoss()\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", + "\n", + "# Hyperparameters (epochs)\n", + "num_epochs = 20\n", + "\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", + "# 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/276/Q3.ipynb b/submissions_extracted/276/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..bf7bbc62fc9dfbe77fef0599437ac479d3ecde50 --- /dev/null +++ b/submissions_extracted/276/Q3.ipynb @@ -0,0 +1,161 @@ +{ + "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", + "q3_path = os.path.join(path, 'q3-exam-data.csv')" + ], + "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 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 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/277/Q1.ipynb b/submissions_extracted/277/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..490ccb021482d889f83814a55d616c641bcaa65e --- /dev/null +++ b/submissions_extracted/277/Q1.ipynb @@ -0,0 +1,344 @@ +{ + "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\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" + ], + "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:(Plot the target distribution (delivery_time))\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:(Drop the 'Order_ID' column from the data)\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: (Handle missing values appropriately (Hint: I guess you want to have a closer look at the columns with 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": [ + "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()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Drop rows where target (delivery time) - can't predict without it\n", + "print(f\"Before: {df_clean.shape}\")\n", + "df_clean = df_clean.dropna(subset=['Delivery_Time'])\n", + "print(f\"After dropping missing Delivery Time: {df_clean.shape}\")" + ], + "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']:\n", + " df_clean[col] = df_clean[col].fillna('unknown')" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Fill years of experience with mode - discrete feature, mode is most representative\n", + "df_clean['Courier_Experience_yrs'] = df_clean['Courier_Experience_yrs'].fillna(df_clean['Courier_Experience_yrs'].mode()[0])\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: (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) #to have it in the original data\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: (Encode categorical variables if needed (Bonus if used One Hot Encoding))\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": [ + "from sklearn.preprocessing import OneHotEncoder\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\n", + "\n", + "df_clean" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here: (Apply feature scaling for all features (Use StandardScaler))\n", + "from sklearn.preprocessing import StandardScaler\n", + "\n", + "features = df_clean.columns.drop(\"Delivery_Time\")\n", + "\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: (Check for target imbalance and state if it is imbalanced or not (keep this cell empty if not needed))" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:(Split the dataset into features (X) and target (y))\n", + "X = df_clean.drop(columns=['Delivery_Time']).astype(float)\n", + "y = df_clean['Delivery_Time'].astype(float)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here: ( 1-Use the correct split: KFold OR StratifiedKFold 2-Train a RandomForest model\n", + "#3- Evaluate using MAE (Mean Absolute Error) ONLY 4-Print the averaged score across all folds)\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\n", + "kf = KFold(n_splits=5, shuffle=True, random_state=42)\n", + "\n", + "lr_mae = []\n", + "\n", + "model = RandomForestRegressor(n_estimators=200)\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", + " # 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", + " lr_mae.append(mae)\n", + "\n", + "print(f\" MAE: {np.mean(lr_mae, axis=0):.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", + "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: (Plot predicted delivery time histogram)\n", + "plt.figure(figsize=(6, 4))\n", + "plt.hist(y_pred, bins=30, edgecolor='black', color='pink')\n", + "plt.title(\"predicted delivery time histogram\")\n", + "plt.grid(True)\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/277/Q2.ipynb b/submissions_extracted/277/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..2768bdf595197fb2b13f400dd9efbecf247c6d3f --- /dev/null +++ b/submissions_extracted/277/Q2.ipynb @@ -0,0 +1,410 @@ +{ + "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 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 (Convert to Tensors: Convert the numpy arrays (X_train, X_test, y_train, y_test) into 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", + "\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 (Create Datasets: Use TensorDataset to create train_dataset and test_dataset from the tensors.)\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 (Create DataLoaders: Create train_loader and test_loader with a batch size of 32.)\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 (Inspect Data: Print the shape of one batch from the train loader and)\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 (Display a few images: Use matplotlib to display a few images.)\n", + "import matplotlib.pyplot as plt\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], 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", + "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: (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.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 = 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" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Start training for 20 epochs:\n", + "from torch.optim import Adam\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", + "# 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", + "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:\n", + "\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/277/Q3.ipynb b/submissions_extracted/277/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..0fcc4868b7b32ebff2c7959f1894b522d36113a1 --- /dev/null +++ b/submissions_extracted/277/Q3.ipynb @@ -0,0 +1,272 @@ +{ + "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", + "\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: (Read the dataset Q3_data.csv using read_csv())\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(\"\\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) #to have it in the 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:\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: (Apply feature scaling to numerical features (Use StandardScaler))\n", + "from sklearn.preprocessing import StandardScaler\n", + "\n", + "features = df.columns.drop(\"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", + "\n", + "ones= df['Target'].sum()\n", + "zeros= (df['Target'] == 0).sum()\n", + "\n", + "if ones == zeros:\n", + " print (\"Balanced\")\n", + "else:\n", + " print(\"imbalanced\")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "X = df.drop(columns=['Target']).astype(float)\n", + "y = df['Target'].astype(float)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "pip install xgboost" + ], + "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", + "# 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", + "from catboost import CatBoostClassifier\n", + "\n", + "model= CatBoostClassifier(\n", + " verbose=0,\n", + " n_estimators=200,\n", + " max_depth=4\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/278/Q1.ipynb b/submissions_extracted/278/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..ab9d0c9709eda36f899cadf29bac778378ff1b1a --- /dev/null +++ b/submissions_extracted/278/Q1.ipynb @@ -0,0 +1,443 @@ +{ + "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", + "\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", + "# Reading the dataset\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=(8, 6))\n", + "sns.histplot(df['Delivery_Time'], kde=True)\n", + "plt.title('Distribution of Delivery Time')\n", + "plt.xlabel('Delivery Time (minutes)')\n", + "plt.show()\n", + "\n", + "# I decided to use a histogram with a KDE (that smooth line) because I need to see the shape of the data.\n", + "# If it looks like a bell curve, my regression model will likely work well." + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "# dropping the Order_ID column\n", + "df = df.drop(columns=['Order_ID'])\n", + "# I'm dropping 'Order_ID' because it's just a unique label for each row.\n", + "# It doesn't actually affect how long the delivery takes (it's not a feature),\n", + "# and if I leave it in, the model might try to find a weird pattern in the ID numbers, which leads to overfitting." + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "# checking which columns have missing values\n", + "print(df.isnull().sum())" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "# First, I have to deal with the missing Target values (Delivery_Time).\n", + "# I see 106 missing values in Delivery_Time.\n", + "# I decided to DROP these rows entirely.\n", + "# Because Delivery_Time is the answer I'm trying to predict.\n", + "# If I fill it with an average, I'm basically training my model on fake answers, which is cheating.\n", + "df = df.dropna(subset=['Delivery_Time'])\n", + "\n", + "# Now for the other columns:\n", + "# 'Courier_Experience_yrs' is a number, so I'll fill it with the Median.\n", + "# I chose median because if one courier has 50 years experience (an outlier), the mean would get skewed.\n", + "df['Courier_Experience_yrs'] = df['Courier_Experience_yrs'].fillna(df['Courier_Experience_yrs'].median())\n", + "\n", + "# Weather, Traffic_Level, and Time_of_Day are text (categorical).\n", + "# I can't calculate an average for \"Rainy\", so I'm filling them with the Mode (the most common value).\n", + "cols_to_fill = ['Weather', 'Traffic_Level', 'Time_of_Day']\n", + "for col in cols_to_fill:\n", + " df[col] = df[col].fillna(df[col].mode()[0])\n", + "\n", + "# Checking to make sure all zeros are gone\n", + "print(df.isnull().sum())" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# checking for duplicates first\n", + "print(f\"Duplicates before: {df.duplicated().sum()}\")\n", + "\n", + "# removing them\n", + "df = df.drop_duplicates()\n", + "\n", + "# Checking after\n", + "print(f\"Duplicates after: {df.duplicated().sum()}\")\n", + "\n", + "# I'm removing duplicates because if the exact same order data appears twice,\n", + "# the model will over-prioritize that specific scenario, leading to bias." + ], + "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", + "df = pd.get_dummies(df, columns=['Weather', 'Traffic_Level', 'Time_of_Day', 'Vehicle_Type'], drop_first=True)\n", + "\n", + "# displaying the new columns to verify\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "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" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "from sklearn.preprocessing import StandardScaler\n", + "\n", + "# I need to separate the Features (X) from the Target (y) before scaling.\n", + "X = df.drop(columns=['Delivery_Time'])\n", + "y = df['Delivery_Time']\n", + "\n", + "scaler = StandardScaler()\n", + "\n", + "# I'm fitting the scaler on X and transforming it.\n", + "X_scaled = pd.DataFrame(scaler.fit_transform(X), columns=X.columns)\n", + "\n", + "# Checking the result\n", + "X_scaled.head()\n", + "\n", + "# I did this because Distance_km has big numbers (like 10-20) but Courier_Experience_yrs has small numbers (like 1-5).\n", + "# If I don't scale them to the same range, the model will think Distance is more important just because the number is bigger." + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 6: Write your code here:\n", + "# Task: Check for target imbalance\n", + "\n", + "# Since this is a regression problem, we don't have classes to count.\n", + "# Instead, I am checking the \"Skewness\" of the delivery times.\n", + "# If the data is heavily skewed (leaning to the left or right), it acts like an imbalance.\n", + "\n", + "skewness = df['Delivery_Time'].skew()\n", + "print(f\"Skewness value: {skewness}\")\n", + "\n", + "# Plotting it to visualize the balance\n", + "plt.figure(figsize=(6, 4))\n", + "sns.histplot(df['Delivery_Time'], kde=True)\n", + "plt.title('Distribution of Delivery Time')\n", + "plt.show()\n", + "\n", + "# My Conclusion:\n", + "# If the skewness is near 0 (e.g., between -0.5 and 0.5), it is NOT imbalanced (it's normal).\n", + "# If the number is high (like > 1.0), it IS imbalanced (highly skewed)." + ], + "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", + "import numpy as np\n", + "\n", + "# 1. Split the dataset into features (X) and target (y)\n", + "# I'm separating them because the model needs to know what to learn from (X) and what to predict (y).\n", + "X = df.drop(columns=['Delivery_Time'])\n", + "y = df['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 RandomForestRegressor\n", + "from sklearn.metrics import mean_absolute_error\n", + "import numpy as np\n", + "\n", + "# Step 1: Defining the Split\n", + "kf = KFold(n_splits=5, shuffle=True, random_state=42)\n", + "\n", + "\n", + "# Step 2: Defining the Model\n", + "model = RandomForestRegressor(random_state=42)\n", + "\n", + "mae_scores = []\n", + "\n", + "# Step 3: Training Loop\n", + "\n", + "# I'm looping through 5 different splits of the data to make sure my model isn't just lucky on one specific test set.\n", + "for train_index, test_index in kf.split(X_scaled):\n", + "\n", + " # Splitting the data\n", + " X_train, X_test = X_scaled.iloc[train_index], X_scaled.iloc[test_index]\n", + " y_train, y_test = y.iloc[train_index], y.iloc[test_index]\n", + "\n", + " # Training\n", + " model.fit(X_train, y_train)\n", + "\n", + " # Predicting\n", + " y_pred = model.predict(X_test)\n", + "\n", + " # Calculating Error\n", + " # I used MAE (Mean Absolute Error) because it's easy to interpret.\n", + " # It tells me exactly how many minutes my prediction is off by on average.\n", + " mae = mean_absolute_error(y_test, y_pred)\n", + " mae_scores.append(mae)\n", + "\n", + "# Step 4: Final Output\n", + "\n", + "# I'm averaging the scores to get one final performance number.\n", + "average_mae = np.mean(mae_scores)\n", + "\n", + "print(f\"MAE Scores for each fold: {mae_scores}\")\n", + "print(f\"Average MAE: {average_mae}\")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "import matplotlib.pyplot as plt\n", + "import seaborn as sns\n", + "import pandas as pd\n", + "\n", + "# --- Plot 1: Feature Importance ---\n", + "\n", + "plt.figure(figsize=(10, 6))\n", + "\n", + "# I'm extracting the importance scores from the random forest model.\n", + "# I matched them with the column names so I know which score belongs to which feature.\n", + "feat_importances = pd.Series(model.feature_importances_, index=X_scaled.columns)\n", + "\n", + "# I'm plotting only the top 10 features.\n", + "# I did this because if I plot all of them, the chart gets messy and hard to read.\n", + "feat_importances.nlargest(10).plot(kind='barh')\n", + "plt.title('Top 10 Important Features')\n", + "plt.xlabel('Importance Score')\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "plt.figure(figsize=(8, 6))\n", + "\n", + "# I'm using the 'y_pred' from the last fold of my validation loop.\n", + "# I plotted this histogram to see the shape of my model's predictions.\n", + "sns.histplot(y_pred, kde=True, color='green')\n", + "\n", + "plt.title('Distribution of Predicted Delivery Times')\n", + "plt.xlabel('Predicted Time (minutes)')\n", + "plt.show()\n", + "\n", + "# If this looks like a nice bell curve (Normal Distribution), it means the model is behaving stably.\n", + "# If it has weird spikes, the model might be biased towards specific numbers." + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "!pip install catboost" + ], + "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", + "# Step 1: Setup\n", + "\n", + "# I'm using KFold again because we are still doing Regression.\n", + "kf = KFold(n_splits=5, shuffle=True, random_state=42)\n", + "\n", + "mae_scores = []\n", + "\n", + "#Step 2: The Loop (Ensemble Strategy)\n", + "\n", + "print(\"Starting Ensemble Training...\")\n", + "\n", + "for train_index, test_index in kf.split(X_scaled):\n", + "\n", + " # Splitting the data for this fold\n", + " X_train, X_test = X_scaled.iloc[train_index], X_scaled.iloc[test_index]\n", + " y_train, y_test = y.iloc[train_index], y.iloc[test_index]\n", + "\n", + " # Training Model 1: Random Forest\n", + " # I'm keeping Random Forest as my base model.\n", + " rf_model = RandomForestRegressor(random_state=42)\n", + " rf_model.fit(X_train, y_train)\n", + " rf_pred = rf_model.predict(X_test)\n", + "\n", + " # Training Model 2: CatBoost\n", + " # I set verbose=0 so it doesn't flood the screen with logs during training.\n", + " cb_model = CatBoostRegressor(random_state=42, verbose=0)\n", + " cb_model.fit(X_train, y_train)\n", + " cb_pred = cb_model.predict(X_test)\n", + "\n", + " # Averaging Predictions (The Ensemble)\n", + " # I'm taking the average of both models.\n", + " # The idea is that if one model makes a mistake, the other might correct it.\n", + " final_pred = (rf_pred + cb_pred) / 2\n", + "\n", + " # Calculating MAE on the averaged prediction\n", + " mae = mean_absolute_error(y_test, final_pred)\n", + " mae_scores.append(mae)\n", + "\n", + "# Step 3: Final Results\n", + "\n", + "average_mae = np.mean(mae_scores)\n", + "\n", + "print(f\"Ensemble MAE Scores per fold: {mae_scores}\")\n", + "print(f\"Average Ensemble MAE: {average_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/278/Q2.ipynb b/submissions_extracted/278/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..9963e6b395672ca4cdbae29d52490ca3b13f0108 --- /dev/null +++ b/submissions_extracted/278/Q2.ipynb @@ -0,0 +1,505 @@ +{ + "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", + "# I'm using torch.tensor() to wrap the existing numpy arrays.\n", + "# I added .float() at the end because PyTorch weights are usually float32.\n", + "X_train_tensor = torch.tensor(X_train).float()\n", + "X_test_tensor = torch.tensor(X_test).float()\n", + "\n", + "# For the targets (y), I also need them to be float because this is a regression problem\n", + "y_train_tensor = torch.tensor(y_train).float()\n", + "y_test_tensor = torch.tensor(y_test).float()\n", + "\n", + "# Checking the shapes just to be safe\n", + "print(f\"X_train tensor shape: {X_train_tensor.shape}\")\n", + "print(f\"y_train tensor shape: {y_train_tensor.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 2. Create TensorDataset objects\n", + "from torch.utils.data import TensorDataset\n", + "\n", + "# I'm using TensorDataset to bundle my features (X) and targets (y) together.\n", + "# This makes it super easy to grab a pair of (image, age) just by indexing like train_dataset[0].\n", + "# It's like zipping them into a list of tuples, but optimized for PyTorch.\n", + "train_dataset = TensorDataset(X_train_tensor, y_train_tensor)\n", + "test_dataset = TensorDataset(X_test_tensor, y_test_tensor)\n", + "\n", + "# Verifying it worked by printing the length\n", + "print(f\"Train dataset size: {len(train_dataset)}\")\n", + "print(f\"Test dataset size: {len(test_dataset)}\")\n", + "\n", + "# I did this because the DataLoader needs a proper 'Dataset' object\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 3. Create DataLoaders\n", + "\n", + "from torch.utils.data import DataLoader\n", + "\n", + "\n", + "\n", + "batch_size = 32\n", + "\n", + "# For training, I set shuffle=True.\n", + "# This is crucial because if the data was sorted\n", + "# the model would get biased during the first few batches. Shuffling mixes it up.\n", + "train_loader = DataLoader(train_dataset, batch_size=batch_size, shuffle=True)\n", + "\n", + "# For testing, I set shuffle=False.\n", + "# I don't need to shuffle the test data because I'm just evaluating performance,\n", + "# and keeping the order the same makes debugging easier if I want to check specific errors later.\n", + "test_loader = DataLoader(test_dataset, batch_size=batch_size, shuffle=False)\n", + "\n", + "# Checking how many batches we have\n", + "print(f\"Number of training batches: {len(train_loader)}\")\n", + "print(f\"Number of testing batches: {len(test_loader)}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 4. Print shape of one batch\n", + "\n", + "# I'm using iter() and next() to manually grab just the very first batch of data from the loader.\n", + "data_iter = iter(train_loader)\n", + "images, labels = next(data_iter)\n", + "\n", + "# Printing the shapes\n", + "print(f\"Batch images shape: {images.shape}\")\n", + "print(f\"Batch labels shape: {labels.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 5. Display sample images\n", + "import matplotlib.pyplot as plt\n", + "\n", + "# I'm creating a grid of 4 images just to see what the data actually looks like.\n", + "fig, axes = plt.subplots(1, 4, figsize=(12, 3))\n", + "\n", + "for i in range(4):\n", + " img_to_show = images[i].permute(1, 2, 0)\n", + "\n", + " axes[i].imshow(img_to_show)\n", + " axes[i].set_title(f\"Age: {labels[i].item()}\") # .item() gets the actual number from the tensor\n", + " axes[i].axis('off') # Hiding axes ticks because they are distracting\n", + "\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", + "\n", + "\n", + "class AgePredictor(nn.Module):\n", + " def __init__(self):\n", + " super(AgePredictor, self).__init__()\n", + "\n", + " # Layer 1: Input to Hidden 1\n", + " self.fc1 = nn.Linear(3 * 36 * 36, 512)\n", + "\n", + " # Layer 2: Hidden 1 to Hidden 2\n", + " # I'm reducing the size gradually (512 -> 128) to compress the information.\n", + " self.fc2 = nn.Linear(512, 128)\n", + "\n", + " # Layer 3: Hidden 2 to Hidden 3\n", + " self.fc3 = nn.Linear(128, 64)\n", + "\n", + " # Layer 4: Hidden 3 to Output\n", + " self.fc4 = nn.Linear(64, 1)\n", + "\n", + " def forward(self, x):\n", + " # Step 1: Flattening\n", + " x = x.view(x.size(0), -1)\n", + "\n", + " # Step 2: Passing through layers with ReLU\n", + " x = F.relu(self.fc1(x))\n", + " x = F.relu(self.fc2(x))\n", + " x = F.relu(self.fc3(x))\n", + "\n", + " # Step 3: Output Layer\n", + " # I am not using an activation function (like Sigmoid or ReLU) here.\n", + " # Because this is Regression. I want the raw number.\n", + " # If I used Sigmoid, predictions would be stuck between 0 and 1, which is bad for age\n", + " x = self.fc4(x)\n", + "\n", + " return x\n", + "\n", + "# Instantiating the model to check it\n", + "model = AgePredictor()\n", + "print(model)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your training loop here:\n", + "\n", + "def train_model(model, train_loader, criterion, optimizer, num_epochs=10):\n", + "\n", + " # I'm looping through the number of epochs\n", + " for epoch in range(num_epochs):\n", + "\n", + " # Setting the model to training mode.\n", + " model.train()\n", + "\n", + " running_loss = 0.0\n", + "\n", + " for images, labels in train_loader:\n", + "\n", + " # 1. Zero the gradients\n", + " # I have to do this because PyTorch accumulates gradients by default.\n", + " # If I don't clear them, the new gradients get added to the old ones, creating a mess.\n", + " optimizer.zero_grad()\n", + "\n", + " # 2. Forward Pass\n", + " outputs = model(images)\n", + "\n", + " # 3. Calculate Loss\n", + " loss = criterion(outputs, labels.view(-1, 1))\n", + "\n", + " # 4. Backward Pass (Backpropagation)\n", + " # This calculates the gradients\n", + " loss.backward()\n", + "\n", + " # 5. Optimizer Step\n", + " # This updates the weights using the gradients we just calculated.\n", + " optimizer.step()\n", + "\n", + " running_loss += loss.item()\n", + "\n", + " # Printing the average loss for this epoch\n", + " # This helps me see if the model is actually learning (loss should go down).\n", + " epoch_loss = running_loss / len(train_loader)\n", + " print(f\"Epoch [{epoch+1}/{num_epochs}], Loss: {epoch_loss:.4f}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your validation loop here:\n", + "\n", + "def validate_model(model, test_loader, criterion):\n", + "\n", + " # I'm switching the model to 'eval' mode.\n", + " # This freezes layers like Dropout or BatchNorm so they behave consistently during testing.\n", + " model.eval()\n", + "\n", + " running_loss = 0.0\n", + " running_mae = 0.0\n", + "\n", + " # I'm using torch.no_grad() here I don't need to calculate gradients for backpropagation during testing.\n", + " # This saves a ton of memory and makes the code run faster.\n", + " with torch.no_grad():\n", + " for images, labels in test_loader:\n", + "\n", + " # Forward pass only\n", + " outputs = model(images)\n", + "\n", + " # Calculating the Loss (MSE)\n", + " loss = criterion(outputs, labels.view(-1, 1))\n", + " running_loss += loss.item()\n", + "\n", + " # Calculating MAE (Mean Absolute Error) manually.\n", + " mae = torch.abs(outputs - labels.view(-1, 1)).mean()\n", + " running_mae += mae.item()\n", + "\n", + " # Calculating averages\n", + " avg_loss = running_loss / len(test_loader)\n", + " avg_mae = running_mae / len(test_loader)\n", + "\n", + " print(f\"Validation Loss: {avg_loss:.4f} | Validation MAE: {avg_mae:.4f}\")\n", + " return avg_mae" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Define device, model, loss, optimizer:\n", + "import torch.optim as optim\n", + "\n", + "# Task: Define device, model, loss function, and optimizer\n", + "\n", + "# 1. Define Device\n", + "device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n", + "print(f\"Using device: {device}\")\n", + "\n", + "# 2. Initialize Model\n", + "model = AgePredictor().to(device)\n", + "\n", + "# 3. Define Loss Function\n", + "# I chose MSELoss (Mean Squared Error) because this is a Regression problem.\n", + "# It penalizes large errors heavily, which helps the model fix big mistakes quickly.\n", + "criterion = nn.MSELoss()\n", + "\n", + "# 4. Define Optimizer\n", + "# I chose Adam with a learning rate (lr) of 0.001.\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", + "\n", + "train_losses = []\n", + "val_maes = []\n", + "\n", + "num_epochs = 20\n", + "\n", + "print(\"Starting Training...\")\n", + "\n", + "for epoch in range(num_epochs):\n", + " # Training Phase\n", + " model.train() # Set to train mode\n", + " running_loss = 0.0\n", + "\n", + " for images, labels in train_loader:\n", + " images, labels = images.to(device), labels.to(device)\n", + "\n", + " optimizer.zero_grad()\n", + "\n", + " outputs = model(images)\n", + " loss = criterion(outputs, labels.view(-1, 1))\n", + "\n", + " loss.backward()\n", + " optimizer.step()\n", + "\n", + " running_loss += loss.item()\n", + "\n", + " # Calculating average training loss for this epoch\n", + " epoch_loss = running_loss / len(train_loader)\n", + " train_losses.append(epoch_loss)\n", + "\n", + " # Validation Phase\n", + " model.eval() # Set to eval mode\n", + " val_loss = 0.0\n", + " val_mae = 0.0\n", + "\n", + " with torch.no_grad():\n", + " for images, labels in test_loader:\n", + " images, labels = images.to(device), labels.to(device)\n", + "\n", + " outputs = model(images)\n", + " # Calculating MAE (Mean Absolute Error) in years\n", + " mae = torch.abs(outputs - labels.view(-1, 1)).mean()\n", + " val_mae += mae.item()\n", + "\n", + " avg_val_mae = val_mae / len(test_loader)\n", + " val_maes.append(avg_val_mae)\n", + "\n", + " print(f\"Epoch [{epoch+1}/{num_epochs}] | Train Loss: {epoch_loss:.4f} | Val MAE: {avg_val_mae:.2f} years\")\n", + "\n", + "print(\"Training Complete!\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "import matplotlib.pyplot as plt\n", + "\n", + "# Task: Plot the training loss over epochs\n", + "\n", + "plt.figure(figsize=(12, 5))\n", + "\n", + "# Plotting Training Loss (MSE)\n", + "plt.subplot(1, 2, 1)\n", + "plt.plot(train_losses, label='Train Loss (MSE)', color='blue')\n", + "plt.title('Training Loss over Epochs')\n", + "plt.xlabel('Epochs')\n", + "plt.ylabel('Loss (Mean Squared Error)')\n", + "plt.grid(True)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task: Plot the validation loss over epochs\n", + "# Plotting Validation MAE\n", + "plt.subplot(1, 2, 2)\n", + "plt.plot(val_maes, label='Validation MAE (Years)', color='orange')\n", + "plt.title('Validation MAE over Epochs')\n", + "plt.xlabel('Epochs')\n", + "plt.ylabel('Mean Absolute Error (Years)')\n", + "plt.grid(True)\n", + "\n", + "plt.show()\n", + "\n", + "# The lines should go down\n", + "# If Training goes down but Validation goes up, that means I'm overfitting" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2 (Bonus): Write your code here:\n", + "\n", + "# 1. Get a batch of test data\n", + "dataiter = iter(test_loader)\n", + "images, labels = next(dataiter)\n", + "\n", + "\n", + "\n", + "# 3. Make predictions\n", + "model.eval() # Safety first: switch to eval mode!\n", + "with torch.no_grad():\n", + " outputs = model(images)\n", + "\n", + "# 4. Prepare for plotting\n", + "images_cpu = images.cpu()\n", + "labels_cpu = labels.cpu()\n", + "preds_cpu = outputs.cpu()\n", + "\n", + "# 5. Plotting\n", + "fig, axes = plt.subplots(2, 4, figsize=(15, 8)) # A grid of 8 images (2 rows, 4 columns)\n", + "axes = axes.flatten()\n", + "\n", + "for i in range(8):\n", + " # Permuting again: (C, H, W) -> (H, W, C) for matplotlib\n", + " img_to_show = images_cpu[i].permute(1, 2, 0)\n", + "\n", + " # Getting the numbers\n", + " actual_age = labels_cpu[i].item()\n", + " pred_age = preds_cpu[i].item()\n", + "\n", + " axes[i].imshow(img_to_show)\n", + "\n", + " # I'm formatting the title to show both numbers.\n", + " # I rounded the prediction (.1f) because the model gives floats like 24.532 years.\n", + " axes[i].set_title(f\"Actual: {actual_age:.0f} | Pred: {pred_age:.1f}\")\n", + " axes[i].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/278/Q3.ipynb b/submissions_extracted/278/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..a7023ca4be944dafd03c809ff55449592896d199 --- /dev/null +++ b/submissions_extracted/278/Q3.ipynb @@ -0,0 +1,350 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "import kagglehub\n", + "import pandas as pd\n", + "import numpy as np\n", + "import matplotlib.pyplot as plt\n", + "import seaborn as sns\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", + "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", + "# Task: Inspect first few 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 1: Write your code here:\n", + "# Task: Handle missing values\n", + "\n", + "# First, let's see which columns actually have holes in them.\n", + "print(\"Missing values before fix:\")\n", + "print(df.isnull().sum())\n", + "\n", + "# Now, I'm filling the missing values.\n", + "# Since I don't know what 'P_2' or 'B_1' actually mean so i can't guess the value\n", + "# For numbers: I use median because financial data usually has big outliers\n", + "# which would mess up the mean. Median is safer.\n", + "# For text/categories: I use mode (the most common value).\n", + "\n", + "for col in df.columns:\n", + " if df[col].dtype == 'object':\n", + " # If it's text (categorical), fill with the most common class\n", + " df[col] = df[col].fillna(df[col].mode()[0])\n", + " else:\n", + " # If it's a number, fill with the median\n", + " df[col] = df[col].fillna(df[col].median())\n", + "\n", + "# Verification step\n", + "print(\"\\nMissing values after fix:\")\n", + "print(df.isnull().sum())" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "# Check and remove duplicates\n", + "\n", + "# 1. Check count\n", + "duplicate_count = df.duplicated().sum()\n", + "print(f\"Number of duplicates found: {duplicate_count}\")\n", + "\n", + "# 2. Remove duplicates (if any)\n", + "if duplicate_count > 0:\n", + " df = df.drop_duplicates()\n", + " print(\"Duplicates removed.\")\n", + "else:\n", + " print(\"No duplicates to remove.\")\n", + "\n", + "# 3. Final Check\n", + "print(f\"Final Data Shape: {df.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "# Encode categorical variables\n", + "\n", + "# First, I need to check if there are any text columns (Type 'object').\n", + "categorical_cols = df.select_dtypes(include=['object']).columns\n", + "print(f\"Categorical columns found: {list(categorical_cols)}\")\n", + "\n", + "if len(categorical_cols) > 0:\n", + " # If there are text columns, I use One Hot Encoding (get_dummies).\n", + " df = pd.get_dummies(df, columns=categorical_cols, drop_first=True, dtype=int)\n", + " print(\"Encoding complete.\")\n", + "else:\n", + " print(\"No categorical variables found. Skipping encoding.\")\n", + "\n", + "# Showing the new shape of the dataframe to see how many columns were added\n", + "print(f\"New Data Shape: {df.shape}\")\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "from sklearn.preprocessing import StandardScaler\n", + "\n", + "target_col = df.columns[-1]\n", + "print(f\"I found the target column name: '{target_col}'\")\n", + "\n", + "\n", + "# 1. Separate Features (X) and Target (y)\n", + "X = df.drop(columns=[target_col])\n", + "y = df[target_col]\n", + "\n", + "# 2. Initialize Scaler\n", + "scaler = StandardScaler()\n", + "\n", + "# 3. Fit and Transform\n", + "X_scaled_array = scaler.fit_transform(X)\n", + "\n", + "# 4. Convert back to DataFrame\n", + "X_scaled = pd.DataFrame(X_scaled_array, columns=X.columns)\n", + "\n", + "print(\"Scaling complete.\")\n", + "X_scaled.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "# Task: Check for target imbalance\n", + "\n", + "# 1. Identify the target column\n", + "target_col = df.columns[-1]\n", + "print(f\"Target column identified as: '{target_col}'\")\n", + "\n", + "# 2. Count the values\n", + "class_counts = df[target_col].value_counts()\n", + "class_percentages = df[target_col].value_counts(normalize=True) * 100\n", + "\n", + "print(\"\\nClass Counts:\")\n", + "print(class_counts)\n", + "\n", + "print(\"\\nClass Percentages:\")\n", + "print(class_percentages)\n", + "\n", + "# 3. State if Imbalanced\n", + "minority_class_percent = class_percentages.min()\n", + "\n", + "if minority_class_percent < 20:\n", + " print(f\"\\nCONCLUSION: The dataset is IMBALANCED (Minority class is only {minority_class_percent:.2f}%).\")\n", + "else:\n", + " print(f\"\\nCONCLUSION: The dataset is BALANCED.\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "# Task: Split the dataset into features (X) and target (y)\n", + "\n", + "# 1. Define Features (X)\n", + "X = X_scaled\n", + "\n", + "# 2. Define Target (y)\n", + "target_col = df.columns[-1]\n", + "y = df[target_col]\n", + "\n", + "# 3. Verification\n", + "print(\"Data split into X and y.\")\n", + "print(f\"Features (X) shape: {X.shape}\")\n", + "print(f\"Target (y) shape: {y.shape}\")" + ], + "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", + "\n", + "from sklearn.model_selection import StratifiedKFold\n", + "from catboost import CatBoostClassifier\n", + "from sklearn.metrics import f1_score, accuracy_score\n", + "import numpy as np\n", + "\n", + "# Step 1: Defining the Split\n", + "skf = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)\n", + "\n", + "# Step 2: Defining the Model\n", + "model = CatBoostClassifier(random_state=42, verbose=0)\n", + "\n", + "f1_scores = []\n", + "acc_scores = []\n", + "\n", + "print(\"Starting 5-Fold Cross-Validation...\")\n", + "\n", + "# Step 3: Training Loop\n", + "\n", + "# I'm looping through 5 different splits.\n", + "for fold, (train_index, test_index) in enumerate(skf.split(X, y)):\n", + "\n", + " # Splitting the 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", + " # Training\n", + " model.fit(X_train, y_train)\n", + "\n", + " # Predicting\n", + " y_pred = model.predict(X_test)\n", + "\n", + " # Calculating Scores\n", + " f1 = f1_score(y_test, y_pred)\n", + " acc = accuracy_score(y_test, y_pred)\n", + "\n", + " f1_scores.append(f1)\n", + " acc_scores.append(acc)\n", + "\n", + " print(f\"Fold {fold+1} | F1 Score: {f1:.4f} | Accuracy: {acc:.4f}\")\n", + "\n", + "# --- Step 4: Final Output ---\n", + "\n", + "average_f1 = np.mean(f1_scores)\n", + "average_acc = np.mean(acc_scores)\n", + "\n", + "print(\"-\" * 30)\n", + "print(f\"Average F1 Score: {average_f1:.4f}\")\n", + "print(f\"Average Accuracy: {average_acc:.4f}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "\n", + "\n", + "#Plot feature importance and find the Golden Feature\n", + "feature_importances = pd.Series(model.feature_importances_, index=X.columns)\n", + "\n", + "# 2. Find the \"Golden Feature\"\n", + "# I'm simply looking for the maximum value in the series.\n", + "golden_feature_name = feature_importances.idxmax()\n", + "golden_feature_score = feature_importances.max()\n", + "\n", + "print(f\"🌟 THE GOLDEN FEATURE IS: '{golden_feature_name}'\")\n", + "print(f\"Importance Score: {golden_feature_score:.2f}\")\n", + "\n", + "# 3. Plotting\n", + "plt.figure(figsize=(10, 6))\n", + "\n", + "feature_importances.nlargest(10).sort_values().plot(kind='barh', color='gold')\n", + "\n", + "plt.title('Top 10 Features (Golden Feature Highlighted)')\n", + "plt.xlabel('Importance Score')\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/279/Q1.ipynb b/submissions_extracted/279/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..07f4ed32c52c75bd751fb3a24d8012c1ba58f4eb --- /dev/null +++ b/submissions_extracted/279/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", + "\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_Q1 = os.path.join(path, 'Q1_data.csv')\n", + "df = pd.read_csv(df_Q1)\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 4: Write your code here:\n", + "df.describe()" + ], + "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", + "plt.figure(figsize=(10, 5))\n", + "plt.hist(df['Delivery_Time'].dropna(), bins=30, edgecolor='black')\n", + "plt.title('Timing')\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']) #drop entire column" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: 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": [ + "# 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 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", + "from sklearn.preprocessing import StandardScaler #import StandardScaler\n", + "\n", + "print('data before scaling:\\n', data_for_scale) #show before scaling\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) #show after scaling\n" + ], + "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", + "\n", + "X_reg = pd.DataFrame({\"Delivery_Time\": np.random.randn(500)}) # features\n", + "y_reg = 3 * X_reg[\"Delivery_Time\"] + np.random.randn(500) * 0.5 # continous labels with noise\n", + "\n", + "\n", + "X_clf = pd.DataFrame({\"Delivery_Time\": np.random.randn(500)}) # features\n", + "y_clf = (X_clf[\"Delivery_Time\"] > 0).astype(int) # labels as class 0 or 1" + ], + "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", + "# 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", + "" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Import tree-based model for regression (Decision Tree Regressor)\n", + "from sklearn.tree import DecisionTreeRegressor\n", + "\n", + "# Use previously generated random regression 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 Decision Tree Regressor\n", + "model = DecisionTreeRegressor(random_state=42) # instantiate\n", + "model.fit(X_train, y_train) # fit\n", + "y_pred = model.predict(X_test) # predict\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "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", + "\n", + "mae = mean_absolute_error(y_test, y_pred)\n", + "\n", + "print(\"MAE :\", mae)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "plt.figure(figsize=(10, 4))\n", + "plt.scatter(y_test, y_pred, alpha=1)\n", + "plt.plot([min(y_test), max(y_test)],\n", + " [min(y_test), max(y_test)],\n", + " 'r--', linewidth=2)\n", + "\n", + "plt.ylabel(\"Delivery_Time\")\n", + "plt.xlabel(\"time\")\n", + "plt.title(\"Timing\")\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", + "plt.figure(figsize=(10, 4))\n", + "plt.scatter(y_test, y_pred, alpha=1)\n", + "plt.plot([min(y_test), max(y_test)],\n", + " [min(y_test), max(y_test)],\n", + " 'r--', linewidth=2)\n", + "\n", + "plt.ylabel(\"Delivery_Time\")\n", + "plt.xlabel(\"Predicted\")\n", + "plt.title(\"Timing\")\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/279/Q2.ipynb b/submissions_extracted/279/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..66154d06d9ca486af5fb5cf0e235cfa4cc190e16 --- /dev/null +++ b/submissions_extracted/279/Q2.ipynb @@ -0,0 +1,414 @@ +{ + "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 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 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", + "# 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)\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", + "# 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" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 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", + "\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" + ], + "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", + " # thirdlayer: hidden layer -> single continuous value\n", + " self.layer3 = nn.Linear(hidden_dim, hidden_dim)\n", + "\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", + " #thrid 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.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 = 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 = 64 # 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": [ + "# Hyperparameters\n", + "num_epochs = 20\n", + "learning_rate = 0.001\n", + "criterion = nn.MSELoss()\n", + "optimizer = (model.parameters(), learning_rate)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Start training for 20 epochs:\n", + "# Run Training\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 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/279/Q3.ipynb b/submissions_extracted/279/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..13ce3ab1885ea7cbb6e9e81f39b6f461183c3cea --- /dev/null +++ b/submissions_extracted/279/Q3.ipynb @@ -0,0 +1,228 @@ +{ + "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", + "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 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", + "# 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_Q3 = os.path.join(path, 'Q3_data.csv')\n", + "df = pd.read_csv(df_Q3)" + ], + "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": [ + "# 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 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 encodin" + ], + "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', data_for_scale) #show before scaling\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) #show after scaling\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", + "\n", + "print('data before scaling:\\n', data_for_scale) #show before scaling\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) #show after scaling" + ], + "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/28/Q1.ipynb b/submissions_extracted/28/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..e83d50e0009d8db70aadad6a66c799c86e35d33a --- /dev/null +++ b/submissions_extracted/28/Q1.ipynb @@ -0,0 +1,175 @@ +{ + "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": [ + "delivery_time_path = os.path.join(path, 'vehicles.csv')\n", + "df_delivery_time = pd.read_csv(delivery_time_path)\n", + "\n", + "print(f\"Dataset shape: {df_cars.shape}\")\n", + "df_delivery_time.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:" + ], + "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/28/Q2.ipynb b/submissions_extracted/28/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..c8937ff34d658b6340ef5c82e1d71e84083e0ea8 --- /dev/null +++ b/submissions_extracted/28/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/28/Q3.ipynb b/submissions_extracted/28/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..c97832709061629f03a86d1f40306ca8a3e2a744 --- /dev/null +++ b/submissions_extracted/28/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/280/Q1.ipynb b/submissions_extracted/280/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..7dcba457c6c44831891dc3e03d165b411c8ce700 --- /dev/null +++ b/submissions_extracted/280/Q1.ipynb @@ -0,0 +1,439 @@ +{ + "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", + "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 catboost import CatBoostClassifier\n", + "from sklearn.ensemble import RandomForestClassifier\n", + "from sklearn.ensemble import VotingClassifier\n", + "from sklearn.metrics import f1_score\n", + "sns\n", + "\n", + "import warnings" + ], + "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')" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import os\n", + "import pandas as pd\n", + "\n", + "pokemon_path = os.path.join(path, '/kaggle/input/q1-exam-data/Q1_data.csv')\n", + "fdt = pd.read_csv(pokemon_path)\n", + "\n", + "print(f\"Shape: {fdt.shape}\")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "fdt.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "fdt.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "fdt.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(fdt, \"Delivery_Time\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "fdt = fdt.drop('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(fdt)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "mis= ['Weather','Traffic_Level','Courier_Experience_yrs','Time_of_Day','Delivery_Time']" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "fdt = fdt.dropna(subset=mis)\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(fdt)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "def encode_categorical_columns(df):\n", + " categorical_cols = df.select_dtypes(include=[\"object\"]).columns\n", + " print(\"Categorical Columns:\", list(categorical_cols))\n", + " return categorical_cols\n", + "\n", + "label_encoders = encode_categorical_columns(fdt)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "from sklearn.preprocessing import LabelEncoder\n", + "\n", + "categorical_cols = fdt.select_dtypes(include=[\"object\"]).columns\n", + "for col in categorical_cols:\n", + " print(f\"Encoding column: {col}\")\n", + " le = LabelEncoder()\n", + " fdt[col] = le.fit_transform(fdt[col])\n", + "fdt" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "fdt['Weather']" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "fdt" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "from sklearn.preprocessing import StandardScaler\n", + "scaler = StandardScaler()\n", + "standard_scaler = StandardScaler() # Instantiate StandardScaler\n", + "data_standard_scaled = standard_scaler.fit_transform(fdt)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "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(fdt, \"Delivery_Time\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "X = fdt.drop(\"Delivery_Time\",axis=1)\n", + "y = fdt['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 , mean_squared_error\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", + "avrge =[]\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 = RandomForestClassifier(n_estimators=100, max_depth=15,\n", + " class_weight='balanced', random_state=42)\n", + "\n", + " model.fit(X_train, y_train)\n", + " y_pred = model.predict(X_test)\n", + "\n", + " print(\"Model trained!\")\n", + " mae = mean_absolute_error(y_test, y_pred)\n", + " avrge.append(mae)\n", + "np.mean(avrge)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "coeffs = {}\n", + "from sklearn.linear_model import Ridge, Lasso\n", + "\n", + "coeffs['Lasso'] = Lasso(alpha=1.0, max_iter=10000).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": [ + "\n", + "plt.hist(y_pred)\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": [ + "!pip install catboost" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "from lightgbm import LGBMClassifier\n", + "from xgboost import XGBClassifier\n", + "from catboost import CatBoostClassifier\n", + "from sklearn.ensemble import RandomForestClassifier\n", + "from sklearn.ensemble import VotingClassifier\n", + "from sklearn.metrics import f1_score" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "models = {\n", + " \"Logistic Regression\": LogisticRegression(max_iter=10000),\n", + " \"Random Forest Classifier\": RandomForestClassifier(n_estimators=100),\n", + " \"CatBoost Classifier\": CatBoostClassifier(verbose=0)\n", + "}\n", + "\n", + "models[\"Ensemble\"] = VotingClassifier(estimators=[\n", + " ('lr', models[\"CatBoost Classifier\"]), ('rf', models[\"Logistic Regression\"]), ('gnb', models[\"Random Forest Classifier\"])], voting=\"soft\")\n", + "\n", + "for model_name, model in models.items():\n", + " scores_accuracy = []\n", + " scores_precision = []\n", + " scores_recall = []\n", + " scores_f1 = []\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.iloc[train_idx], X.iloc[test_idx]\n", + " y_train, y_test = y.iloc[train_idx], y.iloc[test_idx]\n", + " # Train the model\n", + " model.fit(X_train, y_train)\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", + " mse = mean_squared_error(y_test, y_pred)" + ], + "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/280/Q2.ipynb b/submissions_extracted/280/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..cdb9fc18e7453ef0e6d06e5264b508fd87c5cb6f --- /dev/null +++ b/submissions_extracted/280/Q2.ipynb @@ -0,0 +1,424 @@ +{ + "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": [ + "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", + "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": [ + "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": [ + "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": [ + "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": [ + "images, labels = next(iter(train_loader))\n", + "\n", + "images.shape" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "sample_image, sample_label = train_dataset[0]\n", + "\n", + "images, labels = next(iter(train_loader))\n", + "images = images.flatten(start_dim=1).unsqueeze(0)\n", + "labels= labels.unsqueeze(1)\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+1], cmap='gray')\n", + " plt.title(f\"Label: {labels[i+1].item()}\")\n", + " plt.axis('off')\n", + "\n", + "plt.tight_layout()\n", + "plt.show()\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "class NN2Layer(nn.Module):\n", + "\n", + " def __init__(self, input_dim, hidden_dim, out):\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", + " self.layer2 = nn.Linear(hidden_dim, hidden_dim)\n", + " self.layer3 = nn.Linear(hidden_dim, hidden_dim)\n", + " self.layer4 = nn.Linear(hidden_dim, out)\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.layer1(a2)\n", + " a3 = self.relu(z3)\n", + " z4 = self.layer2(a3)\n", + " a4 = self.sigmoid(z4)\n", + " return a4" + ], + "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": [ + "# Task 4: Define device, model, loss, optimizer:\n", + "device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\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", + "m =36*3.6\n", + "input_dim = 36*36 # MNIST images flattened\n", + "hidden_dim = 32 # Design choice\n", + "output_dim = 3\n", + "model = NN2Layer(input_dim, hidden_dim, output_dim).to(device)\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": [ + "3888/1080" + ], + "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", + "# 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": [] + }, + { + "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/280/Q3.ipynb b/submissions_extracted/280/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..390dc3469de0f21ca2de042730e0e62791627849 --- /dev/null +++ b/submissions_extracted/280/Q3.ipynb @@ -0,0 +1,179 @@ +{ + "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 os\n", + "import pandas as pd\n", + "\n", + "pokemon_path = os.path.join(path, '/kaggle/input/q3-exam-data/Q3_data.csv')\n", + "data = pd.read_csv(pokemon_path)\n", + "\n", + "print(f\"Shape: {data.shape}\")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "data.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "data.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "data.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", + " return missing_values[missing_values > 0]\n", + "\n", + "m = check_missing_values(data)\n", + "\n", + "mis = m\n", + "fdt = data.dropna(subset=data.columns)\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/281/Q1.ipynb b/submissions_extracted/281/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..ce8b67fe503a5478bbe314400d5bbc2f4e84d23b --- /dev/null +++ b/submissions_extracted/281/Q1.ipynb @@ -0,0 +1,291 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import numpy as np\n", + "import pandas as pd\n", + "import matplotlib.pyplot as plt #for plotting data\n", + "import os\n", + "import kagglehub\n", + "\n", + "from sklearn.model_selection import train_test_split, KFold # Splits data into training and testing sets\n", + "\n", + "from sklearn.preprocessing import StandardScaler, LabelEncoder # Standardizes numerical features and encodes categorical labels\n", + "from sklearn.ensemble import RandomForestRegressor # Scales features to have mean 0 and variance 1, and converts labels to numbers\n", + "from sklearn.metrics import mean_absolute_error, mean_squared_error #measure the error\n", + "\n", + "import warnings #handles warning\n", + "warnings.filterwarnings('ignore') #hide warning massage\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", + "\n", + "\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", + "\n", + "df_Food.head() #Inspect the first few rows using head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "\n", + "df_Food.info() #Display dataset information using info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "\n", + "df_Food.describe() #Show statistical description using 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_Food[\"delivery_time\"].dropna(), bins=40, edgecolor='black')#chossing the target distribution\n", + "plt.title('Food Delivary 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", + "\n", + "df_Food.drop(columns=['Order_ID']) #Dropping 'Order_ID' column" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "\n", + "df_Food['Order_ID'].fillna(df_Food['Order_ID'].mode()[0])" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "\n", + "le = LabelEncoder()\n", + "df_Food['Weather'] = le.fit_transform(df_Food['Weather'])#Encode categorical variables\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" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "\n", + "df_Food['Order_ID'] = 10 - df_Food['Order_ID'] #Feature Engineering\n", + "\n", + "print(f\"\\nFeature ranges - Min: {X_train.min().min():.2f}, Max: {X_train.max().max():.2f}\")\n", + "X_train.head(3)\n", + "scaler = StandardScaler()\n", + "X_train_scaled = scaler.fit_transform(X_train)\n", + "X_test_scaled = scaler.transform(X_test)\n", + "pd.DataFrame(X_train_scaled, columns=X_train.columns).head(3)\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", + "#Data 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\"Train: {X_train.shape}, Test: {X_test.shape}\")\n", + "#define the variables!!!!!" + ], + "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", + "\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", + "#Training the model\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!\")#prin user text\n", + "\n", + "#Evaluating the model using MAE\n", + "y_pred = model.predict(X_test_scaled)\n", + "mae = mean_absolute_error(y_test, y_pred)\n", + "print(f\"MAE: ${mae:,.2f}\")#print the value\n", + "\n" + ], + "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", + "\n", + "plt.figure(figsize=(10, 6))\n", + "plt.barh(df_Food['delivery_time'])\n", + "plt.xlabel('Delivery time')\n", + "plt.title('freq')\n", + "#plt.gca().invert_yaxis()\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/281/Q2.ipynb b/submissions_extracted/281/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..ee68c8b0b5275d773e1c6ae6a82026c15ff99e97 --- /dev/null +++ b/submissions_extracted/281/Q2.ipynb @@ -0,0 +1,388 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import numpy as np\n", + "import pandas as pd\n", + "import matplotlib.pyplot as plt #for plotting data\n", + "import os\n", + "import kagglehub\n", + "import torch.nn as nn\n", + "\n", + "from sklearn.model_selection import train_test_split, KFold # Splits data into training and testing sets\n", + "\n", + "from sklearn.preprocessing import StandardScaler, LabelEncoder # Standardizes numerical features and encodes categorical labels\n", + "from sklearn.ensemble import RandomForestRegressor # Scales features to have mean 0 and variance 1, and converts labels to numbers\n", + "from sklearn.metrics import mean_absolute_error, mean_squared_error #measure the error\n", + "\n", + "import warnings #handles warning\n", + "warnings.filterwarnings('ignore') #hide warning massage\n", + "\n", + "\n", + "\n", + "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", + "\n", + "# Creating 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": [ + "# 2. Create TensorDataset objects\n", + "\n", + "import torch\n", + "\n", + "# Creating 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", + "# come back here to fix this!!!!" + ], + "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", + "\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}\")" + ], + "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", + "#initialize nn 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", + " # thierd 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", + "\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", + " # 3rd hidden layer\n", + " a3 = self.relu(self.layer3(a2))\n", + "\n", + " # Output layer (regression output)\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.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\n" + ], + "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" + ], + "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", + "\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 = 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", + "#loss function and optmizer\n", + "# Define criterion (loss function)\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 #training for 20 epochs\n", + "learning_rate = 0.001" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "\n", + "#plot results\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 (MSE)')\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:\n", + "\n", + "#predicted age vs actual age\n", + "\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 Age', fontsize=12)\n", + "plt.ylabel('Predicted Age', fontsize=12)\n", + "plt.title('Predicted vs Actual Ages', 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/281/Q3.ipynb b/submissions_extracted/281/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..ae8d8b4c8285d58eb5264d07f95872b43138f28e --- /dev/null +++ b/submissions_extracted/281/Q3.ipynb @@ -0,0 +1,380 @@ +{ + "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", + "import matplotlib.pyplot as plt #for plotting data\n", + "import os\n", + "import kagglehub\n", + "\n", + "from sklearn.model_selection import train_test_split, KFold # Splits data into training and testing sets\n", + "\n", + "from sklearn.preprocessing import StandardScaler, LabelEncoder # Standardizes numerical features and encodes categorical labels\n", + "from sklearn.ensemble import RandomForestRegressor # Scales features to have mean 0 and variance 1, and converts labels to numbers\n", + "from sklearn.metrics import mean_absolute_error, mean_squared_error #measure the error\n", + "\n", + "import warnings #handles warning\n", + "warnings.filterwarnings('ignore') #hide warning massage\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", + "\n", + "Q3_path = os.path.join(path, 'Q3_data.csv')\n", + "df_Q3 = pd.read_csv(Q3_path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "\n", + "df_Q3.head() #Inspect the first few rows using head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "\n", + "df_Q3.info() #Display dataset information using info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "\n", + "df_Q3.describe() #Show statistical description using describe()\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "\n", + "print(\"Missing values:\")\n", + "print(df_Q3.isnull().sum())\n", + "\n", + "#df_Q3.drop(columns=['P_2']) #Dropping 'P_2' column" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "\n", + "#No duplicate columns" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "\n", + "le = LabelEncoder()\n", + "df_Q3['D_144'] = le.fit_transform(df_Q3['D_144'])#Encode categorical variables\n", + "#D_144 has non-numerical values" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "\n", + "feature_cols = stat_cols + ['total_stats', 'attack_defense_ratio', 'type1', 'type2']\n", + "\n", + "X = df_clean[feature_cols]\n", + "y = df_clean['is_legendary']\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", + "# Scale features\n", + "scaler = StandardScaler()\n", + "X_train_scaled = scaler.fit_transform(X_train)\n", + "X_test_scaled = scaler.transform(X_test)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "\n", + "#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_Q3, \"D_144\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "\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", + "\n", + "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)\n", + "\n", + "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.\")\n", + "\n", + "\n", + "sklearn_models = {\n", + " \"K-Nearest Neighbors\": KNeighborsClassifier(\n", + " n_neighbors=3, # Number of neighbors to consider\n", + " ),\n", + " \"CatBoost\": CatBoostClassifier(\n", + " verbose=0,\n", + " n_estimators=320,\n", + " max_depth=4\n", + " )\n", + "}\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", + "print(f\" Accuracy: {np.mean(lr_accuracy):.4f}\") # print the Accuracy\n", + "print(f\" F1-Score: {np.mean(lr_f1):.4f}\") # print the F1 Score\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/282/Q1.ipynb b/submissions_extracted/282/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..35aa371c2055ef37bca065f3621b39235ffa35f3 --- /dev/null +++ b/submissions_extracted/282/Q1.ipynb @@ -0,0 +1,479 @@ +{ + "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\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": [ + "# Task 1: Write your code here:\n", + "Q1_path = os.path.join(path, 'Q1_data.csv')" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "Q1_data = pd.read_csv(Q1_path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:.\n", + "Q1_data.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "Q1_data.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "Q1_data.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\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(Q1_data, \"Delivery_Time\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "Q1_data = Q1_data.drop(columns=\"Order_ID\", axis=1)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "Q1_data.columns\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(Q1_data)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "Q1_data.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "catogrical_columns = [\"Weather\", \"Traffic_Level\", \"Time_of_Day\"]\n", + "\n", + "Q1_data[catogrical_columns]" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "for col in catogrical_columns:\n", + " Q1_data[col] = Q1_data[col].fillna(Q1_data[col].mode()[0])" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "num_columns = [\"Courier_Experience_yrs\", \"Delivery_Time\"]\n", + "for col in num_columns:\n", + " Q1_data[col] = Q1_data[col].fillna(Q1_data[col].mean())" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "missing_values = Q1_data.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(Q1_data)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 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", + "label_encoders = encode_categorical_columns(Q1_data)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "from sklearn.preprocessing import LabelEncoder\n", + "\n", + "all_catogrical_columns = [\"Weather\", \"Traffic_Level\", \"Time_of_Day\", \"Vehicle_Type\"]\n", + "\n", + "\n", + "label_encoders = {}\n", + "for col in all_catogrical_columns:\n", + " le = LabelEncoder()\n", + " Q1_data[col] = le.fit_transform(Q1_data[col])\n", + " label_encoders[col] = le\n", + "\n", + "Q1_data.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "from sklearn.preprocessing import StandardScaler\n", + "\n", + "numerical_cols = Q1_data.select_dtypes(include=[\"int64\", \"float64\"]).columns.drop(\"Delivery_Time\") # DON'T SCALE THE TARGET\n", + "\n", + "scaler = StandardScaler()\n", + "Q1_data[numerical_cols] = scaler.fit_transform(Q1_data[numerical_cols])\n", + "Q1_data.head()\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import seaborn as sns" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 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(Q1_data, \"Delivery_Time\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "X = Q1_data.drop(\"Delivery_Time\", axis=1).astype(float)\n", + "y = Q1_data['Delivery_Time'].astype(float)\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" + ], + "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, mean_squared_error" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "X" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "y" + ], + "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", + "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": [ + "kfold = KFold(n_splits=5, shuffle=True, random_state=42)\n", + "\n", + "mae_scores = []\n", + "rmse_scores = []\n", + "\n", + "for train_index, test_index in kfold.split(X_train, y_train):\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", + "\n", + " # Calculate metrics\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", + "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": [ + "X.columns" + ], + "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", + "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": [ + "y" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "# Price distribution (target variable)\n", + "plt.figure(figsize=(10, 5))\n", + "plt.hist(Q1_data['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 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/282/Q2.ipynb b/submissions_extracted/282/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..b1f4e2125118647e31dd9d50cb4e6517511fa97a --- /dev/null +++ b/submissions_extracted/282/Q2.ipynb @@ -0,0 +1,502 @@ +{ + "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')\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": [ + "Q2_path = os.path.join(path, 'labels.csv')\n", + "Q2_path" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "Q2_data = pd.read_csv(Q2_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, Dataset\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": [ + "class Age(Dataset):\n", + " def __init__(self, root_dir, split='train', transform=None):\n", + " self.root_dir = root_dir\n", + " self.transform = transform\n", + " self.split = split\n", + "\n", + "\n", + " csv_file = os.path.join(root_dir, f'{split}.csv')\n", + " self.data = pd.read_csv(csv_file)\n", + "\n", + " # Extract image paths and labels from the csv files provided in the dataset\n", + " self.image_paths = self.data['image:FILE'].values\n", + " self.labels = self.data['category'].values\n", + "\n", + " def __len__(self):\n", + " return len(self.image_paths)\n", + "\n", + " def __getitem__(self, idx):\n", + " # Construct full image path\n", + " img_path = os.path.join(self.root_dir, self.image_paths[idx])\n", + "\n", + " # Read imagea\n", + " image = Image.open(img_path).convert('RGB')\n", + " label = float(self.labels[idx]) # Always store your labels in float\n", + "\n", + " # Apply transforms if any\n", + " if self.transform:\n", + " image = self.transform(image)\n", + "\n", + " return image, label" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "train_dataset = Age(path, split='Q2_data', transform=to_tensor)\n", + "valid_dataset = Age(path, split='Q2_data', transform=to_tensor)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 2. Create TensorDataset objects\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, num_workers=2)\n", + "valid_loader = DataLoader(valid_dataset, batch_size=32, shuffle=False, num_workers=2)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 4. Print shape of one batch\n", + "\n", + "images, labels = next(iter(train_loader))\n", + "print(f\"Batch shape: {images.shape}, Labels: {labels}\")" + ], + "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", + "# Define mean & std for denormalization (EfficientNet Preprocessing)\n", + "mean = np.array([0.485, 0.456, 0.406])\n", + "std = np.array([0.229, 0.224, 0.225])\n", + "\n", + "# Display 5 images\n", + "fig, axes = plt.subplots(1, 5, figsize=(15, 5))\n", + "\n", + "imgs_indices = [270,233,110,89,15]\n", + "\n", + "for i in range(5):\n", + " img, label = train_dataset[imgs_indices[i]] # Load image & label\n", + "\n", + " # Convert tensor to numpy for visualization\n", + " img_np = img.numpy().transpose(1, 2, 0) # (C, H, W) → (H, W, C)\n", + "\n", + " # Denormalize the image\n", + " img_np = std * img_np + mean\n", + " img_np = np.clip(img_np, 0, 1)\n", + "\n", + " # Show image\n", + " axes[i].imshow(img_np)\n", + " axes[i].set_title(f'Class: {\"Cat\" if label == 0 else \"Dog\"}')\n", + " axes[i].axis('off')\n", + "\n", + "plt.show()\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", + " # TODO: What are the dimensions of previous and output layer? (hint: hidden neurons? num of classes?)\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", + " a4 = self.relu(z4)\n", + "\n", + " # Output layer TODO\n", + " z5 = self.layer5(a4)\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", + "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": [ + "# 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 4: Define device, model, loss, optimizer:\n", + "# TODO: choose number of epochs, increase it if you have gpus :)\n", + "num_epochs = 15\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)\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 5: Start training for 20 epochs:" + ], + "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')a\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/282/Q3.ipynb b/submissions_extracted/282/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..ea7af9dd22f4dd3e26bbc2a793acd7eb246e1af8 --- /dev/null +++ b/submissions_extracted/282/Q3.ipynb @@ -0,0 +1,321 @@ +{ + "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')\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", + "Q3_path = os.path.join(path, 'Q3_data.csv')\n", + "Q3_data = pd.read_csv(Q3_path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "Q3_data.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "Q3_data.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "Q3_data.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\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(Q3_data)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "Q3_data = Q3_data.fillna(Q3_data.mean())" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "# 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(Q3_data)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\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", + "label_encoders = encode_categorical_columns(Q3_data)" + ], + "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 = Q3_data.select_dtypes(include=[\"int64\", \"float64\"]).columns.drop(\"Target\") # DON'T SCALE THE TARGET\n", + "\n", + "scaler = StandardScaler()\n", + "Q3_data[numerical_cols] = scaler.fit_transform(Q3_data[numerical_cols])\n", + "Q3_data.head()\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\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(Q3_data, \"Target\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "# Task 1: Write your code here:\n", + "X = Q3_data.drop(\"Target\", axis=1).astype(float)\n", + "y = Q3_data['Target'].astype(float)\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" + ], + "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, mean_squared_error" + ], + "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 catboost import CatBoostClassifier\n", + "model = CatBoostClassifier(verbose=0)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "from sklearn.metrics import f1_score" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "skf = KFold(n_splits=5)\n", + "for train_index, test_index in skf.split(X, y):\n", + "\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 = []\n", + " scores_f1.append(f1_score(y_Test, y_pred, average='weighted'))\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "# Retrieve CatBoost feature importances and sort them\n", + "catboost_model = model\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", + "\n", + "# Extract features and their importances\n", + "features, importances = zip(*sorted_catboost_importance)\n", + "\n", + "# Plot feature importances\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 2: Write your code here:\n", + "print(sorted_catboost_importance[0])" + ], + "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/283/Q1.ipynb b/submissions_extracted/283/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..fbe5e26a190b619020f850be99444d94694a29c2 --- /dev/null +++ b/submissions_extracted/283/Q1.ipynb @@ -0,0 +1,427 @@ +{ + "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", + "\n", + "df = pd.read_csv(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": [ + "import matplotlib.pyplot as plt\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('Order_ID', axis=1)" + ], + "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)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# since the missing values are small compared to the data, we can drop them\n", + "df = df.dropna()" + ], + "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": [ + "# Task 3: Write your code here:\n", + "# Do we have duplicate samples? drop if yes\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 OneHotEncoder\n", + "\n", + "# 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", + " print(f\"Encoding column: {col}\")\n", + " ohe = OneHotEncoder(sparse_output=False)\n", + " # Apply fit_transform to one hot encode the column and join the resulting columns to the df\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()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "from sklearn.preprocessing import StandardScaler, MinMaxScaler\n", + "\n", + "numerical_cols = df.select_dtypes(include=[\"number\"]).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": [ + "df.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 6: Write your code here:\n", + "check_target_distribution(df, \"Delivery_Time\") # the target column is similar to a normal distribution" + ], + "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) # don't include the target in X\n", + "y = df['Delivery_Time'].astype(float) # take only the target for 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.metrics import mean_absolute_error\n", + "from sklearn.ensemble import RandomForestRegressor\n", + "import numpy as np\n", + "\n", + "model = RandomForestRegressor(n_estimators=200)\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", + "# Storage for linear regression results for each fold\n", + "lr_losses = []\n", + "lr_mae = []\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", + " print(f\"Training...\")\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", + " lr_mae.append(mae)\n", + "\n", + "print(f\"Average MAE score across all folds: {np.mean(lr_mae)}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Is our model good\n", + "# Calculate the baseline predictions (mean of the target)\n", + "baseline_pred = np.full_like(y, y.mean())\n", + "\n", + "# Evaluate the baseline\n", + "baseline_mae = mean_absolute_error(y, baseline_pred)\n", + "\n", + "print(f\"Baseline MAE (using mean target): {baseline_mae:.4f}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "imp = model.feature_importances_\n", + "\n", + "# Create a 1x3 plot\n", + "fig = plt.figure(figsize=(18, 6))\n", + "features = X.columns\n", + "\n", + "model_name = \"Random Forest\"\n", + " # Sort features by importance for a cleaner plot\n", + "sorted_idx = np.argsort(imp)\n", + "\n", + "plt.barh(features[sorted_idx], imp[sorted_idx])\n", + "plt.title(f\"{model_name} Feature Importance\")\n", + "plt.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", + "predictions = model.predict(X_test)\n", + "plt.figure(figsize=(8, 6))\n", + "\n", + "# Plot: Predicted vs Actual scatter\n", + "plt.scatter(y_test, predictions, 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": [ + "!pip install catboost -q" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:\n", + "from catboost import CatBoostRegressor\n", + "\n", + "models = {\n", + " \"rfr\": RandomForestRegressor(n_estimators=200),\n", + " \"cat\": CatBoostRegressor(verbose=0)\n", + "}\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", + "# Storage for linear regression results for each fold\n", + "lr_losses = []\n", + "lr_mae = []\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", + " print(f\"Training...\")\n", + "\n", + " # Train\n", + " models['cat'].fit(X_train, y_train)\n", + " models['rfr'].fit(X_train, y_train)\n", + "\n", + " # Predict\n", + " y_pred_cat = models['cat'].predict(X_test)\n", + " y_pred_rfr = models['rfr'].predict(X_test)\n", + "\n", + " # Calculate metrics\n", + " mae = mean_absolute_error(y_test, (y_pred_cat + y_pred_rfr) / 2)\n", + "\n", + " # Store results\n", + " lr_mae.append(mae)\n", + "\n", + "print(f\"Average MAE score across all folds: {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/283/Q2.ipynb b/submissions_extracted/283/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..f0a8b84ad944ce1122003b244a8730ca88e813d9 --- /dev/null +++ b/submissions_extracted/283/Q2.ipynb @@ -0,0 +1,443 @@ +{ + "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)" + ], + "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)" + ], + "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", + ")" + ], + "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", + "import numpy as np\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].numpy().transpose(1, 2, 0))\n", + " plt.title(f\"Age: {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", + " # Output layer: hidden layer -> hidden_layer\n", + " self.layer3 = nn.Linear(hidden_dim, hidden_dim)\n", + "\n", + " # Output layer: hidden layer -> number of classes\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.layer3(a2)\n", + " a3 = self.relu(z3)\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", + "\n", + " # Reshape square images into flattened vectors\n", + " # Without changing the batch dimension\n", + " X_batch = X_batch.view(X_batch.size(0), -1)\n", + "\n", + "\n", + " # Move batch to the selected device\n", + " X_batch = X_batch.to(device)\n", + " y_batch = y_batch.to(device).to(torch.long)\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", + "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", + "\n", + " with torch.no_grad():\n", + " for X_batch, y_batch in test_loader:\n", + "\n", + " # Reshape square images into flattened vectors\n", + " # 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).to(torch.long)\n", + "\n", + " # Forward pass\n", + " outputs = model(X_batch)\n", + " loss = criterion(outputs, y_batch)\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": [ + "ages_df = pd.DataFrame(y)\n", + "ages_df.value_counts()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Define device, model, loss, optimizer:\n", + "\n", + "from torch.optim import AdamW, Adam\n", + "\n", + "# choose device\n", + "device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n", + "\n", + "# Model parameters\n", + "input_dim = 3 * 36 * 36 # Image shapes (C, H, W)\n", + "hidden_dim = 20 # Design choice\n", + "output_dim = 111 # Ages\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", + "learning_rate = 0.001\n", + "\n", + "# Define criterion (loss function) - MSE because this is is a regrssion task\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", + "num_epochs = 20\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", + " print(f'Epoch [{epoch+1}/{num_epochs}], Train Loss: {train_loss:.4f}, Val Loss: {val_loss:.4f}')\n", + "\n", + "\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 (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", + "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].numpy().transpose(1, 2, 0), 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/283/Q3.ipynb b/submissions_extracted/283/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..517b4aff26620415ea81e1b5ef26971fc3f2c0bd --- /dev/null +++ b/submissions_extracted/283/Q3.ipynb @@ -0,0 +1,385 @@ +{ + "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", + "\n", + "df = pd.read_csv(path + \"/\" + \"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", + "import pandas as pd\n", + "import numpy as np\n", + "import matplotlib.pyplot as plt\n", + "\n", + "# Columns like D_136 will be removed because the hold too many null values. other columns will be filled with mode or median accordingly\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", + "df = df.drop(missing_data[(missing_data['Missing_Percentage'] > 35)]['Column'], axis=1) # Drop columns with more than 35% of the data missing\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\n", + "\n", + "# Do we have categorical columns? if yes fill with the mode\n", + "categorical_cols = df.select_dtypes(include=[\"object\"]).columns\n", + "\n", + "print(\"Categorical Columns:\", list(categorical_cols))\n", + "\n", + "numrical_columns = df.select_dtypes(include=[\"int64\", \"float64\"]).columns.drop(\"Target\")\n", + "\n", + "print(\"Numerical Columns:\", list(numrical_columns))\n", + "\n", + "df[numrical_columns] = df[numrical_columns].fillna(df[numrical_columns].median())\n", + "\n", + "print(\"No missing data left\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "\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)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "# No categorical. No need for encoding!\n", + "\n", + "# Do we have categorical columns?\n", + "categorical_cols = df.select_dtypes(include=[\"object\"]).columns\n", + "\n", + "print(\"Categorical Columns:\", list(categorical_cols))\n", + "\n", + "print(\"No categorical. No need for encoding!\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "from sklearn.preprocessing import StandardScaler\n", + "\n", + "# Replace 'status' with target\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", + "import seaborn as sns\n", + "\n", + "# Target is imbalance, we need a stratified split!\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", + "\n", + "print(\"Target is imbalance, we need a stratified split!\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "\n", + "X = df.drop(\"Target\", axis=1).astype(float) # don't include the target in X\n", + "y = df['Target'].astype(float) # take only the target for y" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "%pip install catboost -q" + ], + "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 StratifiedKFold\n", + "from sklearn.metrics import accuracy_score, f1_score\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", + "model = CatBoostClassifier(\n", + " verbose=0,\n", + " n_estimators=320,\n", + " max_depth=4\n", + " )\n", + "\n", + "accuracy = []\n", + "f1 = []\n", + "\n", + "# Binary\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", + " 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.append(accuracy_score(y_test, y_pred))\n", + " f1.append(f1_score(y_test, y_pred, zero_division=0))\n", + "\n", + "\n", + "print(f\"Average F1-Score: {np.mean(f1)}\") # F1 Score is the appropriate metric for this data since the target is imbalanced\n", + "print(f\"Average Accuracy: {np.mean(accuracy)}\")\n", + "print(\"F1 Score is the appropriate metric for this data since the target is imbalanced\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "imp = model.feature_importances_\n", + "\n", + "# Create a 1x3 plot\n", + "fig = plt.figure(figsize=(18, 6))\n", + "features = X.columns\n", + "\n", + "model_name = \"Random Forest\"\n", + " # Sort features by importance for a cleaner plot\n", + "sorted_idx = np.argsort(imp)\n", + "\n", + "plt.barh(features[sorted_idx], imp[sorted_idx])\n", + "plt.title(f\"{model_name} Feature Importance\")\n", + "plt.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", + "\n", + "absolute_coef = np.abs(model.feature_importances_)\n", + "sorted_idx = np.argsort(absolute_coef)\n", + "\n", + "\n", + "golden_feature = X.columns[sorted_idx[-1]]\n", + "\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", + "golden_X = X[[golden_feature]]\n", + "golden_X" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "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(\n", + " verbose=0,\n", + " n_estimators=320,\n", + " max_depth=4\n", + " )\n", + "\n", + "accuracy = []\n", + "f1 = []\n", + "\n", + "# Binary\n", + "\n", + "for fold_idx, (train_index, test_index) in enumerate(skf.split(golden_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", + " 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.append(accuracy_score(y_test, y_pred))\n", + " f1.append(f1_score(y_test, y_pred, zero_division=0))\n", + "\n", + "\n", + "print(f\"Average F1-Score: {np.mean(f1)}\") # F1 Score is the appropriate metric for this data since the target is imbalanced\n", + "print(f\"Average Accuracy: {np.mean(accuracy)}\")\n", + "print(\"F1 Score is the appropriate metric for this data since the target is imbalanced\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# The score is identical to the one with the features\n", + "# Scores including the other features:\n", + "# Average F1-Score: 0.6839714785086035\n", + "# Average Accuracy: 0.8366082854286429" + ], + "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/284/Q1.ipynb b/submissions_extracted/284/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..ca26bd4da77e686bb400f8029f98150d045342c6 --- /dev/null +++ b/submissions_extracted/284/Q1.ipynb @@ -0,0 +1,257 @@ +{ + "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", + "a = os.path.join(path, \"Q1_data.csv\")\n", + "df = pd.read_csv(a)" + ], + "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'])\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\"])\n", + "df_clean.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "df_clean = df_clean.dropna(subset= ['Weather', \"Traffic_Level\", \"Time_of_Day\", \"Courier_Experience_yrs\", \"Delivery_Time\"])\n", + "df_clean.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "df_clean.drop_duplicates(inplace=True)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "import numpy as np\n", + "import matplotlib.pyplot as plt\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", + "categorical_cols = ['Vehicle_Type', 'Time_of_Day', 'Traffic_Level', '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()" + ], + "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", + "\n", + "df_clean.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 6: Write your code here:\n", + "# our target is a cont value, so no such thing" + ], + "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" + ], + "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", + "n_splits = 5 # K=5 Folds\n", + "\n", + "# 5-Fold, shuffled\n", + "kf = KFold(n_splits=n_splits, shuffle=True, random_state=42)\n", + "\n", + "mse_scores = []\n", + "model = RandomForestRegressor()\n", + "for fold, (train_idx, test_idx) in enumerate(kf.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", + " # instantiate\n", + " model.fit(X_train, y_train) # fit\n", + " y_pred = model.predict(X_test) # predict\n", + "\n", + " mse_scores.append(mean_squared_error(y_test, y_pred))\n", + "\n", + "print(np.mean(mse_scores))" + ], + "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.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 (Ground Truth)\")\n", + "plt.ylabel(\"Predicted\")\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/284/Q2.ipynb b/submissions_extracted/284/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..a8a5e183a7a831cdf1fbe5636e5f0da9e26bd38e --- /dev/null +++ b/submissions_extracted/284/Q2.ipynb @@ -0,0 +1,429 @@ +{ + "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", + "# 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", + "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", + "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", + "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", + "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", + " # TODO: What are the dimensions of the first layer? (hint: features? hidden neurons?)\n", + " self.layer1 = nn.Linear(input_dim, 100)\n", + "\n", + " # TODO: What are the dimensions from previous and next layer?\n", + " self.layer2 = nn.Linear(100, 50)\n", + "\n", + " # TODO: What are the dimensions from previous and next layer?\n", + " self.layer3 = nn.Linear(50, 10)\n", + "\n", + " # TODO: What are the dimensions from previous and next layer?\n", + " self.layer4 = nn.Linear(10, 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", + " return z4" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your training loop here:\n", + "from sklearn.metrics import mean_squared_error\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\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 = 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\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", + "\n", + " running_loss = running_loss + loss.item()\n", + "\n", + " avg_val_loss = running_loss / len(train_loader)\n", + "\n", + " return avg_val_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", + "# 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 = 200 # 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: 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.MSELoss()\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", + "\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", + " 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", + "\n", + "print(train_losses)\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", + "\n", + "# Task 3: Write your validation loop here:\n", + "def validateBonus(model, criterion, test_loader, device):\n", + " # Set the model to evaluation mode\n", + " model.eval()\n", + "\n", + " running_loss = 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", + "\n", + " running_loss = running_loss + loss.item()\n", + "\n", + " avg_val_loss = running_loss / len(train_loader)\n", + "\n", + " return outputs\n", + "\n", + "\n", + "# 5. Display sample images\n", + "labels = validateBonus(model, criterion, test_loader, device)\n", + "images, _= next(iter(test_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": [] + } + ], + "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/284/Q3.ipynb b/submissions_extracted/284/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..55a8f31ec354cfccc54f290bd373ae99f4f00141 --- /dev/null +++ b/submissions_extracted/284/Q3.ipynb @@ -0,0 +1,210 @@ +{ + "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", + "a = os.path.join(path, \"Q3_data.csv\")\n", + "df = pd.read_csv(a)" + ], + "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", + "f = df.drop(axis=1, [\"Target\"]).columns\n", + "df_clean = df.dropna(subset = f , axis=1).T\n", + "df_clean.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "cols = df_clean.drop([\"Target\"]).columns\n", + "print(cols)\n", + "df2 = df_clean.drop_duplicates(subset=cols)\n", + "df2.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "# no catagorical data to encode" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "from sklearn.preprocessing import StandardScaler\n", + "print(df_clean.head())\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", + "\n", + "df_clean.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_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", + "from sklearn.model_selection import KFold\n", + "\n", + "n_splits = 5 # K=5 Folds\n", + "\n", + "# 5-Fold, shuffled\n", + "kf = KFold(n_splits=n_splits, shuffle=True, random_state=42)\n", + "\n", + "!pip install catboost\n", + "from catboost import CatBoostClassifier\n", + "model = CatBoostClassifier(verbose=0, n_estimators=320, max_depth=4)\n", + "lr_f1 = []\n", + "for fold, (train_idx, test_idx) in enumerate(kf.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", + " # instantiate\n", + " model.fit(X_train, y_train) # fit\n", + " y_pred = model.predict(X_test) # predict\n", + "\n", + " f1 = f1_score(y_test, y_pred, zero_division=0)\n", + " lr_f1.append(f1)\n", + "\n", + "print(f1)" + ], + "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/285/Q1.ipynb b/submissions_extracted/285/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..f3cae37d6565f4f6d7943fe7a41aa5fdf5f75127 --- /dev/null +++ b/submissions_extracted/285/Q1.ipynb @@ -0,0 +1,349 @@ +{ + "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 seaborn as sns\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": [ + "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)\n", + "\n", + "print(f\"Shape: {df_Q1.shape}\")\n", + "df_Q1.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "df_Q1.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "print(\"Missing values:\")\n", + "print(df_Q1.isnull().sum())" + ], + "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", + "plt.figure(figsize=(10, 5))\n", + "plt.hist(df_Q1['Delivery_Time'].dropna(), bins=30, edgecolor='black')\n", + "plt.title('Delivery_Time Distribution')\n", + "plt.xlabel('Delivery')\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' ,'Preparation_Time_min', 'Courier_Experience_yrs','Delivery_Time']\n", + "df_clean = df_Q1[cols].copy()\n", + "df_clean = df_clean.dropna(subset=['Order_ID'])\n", + "print(f\"After dropping missing Order_ID : {df_clean.shape}\")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "for col in ['Distance_km' ,'Preparation_Time_min', 'Courier_Experience_yrs','Delivery_Time']:\n", + " df_clean[col] = df_clean[col].fillna('unknown')\n", + "df_clean['Preparation_Time_min'] = df_clean['Preparation_Time_min'].fillna(df_clean['Preparation_Time_min'].mode()[0])\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_Q1):\n", + " duplicates = df_Q1.duplicated().sum()\n", + " print(f\"Number of Duplicate Samples: {duplicates}\")\n", + " if duplicates > 0:\n", + " print(\"Dropping Duplicates...\")\n", + " df_Q1.drop_duplicates(inplace=True)\n", + " print(\"Duplicates Dropped.\")\n", + " else:\n", + " print(\"No Duplicate Samples Found.\")\n", + "\n", + "check_duplicates(df_Q1)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "\n", + "categorical_cols = df_Q1.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 OneHotEncoder #import OneHotEncoder\n", + "\n", + "print('data before encoding:\\n', df_Q1) #show before encoding\n", + "\n", + "onehot_encoder = OneHotEncoder(sparse_output=False) # Instantiate OneHotEncoder\n", + "data_onehot_encoded = onehot_encoder.fit_transform(df_Q1)\n", + "\n", + "print('\\nData after encoding:\\n', data_onehot_encoded)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "data_for_scale = pd.DataFrame({\"Preparation_Time_min\": [12, 20, 28,15],\"Delivery_Time\": [43, 84, 95,77]})\n", + "\n", + "print(\"Before scaling:\")\n", + "data_for_scale\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "from sklearn.preprocessing import StandardScaler\n", + "print('data before scaling:\\n', data_for_scale)\n", + "standard_scaler = StandardScaler()\n", + "data_standard_scaled = standard_scaler.fit_transform(data_for_scale)\n", + "print('\\nData after scaling:\\n', data_standard_scaled)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "df_Q1['Delivery_Time'] = df_Q1['Delivery_Time'].map({'Placed': 1, 'Not Placed': 0})\n", + "\n", + "# Drop unnecessary columns\n", + "df = df_Q1.drop(['Delivery_Time'], axis=1)\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", + " 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_Q1, \"Delivery_Time\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "feature_cols = ['Order_ID',\t'Distance_km' ,'Preparation_Time_min', 'Courier_Experience_yrs','Delivery_Time']\n", + "X = df_clean[feature_cols]\n", + "y = df_clean['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", + "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 (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": [ + "lr_losses = []\n", + "lr_mse = []\n", + "lr_rmse = []\n", + "lr_r2 = []" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "plt.figure(figsize=(10, 5))\n", + "plt.hist(df_Q1['Preparation_Time_min'].dropna(), bins=30, edgecolor='black', color='yellow')\n", + "plt.title('Preparation_Time_min')\n", + "plt.xlabel('Preparation_Time_min')\n", + "plt.ylabel('Frequency')\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/285/Q2.ipynb b/submissions_extracted/285/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..8ad75381831b35a0a07f266591fa16c130420519 --- /dev/null +++ b/submissions_extracted/285/Q2.ipynb @@ -0,0 +1,244 @@ +{ + "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", + "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", + "\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:\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!')" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2 (Bonus): 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": [] + } + ], + "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/285/Q3.ipynb b/submissions_extracted/285/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..eb9fe9dd062425624e0561d2916b974466dcca6f --- /dev/null +++ b/submissions_extracted/285/Q3.ipynb @@ -0,0 +1,282 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "import pandas as pd\n", + "import numpy as np\n", + "import os\n", + "import seaborn as sns\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", + "\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)\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "Q1_path = os.path.join(path, 'Q3_data.csv')\n", + "df_Q3 = pd.read_csv(Q1_path)\n", + "\n", + "print(f\"Shape: {df_Q3.shape}\")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "df_Q3.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "df_Q3.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "df_Q3.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "cols = ['P_2','D_39','B_1','B_2','R_1']\n", + "df_clean = df_Q3[cols].copy()\n", + "print(f\"Before: {df_clean.shape}\")\n", + "df_clean = df_clean.dropna(subset=['P_2','D_39','B_1'])\n", + "print(f\"After dropping missing P_2','D_39','B_1': {df_clean.shape}\")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "def check_duplicates(df_Q3):\n", + " duplicates = df_Q3.duplicated().sum()\n", + " print(f\"Number of Duplicate Samples: {duplicates}\")\n", + " if duplicates > 0:\n", + " print(\"Dropping Duplicates...\")\n", + " df_Q3.drop_duplicates(inplace=True)\n", + " print(\"Duplicates Dropped.\")\n", + " else:\n", + " print(\"No Duplicate Samples Found.\")\n", + "\n", + "check_duplicates(df_Q3)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "from sklearn.preprocessing import OneHotEncoder #import OneHotEncoder\n", + "\n", + "print('data before encoding:\\n', df_Q3) #show before encoding\n", + "\n", + "onehot_encoder = OneHotEncoder(sparse_output=False) # Instantiate OneHotEncoder\n", + "data_onehot_encoded = onehot_encoder.fit_transform(df_Q3)\n", + "\n", + "print('\\nData after encoding:\\n', data_onehot_encoded)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "data_for_scale = pd.DataFrame({\"D_39\": [80, 5, 28,15],\"B_1\": [43, 84, 95,77]})\n", + "\n", + "print(\"Before scaling:\")\n", + "data_for_scale\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "from sklearn.preprocessing import StandardScaler\n", + "print('data before scaling:\\n', data_for_scale)\n", + "standard_scaler = StandardScaler()\n", + "data_standard_scaled = standard_scaler.fit_transform(data_for_scale)\n", + "print('\\nData after scaling:\\n', data_standard_scaled)" + ], + "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() # Yeah you can just do this :)\n", + " plt.show()\n", + "\n", + "check_target_imbalance(df_Q3, \"D_39\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\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 2,3,4,5: Write your code here:\n", + "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": [ + "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", + "plt.figure(figsize=(10, 5))\n", + "plt.hist(df_Q3['D_39'].dropna(), bins=30, edgecolor='black', color='yellow')\n", + "plt.title('D_39')\n", + "plt.xlabel('D_39')\n", + "plt.ylabel('Frequency')\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/286/Q1.ipynb b/submissions_extracted/286/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..46a6d172f3251c9ab74d53e358d478231cc5ba40 --- /dev/null +++ b/submissions_extracted/286/Q1.ipynb @@ -0,0 +1,339 @@ +{ + "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", + "%matplotlib inline\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", + "# Load the dataset\n", + "food_path = os.path.join(path, 'Q1_data.csv')\n", + "df_food = pd.read_csv(food_path)\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", + "# food delivry distribution (target variable)\n", + "plt.figure(figsize=(10, 5))\n", + "plt.hist(df_food['Delivery_Time'].dropna(), bins=50, edgecolor='black')\n", + "plt.title('food delivry 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_food.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_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(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)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "\n", + "categorical_cols = df_food(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()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "\n", + "# [HINT]: Select numerical columns, but drop \"price\" from the list\n", + "\n", + "numerical_cols = df_food(include=[\"number\"]).columns.drop(\"Distance_km, Weather, Traffic_Level, Time_of_Day,Vehicle_Type , Preparation_Time_min , Courier_Experience_yrs,Delivery_Time\")\n", + "\n", + "scaler = StandardScaler()\n", + "\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", + "\n", + "# i dont have time ti ssa imbalanced" + ], + "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 = ['Distance_km', 'Weather', 'Traffic_Level', 'Time_of_Day',\n", + " 'Vehicle_Type', 'Preparation_Time_min', 'Courier_Experience_yrs', 'Delivery_Time']\n", + "X = df_food.clean[feature_cols]\n", + "y = df_food.clean['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", + "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}\")\n", + "\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.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", + "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": [] + }, + { + "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/286/Q2.ipynb b/submissions_extracted/286/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..7ca2a147751679e081a1fb1b07dbf3b34bccb9f8 --- /dev/null +++ b/submissions_extracted/286/Q2.ipynb @@ -0,0 +1,418 @@ +{ + "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 torchvision.datasets import CIFAR10\n", + "from torchvision.transforms.functional import to_tensor\n", + "from torch.utils.data import DataLoader\n", + "import torch.nn as nn\n", + "import torch.nn.functional as F\n", + "import torch\n", + "from torch.optim import AdamW\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/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", + "# 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", + "\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", + "\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}\")" + ], + "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", + "# 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}\")" + ], + "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, hidden_dim)\n", + "\n", + "\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", + "\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)\n", + " y_batch = y_batch.to(device)\n", + "\n", + " # Forward pass\n", + " # make predictions\n", + " outputs = model(X_batch) # shape: (batch_size, 10)\n", + " # 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", + " # make predictions\n", + " outputs = model(X_batch) # shape: (batch_size, 10)\n", + " # compute loss\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", + " # 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 = 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 = 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", + "\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", + "# Hyperparameters\n", + "num_epochs = 20\n", + "learning_rate = 0.001" + ], + "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:# 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", + "# [HINT]: Use sklearn metrics - mean_absolute_error, mean_squared_error, r2_score\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}\")" + ], + "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/286/Q3.ipynb b/submissions_extracted/286/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..0b04781d85eec73375a5f583ed7836606df7ce0d --- /dev/null +++ b/submissions_extracted/286/Q3.ipynb @@ -0,0 +1,197 @@ +{ + "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", + "\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", + "golden_path = os.path.join(path, 'Q3_data.csv')\n", + "df_golden = pd.read_csv(golden_path)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "df_golden.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "df_golden.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "df_golden.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "# Analyze missing values\n", + "missing_percentage = (df_golden.isnull().sum() / len(df_golden)) * 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:" + ], + "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/287/Q1.ipynb b/submissions_extracted/287/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..4e92e89ecb70d3c47f5b16de73b0e9de21eaa16c --- /dev/null +++ b/submissions_extracted/287/Q1.ipynb @@ -0,0 +1,417 @@ +{ + "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.preprocessing import StandardScaler, LabelEncoder, OneHotEncoder, MinMaxScaler\n", + "from sklearn.model_selection import KFold\n", + "from sklearn.ensemble import RandomForestRegressor\n", + "from sklearn.metrics import mean_absolute_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", + "full_path = os.path.join(path, 'Q1_data.csv')\n", + "df = pd.read_csv(full_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 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('target')\n", + "plt.ylabel('Frequency')\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "df.drop([\"Order_ID\"], axis=1, inplace=True)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "# Let us see the proportion of each feature\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": [ + "# And this is the total number of each one\n", + "df.isnull().sum()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Let us start with filling the categories features\n", + "# Fill categorical columns with 'unknown' - missing likely means \"not specified\"\n", + "df_clean = df.copy()\n", + "for col in ['Weather', 'Traffic_Level', 'Time_of_Day']:\n", + " df_clean[col] = df_clean[col].fillna('unknown')\n", + "\n", + "df_clean.isnull().sum()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Now it is time to work on each numerical feature # for me I prefer to give it each missing with the mean\n", + "for col in ['Courier_Experience_yrs', 'Delivery_Time']:\n", + " df_clean[col] = df_clean[col].fillna(df[col].mean())\n", + "\n", + "df_clean.isnull().sum()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "df_clean.duplicated().sum() # there are 557 dubs" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "df_clean = df_clean.drop_duplicates()\n", + "df_clean.duplicated().sum()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "df_clean.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "# It is time to label encode all of the categories as LabelEncoder # except one feature \"Traffic_Level\" that is order and it is best to make it OneHot # but I couldn't do it due to an error please if you are reading this try to do it and you will understand me\n", + "\n", + "# Encode categorical columns - converts text to integers\n", + "le = LabelEncoder()\n", + "categorical_cols = ['Weather', 'Time_of_Day', 'Vehicle_Type', \"Traffic_Level\"]\n", + "for col in categorical_cols:\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.drop([\"Delivery_Time\"], axis=1) # we must not include the target\n", + "scaler = StandardScaler()\n", + "X_scaled = scaler.fit_transform(X)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "X_scaled # is is scaled now" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 6: Write your code here:\n", + "df_clean[\"Delivery_Time\"].value_counts()\n", + "\n", + "\n", + "Delivery_Time = df_clean[\"Delivery_Time\"].value_counts()\n", + "\n", + "\n", + "plt.figure(figsize=(10, 5))\n", + "plt.bar(Delivery_Time.index, Delivery_Time.values, color='coral')\n", + "plt.title('Delivery_Time Distribution')\n", + "plt.xlabel('Condition')\n", + "plt.ylabel('Count')\n", + "plt.xticks(rotation=45)\n", + "plt.grid()\n", + "plt.show()\n", + "\n", + "# We can say that it is imbalanced due to the different scale here (around the 60)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "# X_scaled already did it before in part two\n", + "y = df_clean[\"Delivery_Time\"].to_numpy()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "X_scaled[:5], y[:5]" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:\n", + "# Define Model\n", + "model = RandomForestRegressor()\n", + "\n", + "# K-Fold Cross Validation\n", + "kf = KFold(n_splits=5, shuffle=True, random_state=42)\n", + "mae_scores = []\n", + "i = 0\n", + "for train_idx, test_idx in kf.split(X_scaled):\n", + " X_train, X_test = X_scaled[train_idx], X_scaled[test_idx]\n", + " y_train, y_test = y[train_idx], y[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", + " # Print Evaluation Metrics\n", + " print(f\"K-Fold {i + 1}\")\n", + " print(f\"MAE {mae_scores[i]}\")\n", + " print(\"-\"*40)\n", + " i+=1\n", + "\n", + "\n", + "# 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": [ + "df_clean.columns" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "# Feature importance\n", + "\n", + "# must have those:\n", + "feature_cols = ['Distance_km', 'Weather', 'Traffic_Level', 'Time_of_Day',\n", + " 'Vehicle_Type', 'Preparation_Time_min', 'Courier_Experience_yrs']\n", + "\n", + "# + model (sklearn)\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", + "y_pred = model.predict(X_test)\n", + "# len(y_pred), len(y_test) same len\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "plt.figure(figsize=(10, 5))\n", + "plt.hist(y_pred, bins=50, edgecolor='black')\n", + "plt.title('y_pred distribution')\n", + "plt.xlabel('target')\n", + "plt.ylabel('Frequency')\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "plt.figure(figsize=(10, 5))\n", + "plt.hist(y_test, bins=50, edgecolor='black')\n", + "plt.title('y_test distribution')\n", + "plt.xlabel('target')\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/287/Q2.ipynb b/submissions_extracted/287/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..9e7ac5ac84aca010c03841b21145bb6c87b7b10b --- /dev/null +++ b/submissions_extracted/287/Q2.ipynb @@ -0,0 +1,403 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# IGNORE IT THIS IS FROM ME;)\n", + "\n", + "from sklearn.datasets import load_breast_cancer\n", + "from sklearn.model_selection import train_test_split\n", + "from sklearn.preprocessing import StandardScaler, LabelEncoder\n", + "from torch.utils.data import TensorDataset\n", + "from torch.utils.data import DataLoader\n", + "import torch\n", + "import numpy as np\n", + "import pandas as pd\n", + "import matplotlib.pyplot as plt\n", + "import kagglehub\n", + "import os\n", + "import torch.nn as nn\n", + "import torch.nn.functional as F\n", + "from torchvision.datasets import MNIST\n", + "from torchvision.transforms.functional import to_tensor\n", + "from sklearn.metrics import 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/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", + "# 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", + "# 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", + "\n", + "# Create Dataloaders to train and test data in batches\n", + "train_loader = DataLoader(train_dataset, batch_size=64, shuffle=True)\n", + "test_loader = DataLoader(test_dataset, batch_size=64, shuffle=False)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 4. Print shape of one batch\n", + "\n", + "sample, label = train_dataset[0]\n", + "\n", + "print(sample.shape) # I don't know how to print it from train_loader but I can do it in train_dataset" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 5. Display sample images\n", + "\n", + "plt.title(f\"Age = {label}\")\n", + "plt.imshow(sample[0], cmap=\"gray\") # it is okay to user either channel because I am making them in gray ;)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your model class here:\n", + "class NNLayer(nn.Module):\n", + "\n", + " def __init__(self, input_dim, hidden_dim):\n", + "\n", + " super(NNLayer, self).__init__()\n", + "\n", + " self.layer_1 = nn.Linear(input_dim, hidden_dim)\n", + " self.layer_2 = nn.Linear(hidden_dim, hidden_dim)\n", + " self.layer_3 = nn.Linear(hidden_dim, hidden_dim)\n", + " self.layer_4 = nn.Linear(hidden_dim, 1)\n", + "\n", + " # non-linearity activation function\n", + " self.relu = nn.ReLU()\n", + "\n", + " # forward pass\n", + " def forward(self, x):\n", + " z1 = self.layer_1(x)\n", + " a1 = self.relu(z1)\n", + "\n", + " z2 = self.layer_2(a1)\n", + " a2 = self.relu(z2)\n", + "\n", + " z3 = self.layer_3(a2)\n", + " a3 = self.relu(z3)\n", + "\n", + " y_pred = self.layer_4(a3)\n", + "\n", + "\n", + "\n", + " return y_pred" + ], + "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) # shape: (batch_size, num_features)\n", + " y_batch = y_batch.to(device) # shape: (batch_size,)\n", + "\n", + "\n", + " # if using MINST (UNCOMMENT):\n", + " # FIX: flatten MNIST image to vector\n", + " X_batch = X_batch.view(X_batch.size(0), -1)\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", + "\n", + " # Average loss over all batches + accuracy\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.to(device) # shape: (batch_size,)\n", + "\n", + "\n", + " # if using MINST (UNCOMMENT):\n", + " # FIX: flatten MNIST image to vector\n", + " X_batch = X_batch.view(X_batch.size(0), -1)\n", + "\n", + " # Forward pass\n", + " outputs = model(X_batch)\n", + " loss = criterion(outputs, y_batch)\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", + "\n", + "# Device setup\n", + "device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n", + "\n", + "hidden_dim = 67 # Lucky number I guess ;)\n", + "input_dim = 3 * 36 * 36 # 3888\n", + "\n", + "model = NNLayer(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", + "\n", + "print(f\"\\nTotal trainable parameters: {total_params}\")\n", + "\n", + "\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 = torch.optim.AdamW(model.parameters(), lr=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", + " 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": [ + "X_test[0].shape" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2 (Bonus): Write your code here:\n", + "\n", + "test_from_me = model(X_test[0].reshape(1,-1))\n", + "test_from_me" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "plt.title(f\"Age Ground Truth = {int(y_test[0])}\\n Age Prediction Model = {int(test_from_me.item())}\")\n", + "plt.imshow(X_test[0][0], cmap=\"gray\")" + ], + "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/287/Q3.ipynb b/submissions_extracted/287/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..85cd7cb07babc1f007b6d13719422ba42671c27d --- /dev/null +++ b/submissions_extracted/287/Q3.ipynb @@ -0,0 +1,468 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "!pip install catboost" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "#Ignore it this is from me\n", + "\n", + "import numpy as np\n", + "import pandas as pd\n", + "import matplotlib.pyplot as plt\n", + "import os\n", + "from sklearn.preprocessing import StandardScaler, LabelEncoder, OneHotEncoder, MinMaxScaler\n", + "from sklearn.model_selection import KFold, StratifiedKFold\n", + "from sklearn.ensemble import RandomForestRegressor\n", + "from sklearn.metrics import f1_score, accuracy_score\n", + "from catboost import CatBoostClassifier" + ], + "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", + "full_path = os.path.join(path, 'Q3_data.csv')\n", + "df = pd.read_csv(full_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": [ + "df" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "# Let us see the proportion of each feature\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": [ + "# And this is the total number of each one\n", + "df.isnull().sum()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "df.dtypes.unique() # since they are all numerical values (no categoricals) so we will handle it in a numerical way" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# it is time to work on each numerical feature # for me I prefer to give it each missing with the mean\n", + "df_clean = df.copy()\n", + "for col in df.columns:\n", + " df_clean[col] = df_clean[col].fillna(df[col].mean())\n", + "\n", + "df_clean.isnull().sum()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Analyze missing values for clean\n", + "missing_percentage = (df_clean.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", + "df_clean.duplicated().sum() # there are no dubs" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "# There are no categorical variables, and as we can see below the traget label already encoded\n", + "df_clean[\"Target\"].value_counts()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "\n", + "X = df_clean.drop([\"Target\"], axis=1) # we must not include the target\n", + "scaler = StandardScaler()\n", + "X_scaled = scaler.fit_transform(X)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "df_clean.shape" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "X_scaled.shape # just removed the target label and scaled it" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "# Condition distribution\n", + "\n", + "\n", + "plt.figure(figsize=(10, 5))\n", + "plt.bar(df_clean['Target'].unique(),df_clean['Target'].value_counts(), color='green')\n", + "plt.title('Target Distribution')\n", + "plt.xlabel('Condition')\n", + "plt.ylabel('Count')\n", + "plt.xticks(rotation=45)\n", + "plt.grid()\n", + "plt.show()\n", + "\n", + "# As we can see here it is clearly that the target is imbalanced (most of them are No Default)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "# X_scaled already did it before in part two\n", + "y = df_clean[\"Target\"].to_numpy()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "X_scaled.shape, y.shape" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:\n", + "\n", + "# Define Model\n", + "model = CatBoostClassifier()\n", + "\n", + "# K-Fold Cross Validation\n", + "kf = KFold(n_splits=5, shuffle=True, random_state=42)\n", + "f1 = []\n", + "accuracy = []\n", + "i = 0\n", + "for train_idx, test_idx in kf.split(X_scaled):\n", + " X_train, X_test = X_scaled[train_idx], X_scaled[test_idx]\n", + " y_train, y_test = y[train_idx], y[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.append(accuracy_score(y_test, y_pred))\n", + " f1.append(f1_score(y_test, y_pred))\n", + "\n", + " # Print Evaluation Metrics\n", + " print(f\"K-Fold {i + 1}\")\n", + " print(f\"Accuracy {accuracy[i]}\")\n", + " print(f\"F1 {f1[i]}\")\n", + " print(\"-\"*40)\n", + " i+=1\n", + "\n", + "\n", + "# Print Evaluation Metrics\n", + "print(\"\\nModel Evaluation Metrics (K-Fold)\\n\" + \"-\"*40)\n", + "print(f\"Accuracy Avg : {np.mean(accuracy):.2f}\")\n", + "print(f\"F1 Avg : {np.mean(f1):.2f}\")\n", + "print(\"-\"*40)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "df_clean.columns" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "# must have those:\n", + "feature_cols = df_clean.drop([\"Target\"], axis=1).columns\n", + "\n", + "# + model (sklearn)\n", + "\n", + "feature_importance = pd.DataFrame({\n", + " 'feature': feature_cols[:10],\n", + " 'importance': model.feature_importances_[:10]\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", + "\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "\n", + "# due to the large number of features I printed the first 10, and finally I can say:\n", + "# I FOUND THE GOLDEN FEATURE !!\n", + "\n", + "# it is: \"P_2\"" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:\n", + "X_bonus = df_clean[\"P_2\"].to_numpy()\n", + "scaler = StandardScaler()\n", + "X_scaled_bonus = scaler.fit_transform(X_bonus.reshape(-1,1))" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "X_scaled_bonus.shape, y.shape" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:\n", + "\n", + "# Define Model\n", + "model = CatBoostClassifier()\n", + "\n", + "# K-Fold Cross Validation\n", + "kf = KFold(n_splits=5, shuffle=True, random_state=42)\n", + "f1 = []\n", + "accuracy = []\n", + "i = 0\n", + "for train_idx, test_idx in kf.split(X_scaled_bonus):\n", + " X_train, X_test = X_scaled_bonus[train_idx], X_scaled_bonus[test_idx]\n", + " y_train, y_test = y[train_idx], y[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.append(accuracy_score(y_test, y_pred))\n", + " f1.append(f1_score(y_test, y_pred))\n", + "\n", + " # Print Evaluation Metrics\n", + " print(f\"K-Fold {i + 1}\")\n", + " print(f\"Accuracy {accuracy[i]}\")\n", + " print(f\"F1 {f1[i]}\")\n", + " print(\"-\"*40)\n", + " i+=1\n", + "\n", + "\n", + "# Print Evaluation Metrics\n", + "print(\"\\nModel Evaluation Metrics (K-Fold)\\n\" + \"-\"*40)\n", + "print(f\"Accuracy Avg : {np.mean(accuracy):.2f}\")\n", + "print(f\"F1 Avg : {np.mean(f1):.2f}\")\n", + "print(\"-\"*40)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# For golden feature, this is the result:\n", + "\n", + "# Model Evaluation Metrics (K-Fold)\n", + "# ----------------------------------------\n", + "# Accuracy Avg : 0.79\n", + "# F1 Avg : 0.58\n", + "# ----------------------------------------\n", + "\n", + "\n", + "# For the whole features, this is the result\n", + "\n", + "\n", + "# Model Evaluation Metrics (K-Fold)\n", + "# ----------------------------------------\n", + "# Accuracy Avg : 0.84\n", + "# F1 Avg : 0.70\n", + "# ----------------------------------------\n", + "\n", + "\n", + "\n", + "# \"More features are better than a single one\"\n", + "# of course, but as we can see here the result for golden feature is not that bad since it is single and achive that, I think it is great ;)" + ], + "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/288/Q1.ipynb b/submissions_extracted/288/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..c3bab25a2ada5cbbc181ef726e0b9427e13baf32 --- /dev/null +++ b/submissions_extracted/288/Q1.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 os\n", + "\n", + "from sklearn.model_selection import train_test_split, KFold, StratifiedKFold\n", + "from sklearn.preprocessing import StandardScaler, MinMaxScaler, LabelEncoder, OneHotEncoder\n", + "from sklearn.impute import SimpleImputer\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: Read the dataset Q1_data.csv using read_csv()\n", + "csv_file_path = os.path.join(path, 'Q1_data.csv')\n", + "\n", + "df = pd.read_csv(csv_file_path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:Inspect the first few rows using head()\n", + "print(f\"Shape: {df.shape}\")\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:Display dataset information using info()\n", + "df.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:Show statistical description using describe()\n", + "df.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:Plot the target distribution (delivery_time)\n", + "\n", + "import matplotlib.pyplot as plt\n", + "import seaborn as sns\n", + "\n", + "plt.figure(figsize=(10, 5))\n", + "plt.hist(df['Delivery_Time'], bins=30, 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:Drop the 'Order_ID' column from the data\n", + "df = df.drop(columns=['Order_ID'])" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:Handle missing values appropriately (Hint: I guess you want to have a closer look at the columns with missing values :) )\n", + "print(\"Missing values per column:\")\n", + "print(df.isnull().sum())\n", + "print(f\"\\nTotal missing: {df.isnull().sum().sum()}\")\n", + "\n", + "df['Weather'] = df['Weather'].fillna('unknown')\n", + "df['Traffic_Level'] = df['Traffic_Level'].fillna('unknown')\n", + "df['Time_of_Day'] = df['Time_of_Day'].fillna('unknown')\n", + "df['Courier_Experience_yrs'] = df['Courier_Experience_yrs'].fillna('unknown')\n", + "df['Delivery_Time'] = df['Delivery_Time'].fillna('unknown')\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:Check and remove duplicates if any exist\n", + "print(f\"Duplicates: {df.duplicated().sum()}\")\n", + "df.drop_duplicates(inplace=True)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:Encode categorical variables if needed (Bonus if used One Hot Encoding)\n", + "from sklearn.preprocessing import LabelEncoder\n", + "categorical_cols = df.select_dtypes(include=['object']).columns\n", + "for col in categorical_cols:\n", + " le = LabelEncoder()\n", + " df[col] = le.fit_transform(df[col].astype(str))" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:Apply feature scaling for all features (Use StandardScaler)\n", + "from sklearn.preprocessing import StandardScaler\n", + "scaler = StandardScaler()\n", + "dff = scaler.fit_transform(df)" + ], + "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", + "X = df.drop(columns=['Delivery_Time'])\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 train_test_split\n", + "from sklearn.ensemble import RandomForestRegressor\n", + "\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", + ")\n", + "print(f\"Train: {X_train.shape}, Test: {X_test.shape}\")\n", + "\n", + "model = RandomForestRegressor(n_estimators=100, max_depth=10, random_state=42)\n", + "model.fit(X_train, y_train)\n", + "y_pred = model.predict(X_test)\n", + "\n", + "from sklearn.metrics import mean_squared_error\n", + "mse = mean_squared_error(y_test, y_pred)\n", + "print(f\"MSE: {mse:.4f}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "plt.figure(figsize=(8, 6))\n", + "plt.scatter(y_test, y_pred, alpha=0.5)\n", + "plt.plot([y_test.min(), y_test.max()], [y_test.min(), y_test.max()], 'r--', lw=2)\n", + "plt.xlabel('Actual')\n", + "plt.ylabel('Predicted')\n", + "plt.title('Predictions vs Actual')\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/288/Q2.ipynb b/submissions_extracted/288/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..1df39b5a9bbc650e0f8204c8268daffef3b7983d --- /dev/null +++ b/submissions_extracted/288/Q2.ipynb @@ -0,0 +1,347 @@ +{ + "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 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", + "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", + "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", + "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:\")\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", + " 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.layer3(a2)\n", + " a3 = self.relu(z3)\n", + "\n", + "\n", + " z4 = self.layer5(a3)\n", + "\n", + "\n", + " return z5" + ], + "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.view(X_batch.size(0), -1).to(device)\n", + " y_batch = y_batch.to(device)\n", + "\n", + " outputs = model(X_batch)\n", + "\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", + " correct = 0\n", + " total = 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)\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", + " 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 = 3 * 32 * 32\n", + "\n", + "hidden_dim = 64\n", + "\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", + "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 5: Start training for 20 epochs:\n", + "num_epochs = 20\n", + "learning_rate = 0.001\n", + "\n", + "criterion = nn.CrossEntropyLoss()\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_loss = train_one_epoch(model, optimizer, criterion, train_loader, device)\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/288/Q3.ipynb b/submissions_extracted/288/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..5aca5c4feb7031a32a7abbb0254a5da27cd4e8f0 --- /dev/null +++ b/submissions_extracted/288/Q3.ipynb @@ -0,0 +1,213 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "import pandas as pd\n", + "import numpy as np\n", + "import os\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)" + ], + "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", + "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:Handle missing values appropriately\n", + "print(\"Missing values per column:\")\n", + "print(df.isnull().sum())\n", + "print(f\"\\nTotal missing: {df.isnull().sum().sum()}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:Check and remove duplicates if any exist\n", + "print(f\"Duplicates: {df.duplicated().sum()}\")\n", + "df.drop_duplicates(inplace=True)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:Encode categorical variables if needed\n", + "from sklearn.preprocessing import LabelEncoder\n", + "categorical_cols = df.select_dtypes(include=['object']).columns\n", + "for col in categorical_cols:\n", + " le = LabelEncoder()\n", + " df[col] = le.fit_transform(df[col].astype(str))" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:Apply feature scaling to numerical features (Use StandardScaler)\n", + "from sklearn.preprocessing import StandardScaler\n", + "scaler = StandardScaler()\n", + "dff = scaler.fit_transform(df)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:Check for target imbalance and state if it is imbalanced or not" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "X = df.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", + "from sklearn.model_selection import train_test_split\n", + "from sklearn.ensemble import RandomForestRegressor\n", + "\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", + ")\n", + "print(f\"Train: {X_train.shape}, Test: {X_test.shape}\")\n", + "\n", + "\n", + "\n", + "from sklearn.metrics import f1_score\n", + "\n", + "f1_macro = f1_score(y_test, y_pred, average='macro')\n", + "f1_weighted = f1_score(y_test, y_pred, average='weighted')\n", + "\n", + "print(f\"F1 (macro): {f1_macro:.4f}\")\n", + "print(f\"F1 (weighted): {f1_weighted:.4f}\")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "import matplotlib.pyplot as plt\n", + "import seaborn as sns\n", + "\n", + "plt.figure(figsize=(8, 6))\n", + "plt.scatter(y_test, y_pred, alpha=0.5)\n", + "plt.plot([y_test.min(), y_test.max()], [y_test.min(), y_test.max()], 'r--', lw=2)\n", + "plt.xlabel('Actual')\n", + "plt.ylabel('Predicted')\n", + "plt.title('Predictions vs Actual')\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/289/Q1.ipynb b/submissions_extracted/289/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..6d19ee3eb7d89319a77066487eceaaef21a796c7 --- /dev/null +++ b/submissions_extracted/289/Q1.ipynb @@ -0,0 +1,234 @@ +{ + "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", + "\n", + "delivery_path = os.path.join(path, 'Q1_data.csv')\n", + "df_delivery = pd.read_csv(delivery_path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "\n", + "print(f\"Dataset shape: {df_delivery.shape}\")\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", + "import matplotlib.pyplot as plt\n", + "\n", + "plt.figure(figsize=(10, 5))\n", + "plt.hist(df_delivery['Delivery_Time'].dropna(), bins=50, edgecolor='black')\n", + "plt.title('Delivary 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 = pd.DataFrame(df_delivery)\n", + "df_clean = df_delivery['Order_ID'].copy()\n", + "df_clean = df.drop(columns=['Order_ID'])" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "cols = ['Order_ID',\t'Distance_km',\t'Weather',\t'Traffic_Level',\t'Time_of_Day',\n", + " 'Vehicle_Type',\t'Preparation_Time_min',\t'Courier_Experience_yrs',\t'Delivery_Time']\n", + "df_clean = df_delivery[cols].copy()\n", + "df_clean = df.drop(columns=(cols))" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "from sklearn.preprocessing import LabelEncoder\n", + "for col in df_clean:\n", + " le = LabelEncoder()\n", + " df_clean[col] = le.fit_transform(df_clean[col].astype(str))\n", + "print(df_clean)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "from sklearn.preprocessing import StandardScaler\n", + "\n", + "data_for_scale = pd.DataFrame(df_clean)\n", + "\n", + "standard_scaler = StandardScaler()\n", + "data_standard_scaled = standard_scaler.fit_transform(data_for_scale)\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:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "feature_cols = pd.DataFrame(['Order_ID',\t'Distance_km',\t'Weather',\t'Traffic_Level', 'Time_of_Day',\n", + " 'Vehicle_Type',\t'Preparation_Time_min',\t'Courier_Experience_yrs'])\n", + "feature = df_clean[feature_cols]\n", + "target = df_clean['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 RandomForestClassifier\n", + "from sklearn.metrics import mean_squared_error as mean_absolute_error\n", + "\n", + "X, y = feature.copy(), target.copy()\n", + "kf = KFold(n_splits=5, shuffle=True)\n", + "\n", + "for fold, (train_indx, test_indx) in enumerate(kf.split(X), start=1):\n", + " X_train, X_test = X.iloc[train_indx], X.iloc[test_indx]\n", + " y_train, y_test = y.iloc[train_indx], y.iloc[test_indx]\n", + "\n", + "model= RandomForestClassifier()\n", + "model.fit(X_train, y_train)\n", + "y_pred = model.predict(X_test)\n", + "\n", + "mae= []\n", + "lr_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" + ], + "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/289/Q2.ipynb b/submissions_extracted/289/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..49035e54d2acf37ccce8b00c4c2f64a5edb851af --- /dev/null +++ b/submissions_extracted/289/Q2.ipynb @@ -0,0 +1,261 @@ +{ + "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, X_test, y_train, y_test = torch.tensor()" + ], + "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", + " 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()" + ], + "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()" + ], + "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" + ], + "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/289/Q3.ipynb b/submissions_extracted/289/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..6333ae32fe1bd040db22b17709cd55dd70f6f66c --- /dev/null +++ b/submissions_extracted/289/Q3.ipynb @@ -0,0 +1,199 @@ +{ + "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", + "\n", + "data3_path = os.path.join(path, 'Q3_data.csv')\n", + "df_data3 = pd.read_csv(data3_path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "print(f\"Dataset shape: {df_data3.shape}\")\n", + "df_data3.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "df_data3.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "df_data3.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "df = pd.DataFrame(df_data3)\n", + "df_clean = df_data3.copy()\n", + "for col in df_data3:\n", + " df_clean[col] = df_clean[col].fillna('unknown')" + ], + "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:\n", + "from sklearn.preprocessing import LabelEncoder\n", + "for col in df_data3:\n", + " le = LabelEncoder()\n", + " df_clean[col] = le.fit_transform(df_clean[col].astype(str))\n", + "print(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", + "data_for_scale = pd.DataFrame(df_data3)\n", + "\n", + "standard_scaler = StandardScaler()\n", + "data_standard_scaled = standard_scaler.fit_transform(data_for_scale)\n", + "\n", + "print('\\nData after scaling:\\n', data_standard_scaled)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "full_ratio = (df_data3.value_counts(normalize=True) * 100).sort_index()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "\n", + "X = df_clean[feature_cols]\n", + "y = df_clean['Target']" + ], + "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", + "print(\"Stratified K-Fold Cross Validation\\n\" + \"-\"*40)\n", + "\n", + "#skf.split(X, y)-> retern indces and y to balance the distribution\n", + "for fold, (train_idx, test_idx) in enumerate(skf.split(X, y), start=1):\n", + " # indexing for each fold based selection\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]" + ], + "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/29/Q1.ipynb b/submissions_extracted/29/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..c80e3aa931df484b81cedb7032c98ebfbfcbf963 --- /dev/null +++ b/submissions_extracted/29/Q1.ipynb @@ -0,0 +1,417 @@ +{ + "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", + "df = pd.read_csv('/root/.cache/kagglehub/datasets/ANON_OWNER/q1-exam-data/versions/1/Q1_data.csv')\n", + "print(\"Dataset loaded successfully!\")\n", + "print(f\"Dataset shape: {df.shape}\\n\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "print(\"=\"*80)\n", + "print(\"TASK 2: First few rows of the dataset\")\n", + "print(\"=\"*80)\n", + "print(df.head())\n", + "print()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "print(\"=\"*80)\n", + "print(\"TASK 3: Dataset Information\")\n", + "print(\"=\"*80)\n", + "df.info()\n", + "print()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "print(\"=\"*80)\n", + "print(\"TASK 4: Statistical Description\")\n", + "print(\"=\"*80)\n", + "print(df.describe())\n", + "print()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "print(\"=\"*80)\n", + "print(\"TASK 5: Target Distribution\")\n", + "print(\"=\"*80)\n", + "plt.figure(figsize=(12, 5))\n", + "\n", + "plt.subplot(1, 2, 1)\n", + "plt.hist(df['delivery_time'], bins=30, edgecolor='black', alpha=0.7, color='steelblue')\n", + "plt.xlabel('Delivery Time (minutes)', fontsize=12)\n", + "plt.ylabel('Frequency', fontsize=12)\n", + "plt.title('Distribution of Delivery Time', fontsize=14, fontweight='bold')\n", + "plt.grid(axis='y', alpha=0.3)\n", + "\n", + "plt.subplot(1, 2, 2)\n", + "plt.boxplot(df['delivery_time'], vert=True)\n", + "plt.ylabel('Delivery Time (minutes)', fontsize=12)\n", + "plt.title('Boxplot of Delivery Time', fontsize=14, fontweight='bold')\n", + "plt.grid(axis='y', alpha=0.3)\n", + "plt.tight_layout()\n", + "plt.show()\n", + "print(f\"\\nTarget Statistics:\")\n", + "print(f\"Mean: {df['delivery_time'].mean():.2f} minutes\")\n", + "print(f\"Median: {df['delivery_time'].median():.2f} minutes\")\n", + "print(f\"Std Dev: {df['delivery_time'].std():.2f} minutes\")\n", + "print()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "print(\"=\"*80)\n", + "print(\"PART 2: DATA CLEANING\")\n", + "print(\"=\"*80)\n", + "print(\"\\nTask 1: Dropping Order_ID column...\")\n", + "df_clean = df.drop('Order_ID', axis=1)\n", + "print(f\"Columns after dropping Order_ID: {df_clean.columns.tolist()}\\n\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "print(\"Task 2: Handling missing values...\")\n", + "print(\"\\nMissing values before handling:\")\n", + "print(df_clean.isnull().sum())\n", + "print()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "missing_pct = print(\"Task 3: Checking for duplicates...\")\n", + "duplicates = df_clean.duplicated().sum()\n", + "print(f\"Number of duplicate rows: {duplicates}\")\n", + "if duplicates > 0:\n", + " df_clean = df_clean.drop_duplicates()\n", + " print(f\"Removed {duplicates} duplicate rows\")\n", + "print(f\"Dataset shape after removing duplicates: {df_clean.shape}\\n\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "print(\"Task 4: Encoding categorical variables...\")\n", + "categorical_cols = df_clean.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 found: {categorical_cols}\")\n", + "\n", + "if categorical_cols:\n", + " # Using One Hot Encoding\n", + " df_encoded = pd.get_dummies(df_clean, columns=categorical_cols, drop_first=True)\n", + " print(f\"Applied One-Hot Encoding\")\n", + " print(f\"Shape after encoding: {df_encoded.shape}\")\n", + "else:\n", + " df_encoded = df_clean.copy()\n", + " print(\"No categorical columns to encode\")\n", + "print()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "print(\"Task 5: Applying feature scaling...\")\n", + "# Separate features and target\n", + "X = df_encoded.drop('delivery_time', axis=1)\n", + "y = df_encoded['delivery_time']\n", + "\n", + "# Apply StandardScaler\n", + "scaler = StandardScaler()\n", + "X_scaled = scaler.fit_transform(X)\n", + "X_scaled = pd.DataFrame(X_scaled, columns=X.columns)\n", + "\n", + "print(f\"Applied StandardScaler to all features\")\n", + "print(f\"Feature shape: {X_scaled.shape}\")\n", + "print(f\"Target shape: {y.shape}\\n\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 6: Write your code here:\n", + "print(\"Task 6: Checking target distribution...\")\n", + "print(\"Note: This is a regression task, so we check distribution rather than class imbalance\")\n", + "print(f\"Target variable (delivery_time) is continuous: {y.dtype}\")\n", + "print(f\"Range: [{y.min():.2f}, {y.max():.2f}]\")\n", + "print(\"The target is NOT imbalanced (this concept applies to classification tasks)\")\n", + "print()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "print(\"=\"*80)\n", + "print(\"PART 3: MODELING\")\n", + "print(\"=\"*80)\n", + "\n", + "# Task 1: Split dataset (already done above)\n", + "print(\"\\nTask 1: Features (X) and Target (y) split completed\")\n", + "print(f\"X shape: {X_scaled.shape}\")\n", + "print(f\"y shape: {y.shape}\\n\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:\n", + "print(\"Tasks 2-5: KFold Cross-Validation with RandomForest\")\n", + "print(\"-\"*80)\n", + "\n", + "# Use KFold (not StratifiedKFold, as this is regression)\n", + "kfold = KFold(n_splits=5, shuffle=True, random_state=42)\n", + "\n", + "mae_scores = []\n", + "fold_num = 1\n", + "\n", + "for train_idx, val_idx in kfold.split(X_scaled):\n", + " # Split data\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", + " # Train RandomForest model\n", + " rf_model = RandomForestRegressor(n_estimators=100, random_state=42, n_jobs=-1)\n", + " rf_model.fit(X_train, y_train)\n", + "\n", + " # Predict\n", + " y_pred = rf_model.predict(X_val)\n", + "\n", + " # Evaluate using MAE\n", + " mae = mean_absolute_error(y_val, y_pred)\n", + " mae_scores.append(mae)\n", + "\n", + " print(f\"Fold {fold_num}: MAE = {mae:.4f}\")\n", + " fold_num += 1\n", + "\n", + "# Print averaged score\n", + "print(\"-\"*80)\n", + "print(f\"\\nAveraged MAE across all folds: {np.mean(mae_scores):.4f} ± {np.std(mae_scores):.4f}\")\n", + "print()\n", + "\n", + "# Train final model on full data for feature importance and predictions\n", + "final_model = RandomForestRegressor(n_estimators=100, random_state=42, n_jobs=-1)\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", + "print(\"=\"*80)\n", + "print(\"PART 4: PLOTS\")\n", + "print(\"=\"*80)\n", + "\n", + "# Task 1: Plot feature importance\n", + "print(\"\\nTask 1: Plotting feature importance...\")\n", + "feature_importance = pd.DataFrame({\n", + " 'feature': X_scaled.columns,\n", + " 'importance': final_model.feature_importances_\n", + "}).sort_values('importance', ascending=False)\n", + "plt.figure(figsize=(12, 8))\n", + "plt.barh(range(len(feature_importance)), feature_importance['importance'], color='steelblue')\n", + "plt.yticks(range(len(feature_importance)), feature_importance['feature'])\n", + "plt.xlabel('Importance', fontsize=12)\n", + "plt.ylabel('Features', fontsize=12)\n", + "plt.title('Feature Importance from RandomForest Model', fontsize=14, fontweight='bold')\n", + "plt.gca().invert_yaxis()\n", + "plt.grid(axis='x', alpha=0.3)\n", + "plt.tight_layout()\n", + "plt.show()\n", + "\n", + "print(\"\\nTop 5 Most Important Features:\")\n", + "print(feature_importance.head())\n", + "print()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "print(\"Task 2: Plotting predicted delivery time histogram...\")\n", + "plt.figure(figsize=(14, 6))\n", + "\n", + "plt.subplot(1, 2, 1)\n", + "plt.hist(final_predictions, bins=30, edgecolor='black', alpha=0.7, color='coral', label='Predicted')\n", + "plt.hist(y, bins=30, edgecolor='black', alpha=0.5, color='steelblue', label='Actual')\n", + "plt.xlabel('Delivery Time (minutes)', fontsize=12)\n", + "plt.ylabel('Frequency', fontsize=12)\n", + "plt.title('Predicted vs Actual Delivery Time Distribution', fontsize=14, fontweight='bold')\n", + "plt.legend()\n", + "plt.grid(axis='y', alpha=0.3)\n", + "\n", + "plt.subplot(1, 2, 2)\n", + "plt.scatter(y, final_predictions, alpha=0.5, color='steelblue', s=20)\n", + "plt.plot([y.min(), y.max()], [y.min(), y.max()], 'r--', lw=2, label='Perfect Prediction')\n", + "plt.xlabel('Actual Delivery Time (minutes)', fontsize=12)\n", + "plt.ylabel('Predicted Delivery Time (minutes)', fontsize=12)\n", + "plt.title('Actual vs Predicted Delivery Time', fontsize=14, fontweight='bold')\n", + "plt.legend()\n", + "plt.grid(alpha=0.3)\n", + "\n", + "plt.tight_layout()\n", + "plt.show()\n", + "print()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:\n", + "print(\"=\"*80)\n", + "print(\"PART 5: BONUS - ENSEMBLE (RandomForest + CatBoost)\")\n", + "print(\"=\"*80)\n", + "\n", + "try:\n", + " from catboost import CatBoostRegressor\n", + "\n", + " print(\"\\nTraining ensemble model with KFold cross-validation...\")\n", + " print(\"-\"*80)\n", + "\n", + " ensemble_mae_scores = []\n", + " fold_num = 1\n", + "\n", + " for train_idx, val_idx in kfold.split(X_scaled):\n", + " # Split data\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", + " # Train RandomForest model\n", + " rf_model = RandomForestRegressor(n_estimators=100, random_state=42, n_jobs=-1)\n", + " rf_model.fit(X_train, y_train)\n", + " rf_pred = rf_model.predict(X_val)\n", + "\n", + " # Train CatBoost model\n", + " cb_model = CatBoostRegressor(iterations=100, random_state=42, verbose=0)\n", + " cb_model.fit(X_train, y_train)\n", + " cb_pred = cb_model.predict(X_val)\n", + "\n", + " # Average predictions\n", + " ensemble_pred = (rf_pred + cb_pred) / 2\n", + "\n", + " # Calculate MAE on averaged predictions\n", + " mae = mean_absolute_error(y_val, ensemble_pred)\n", + " ensemble_mae_scores.append(mae)\n", + "\n", + " print(f\"Fold {fold_num}: Ensemble MAE = {mae:.4f}\")\n", + " fold_num += 1\n", + "\n", + " print(\"-\"*80)\n", + " print(f\"\\nAveraged Ensemble MAE across all folds: {np.mean(ensemble_mae_scores):.4f} ± {np.std(ensemble_mae_scores):.4f}\")\n", + " print(f\"Single RandomForest MAE: {np.mean(mae_scores):.4f}\")\n", + " print(f\"Improvement: {np.mean(mae_scores) - np.mean(ensemble_mae_scores):.4f}\")\n", + "\n", + "except ImportError:\n", + " print(\"\\nCatBoost not installed. To use ensemble, install it with: pip install catboost\")\n", + " print(\"Using only RandomForest for now.\")\n", + "\n", + "print(\"\\n\" + \"=\"*80)\n", + "print(\"ANALYSIS COMPLETE!\")\n", + "print(\"=\"*80)" + ], + "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/29/Q2.ipynb b/submissions_extracted/29/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..8e31b9d78c832af8b9ca96b8bfba3f1c2aa0a40e --- /dev/null +++ b/submissions_extracted/29/Q2.ipynb @@ -0,0 +1,548 @@ +{ + "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", + "print(\"\\nTask 1: Converting numpy arrays to PyTorch tensors...\")\n", + "\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)\n", + "\n", + "print(f\"X_train_tensor shape: {X_train_tensor.shape}\")\n", + "print(f\"X_test_tensor shape: {X_test_tensor.shape}\")\n", + "print(f\"y_train_tensor shape: {y_train_tensor.shape}\")\n", + "print(f\"y_test_tensor shape: {y_test_tensor.shape}\")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 2. Create TensorDataset objects\n", + "print(\"\\nTask 2: Creating 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", + "print(f\"Train dataset size: {len(train_dataset)}\")\n", + "print(f\"Test dataset size: {len(test_dataset)}\")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 3. Create DataLoaders\n", + "print(\"\\nTask 3: Creating DataLoaders with batch_size=32...\")\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", + "print(f\"Number of training batches: {len(train_loader)}\")\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 4. Print shape of one batch\n", + "print(\"\\nTask 4: Inspecting one batch from train_loader...\")\n", + "\n", + "for batch_images, batch_labels in train_loader:\n", + " print(f\"Batch images shape: {batch_images.shape}\")\n", + " print(f\"Batch labels shape: {batch_labels.shape}\")\n", + " print(f\"Images dtype: {batch_images.dtype}\")\n", + " print(f\"Labels dtype: {batch_labels.dtype}\")\n", + " break\n", + "\n", + "\n", + " # Calculate loss\n", + " loss = criterion(predictions, batch_labels)\n", + "\n", + " # Backward pass\n", + " loss.backward()\n", + "\n", + " # Update weights\n", + " optimizer.step()\n", + "\n", + " # Accumulate loss\n", + " total_loss += loss.item()\n", + "\n", + " # Return average loss\n", + " avg_loss = total_loss / len(train_loader)\n", + " return avg_loss\n", + "\n", + "print(\"Training loop function created!\")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 5. Display sample images\n", + "print(\"\\nTask 5: Displaying sample images...\")\n", + "\n", + "# Get one batch for visualization\n", + "sample_images, sample_labels = next(iter(train_loader))\n", + "\n", + "# Display 8 sample images\n", + "fig, axes = plt.subplots(2, 4, figsize=(15, 8))\n", + "axes = axes.ravel()\n", + "\n", + "for i in range(8):\n", + " # Convert from (C, H, W) to (H, W, C) for display\n", + " img = sample_images[i].numpy().transpose(1, 2, 0)\n", + " age = sample_labels[i].item()\n", + "\n", + " axes[i].imshow(img)\n", + " axes[i].set_title(f'Age: {age:.0f}', fontsize=12, fontweight='bold')\n", + " axes[i].axis('off')\n", + "\n", + "plt.suptitle('Sample Training Images with Ages', fontsize=16, fontweight='bold')\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", + "print(\"\\nTask 1: Creating model class with 4 linear layers...\")\n", + "\n", + "class AgePredictionModel(nn.Module):\n", + " def __init__(self):\n", + " super(AgePredictionModel, self).__init__()\n", + "\n", + " # Calculate input size: 3 channels * 36 height * 36 width\n", + " input_size = 3 * 36 * 36\n", + "\n", + " # Define 4 linear layers with decreasing sizes\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) # Output: single age value\n", + "\n", + " # Activation function\n", + " self.relu = nn.ReLU()\n", + " self.dropout = nn.Dropout(0.3)\n", + "\n", + " def forward(self, x):\n", + " # Flatten the input\n", + " x = x.view(x.size(0), -1)\n", + "\n", + " # Pass through layers with ReLU activation\n", + " x = self.relu(self.fc1(x))\n", + " x = self.dropout(x)\n", + "\n", + " x = self.relu(self.fc2(x))\n", + " x = self.dropout(x)\n", + "\n", + " x = self.relu(self.fc3(x))\n", + " x = self.dropout(x)\n", + "\n", + " x = self.fc4(x)\n", + "\n", + " return x.squeeze()\n", + "\n", + "print(\"Model architecture created successfully!\")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your training loop here:\n", + "print(\"\\nTask 2: Creating training loop function...\")\n", + "\n", + "def train_one_epoch(model, train_loader, criterion, optimizer, device):\n", + " \"\"\"\n", + " Train the model for one epoch\n", + "\n", + " Args:\n", + " model: PyTorch model\n", + " train_loader: DataLoader for training data\n", + " criterion: Loss function\n", + " optimizer: Optimizer\n", + " device: Device to run on (CPU or GPU)\n", + "\n", + " Returns:\n", + " Average training loss for the epoch\n", + " \"\"\"\n", + " model.train()\n", + " total_loss = 0.0\n", + "\n", + " for batch_images, batch_labels in train_loader:\n", + " # Move data to device\n", + " batch_images = batch_images.to(device)\n", + " batch_labels = batch_labels.to(device)\n", + "\n", + " # Zero gradients\n", + " optimizer.zero_grad()\n", + "\n", + " # Forward pass\n", + " predictions = model(batch_images)\n", + "\n", + " # Calculate loss\n", + " loss = criterion(predictions, batch_labels)\n", + "\n", + " # Backward pass\n", + " loss.backward()\n", + "\n", + " # Update weights\n", + " optimizer.step()\n", + "\n", + " # Accumulate loss\n", + " total_loss += loss.item()\n", + "\n", + " # Return average loss\n", + " avg_loss = total_loss / len(train_loader)\n", + " return avg_loss\n", + "\n", + "print(\"Training loop function created!\")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your validation loop here:\n", + "print(\"\\nTask 3: Creating validation loop function...\")\n", + "\n", + "def validate(model, test_loader, criterion, device):\n", + " \"\"\"\n", + " Validate the model\n", + "\n", + " Args:\n", + " model: PyTorch model\n", + " test_loader: DataLoader for test data\n", + " criterion: Loss function\n", + " device: Device to run on (CPU or GPU)\n", + "\n", + " Returns:\n", + " Average validation loss\n", + " \"\"\"\n", + " model.eval()\n", + " total_loss = 0.0\n", + "\n", + " with torch.no_grad():\n", + " for batch_images, batch_labels in test_loader:\n", + " # Move data to device\n", + " batch_images = batch_images.to(device)\n", + " batch_labels = batch_labels.to(device)\n", + "\n", + " # Forward pass\n", + " predictions = model(batch_images)\n", + "\n", + " # Calculate loss\n", + " loss = criterion(predictions, batch_labels)\n", + "\n", + " # Accumulate loss\n", + " total_loss += loss.item()\n", + "\n", + " # Return average loss\n", + " avg_loss = total_loss / len(test_loader)\n", + " return avg_loss\n", + "\n", + "print(\"Validation loop function created!\")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Define device, model, loss, optimizer:\n", + "print(\"\\nTask 4: Defining device, model, loss function, and optimizer...\")\n", + "\n", + "# Set device\n", + "device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\n", + "print(f\"Using device: {device}\")\n", + "\n", + "# Initialize model\n", + "model = AgePredictionModel().to(device)\n", + "print(f\"\\nModel architecture:\")\n", + "print(model)\n", + "\n", + "# Count parameters\n", + "total_params = sum(p.numel() for p in model.parameters())\n", + "trainable_params = sum(p.numel() for p in model.parameters() if p.requires_grad)\n", + "print(f\"\\nTotal parameters: {total_params:,}\")\n", + "print(f\"Trainable parameters: {trainable_params:,}\")\n", + "\n", + "# Define loss function (MSE for regression)\n", + "criterion = nn.MSELoss()\n", + "print(f\"\\nLoss function: MSE (Mean Squared Error)\")\n", + "\n", + "# Define optimizer (Adam)\n", + "optimizer = optim.Adam(model.parameters(), lr=0.001)\n", + "print(f\"Optimizer: Adam with learning rate 0.001\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Start training for 20 epochs:\n", + "print(\"\\n\" + \"=\"*80)\n", + "print(\"Task 5: Training for 20 epochs...\")\n", + "print(\"=\"*80)\n", + "\n", + "num_epochs = 20\n", + "train_losses = []\n", + "val_losses = []\n", + "\n", + "for epoch in range(num_epochs):\n", + " # Train\n", + " train_loss = train_one_epoch(model, train_loader, criterion, optimizer, device)\n", + " train_losses.append(train_loss)\n", + "\n", + " # Validate\n", + " val_loss = validate(model, test_loader, criterion, device)\n", + " val_losses.append(val_loss)\n", + "\n", + " # Print progress\n", + " print(f\"Epoch [{epoch+1}/{num_epochs}] | \"\n", + " f\"Train Loss: {train_loss:.4f} | \"\n", + " f\"Val Loss: {val_loss:.4f}\")\n", + "\n", + "print(\"\\n\" + \"=\"*80)\n", + "print(\"Training completed!\")\n", + "print(\"=\"*80)\n", + "print(f\"Final Train Loss: {train_losses[-1]:.4f}\")\n", + "print(f\"Final Val Loss: {val_losses[-1]:.4f}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "print(\"\\nTask 1: Plotting training and validation loss...\")\n", + "\n", + "plt.figure(figsize=(12, 6))\n", + "\n", + "plt.subplot(1, 2, 1)\n", + "plt.plot(range(1, num_epochs+1), train_losses, 'b-o', label='Training Loss', linewidth=2)\n", + "plt.plot(range(1, num_epochs+1), val_losses, 'r-s', label='Validation Loss', linewidth=2)\n", + "plt.xlabel('Epoch', fontsize=12)\n", + "plt.ylabel('Loss (MSE)', fontsize=12)\n", + "plt.title('Training and Validation Loss Over Epochs', fontsize=14, fontweight='bold')\n", + "plt.legend(fontsize=11)\n", + "plt.grid(alpha=0.3)\n", + "\n", + "plt.subplot(1, 2, 2)\n", + "plt.plot(range(1, num_epochs+1), train_losses, 'b-o', label='Training Loss', linewidth=2)\n", + "plt.plot(range(1, num_epochs+1), val_losses, 'r-s', label='Validation Loss', linewidth=2)\n", + "plt.xlabel('Epoch', fontsize=12)\n", + "plt.ylabel('Loss (MSE)', fontsize=12)\n", + "plt.title('Training and Validation Loss (Log Scale)', fontsize=14, fontweight='bold')\n", + "plt.legend(fontsize=11)\n", + "plt.yscale('log')\n", + "plt.grid(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:\n", + "print(\"\\nTask 2 (Bonus): Plotting predictions with actual images...\")\n", + "\n", + "# Get predictions on test set\n", + "model.eval()\n", + "sample_images, sample_labels = next(iter(test_loader))\n", + "sample_images = sample_images.to(device)\n", + "\n", + "with torch.no_grad():\n", + " predictions = model(sample_images)\n", + "\n", + "# Move back to CPU for plotting\n", + "sample_images = sample_images.cpu()\n", + "sample_labels = sample_labels.cpu()\n", + "predictions = predictions.cpu()\n", + "\n", + "# Display 12 samples with predictions\n", + "fig, axes = plt.subplots(3, 4, figsize=(16, 12))\n", + "axes = axes.ravel()\n", + "\n", + "for i in range(12):\n", + " # Convert from (C, H, W) to (H, W, C) for display\n", + " img = sample_images[i].numpy().transpose(1, 2, 0)\n", + " actual_age = sample_labels[i].item()\n", + " predicted_age = predictions[i].item()\n", + " error = abs(actual_age - predicted_age)\n", + "\n", + " axes[i].imshow(img)\n", + " axes[i].set_title(f'Actual: {actual_age:.0f} | Predicted: {predicted_age:.1f}\\nError: {error:.1f}',\n", + " fontsize=11, fontweight='bold')\n", + " axes[i].axis('off')\n", + "\n", + " # Color-code border based on error\n", + " if error < 5:\n", + " color = 'green'\n", + " elif error < 10:\n", + " color = 'orange'\n", + " else:\n", + " color = 'red'\n", + "\n", + " for spine in axes[i].spines.values():\n", + " spine.set_edgecolor(color)\n", + " spine.set_linewidth(3)\n", + "\n", + "plt.suptitle('Predictions on Test Set (Green: Error < 5, Orange: Error < 10, Red: Error ≥ 10)',\n", + " fontsize=14, fontweight='bold')\n", + "plt.tight_layout()\n", + "plt.show()\n", + "\n", + "# Calculate and display overall metrics\n", + "print(\"\\n\" + \"=\"*80)\n", + "print(\"OVERALL PERFORMANCE METRICS\")\n", + "print(\"=\"*80)\n", + "\n", + "all_predictions = []\n", + "all_labels = []\n", + "\n", + "model.eval()\n", + "with torch.no_grad():\n", + " for batch_images, batch_labels in test_loader:\n", + " batch_images = batch_images.to(device)\n", + " predictions = model(batch_images)\n", + " all_predictions.extend(predictions.cpu().numpy())\n", + " all_labels.extend(batch_labels.numpy())\n", + "\n", + "all_predictions = np.array(all_predictions)\n", + "all_labels = np.array(all_labels)\n", + "\n", + "mae = np.mean(np.abs(all_predictions - all_labels))\n", + "rmse = np.sqrt(np.mean((all_predictions - all_labels)**2))\n", + "mse = np.mean((all_predictions - all_labels)**2)\n", + "\n", + "print(f\"Mean Absolute Error (MAE): {mae:.2f} years\")\n", + "print(f\"Root Mean Squared Error (RMSE): {rmse:.2f} years\")\n", + "print(f\"Mean Squared Error (MSE): {mse:.2f}\")\n", + "\n", + "# Plot prediction scatter\n", + "plt.figure(figsize=(10, 8))\n", + "plt.scatter(all_labels, all_predictions, alpha=0.5, s=30, color='steelblue')\n", + "plt.plot([all_labels.min(), all_labels.max()],\n", + " [all_labels.min(), all_labels.max()],\n", + " 'r--', lw=2, label='Perfect Prediction')\n", + "plt.xlabel('Actual Age', fontsize=12)\n", + "plt.ylabel('Predicted Age', fontsize=12)\n", + "plt.title('Actual vs Predicted Age (All Test Samples)', fontsize=14, fontweight='bold')\n", + "plt.legend(fontsize=11)\n", + "plt.grid(alpha=0.3)\n", + "plt.tight_layout()\n", + "plt.show()\n", + "\n", + "print(\"\\n\" + \"=\"*80)\n", + "print(\"ANALYSIS COMPLETE!\")\n", + "print(\"=\"*80)" + ], + "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/29/Q3.ipynb b/submissions_extracted/29/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..e8cb09bcc4d0683ee0224b9464d98735506ddac5 --- /dev/null +++ b/submissions_extracted/29/Q3.ipynb @@ -0,0 +1,565 @@ +{ + "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", + "print(\"\\nTask 1: Reading the dataset...\")\n", + "df = pd.read_csv('/root/.cache/kagglehub/datasets/ANON_OWNER/q3-exam-data/versions/1/Q3_data.csv')\n", + "print(\"Dataset loaded successfully!\")\n", + "print(f\"Dataset shape: {df.shape}\")\n", + "print(f\"Number of rows: {df.shape[0]:,}\")\n", + "print(f\"Number of columns: {df.shape[1]}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "print(\"\\n\" + \"=\"*80)\n", + "print(\"Task 2: First few rows of the dataset\")\n", + "print(\"=\"*80)\n", + "print(df.head(10))" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "print(\"\\n\" + \"=\"*80)\n", + "print(\"Task 3: Dataset Information\")\n", + "print(\"=\"*80)\n", + "df.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "print(\"\\n\" + \"=\"*80)\n", + "print(\"Task 4: Statistical Description\")\n", + "print(\"=\"*80)\n", + "print(df.describe())\n", + "# Additional exploration\n", + "print(\"\\n\" + \"=\"*80)\n", + "print(\"ADDITIONAL DATA EXPLORATION\")\n", + "print(\"=\"*80)\n", + "\n", + "# Check target distribution\n", + "if 'target' in df.columns:\n", + " target_col = 'target'\n", + "elif 'default' in df.columns:\n", + " target_col = 'default'\n", + "else:\n", + " # Find the target column (likely the last one or contains 'target'/'default')\n", + " target_col = df.columns[-1]\n", + "\n", + "print(f\"\\nTarget column identified: '{target_col}'\")\n", + "print(\"\\nTarget Distribution:\")\n", + "print(df[target_col].value_counts())\n", + "print(\"\\nTarget Proportions:\")\n", + "print(df[target_col].value_counts(normalize=True))\n", + "\n", + "# Visualize target distribution\n", + "fig, axes = plt.subplots(1, 2, figsize=(14, 5))\n", + "\n", + "# Count plot\n", + "df[target_col].value_counts().plot(kind='bar', ax=axes[0], color=['steelblue', 'coral'])\n", + "axes[0].set_xlabel('Class', fontsize=12)\n", + "axes[0].set_ylabel('Count', fontsize=12)\n", + "axes[0].set_title('Target Distribution (Count)', fontsize=14, fontweight='bold')\n", + "axes[0].set_xticklabels(['No Default (0)', 'Default (1)'], rotation=0)\n", + "axes[0].grid(axis='y', alpha=0.3)\n", + "\n", + "# Pie chart\n", + "df[target_col].value_counts().plot(kind='pie', ax=axes[1], autopct='%1.1f%%',\n", + " colors=['steelblue', 'coral'], startangle=90)\n", + "axes[1].set_ylabel('')\n", + "axes[1].set_title('Target Distribution (Percentage)', fontsize=14, fontweight='bold')\n", + "\n", + "plt.tight_layout()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "print(\"\\nTask 1: Handling missing values...\")\n", + "print(\"\\nMissing values before handling:\")\n", + "missing_before = df.isnull().sum()\n", + "print(missing_before[missing_before > 0])\n", + "\n", + "if df.isnull().sum().sum() > 0:\n", + " missing_pct = (df.isnull().sum() / len(df)) * 100\n", + " missing_info = pd.DataFrame({\n", + " 'Missing_Count': df.isnull().sum(),\n", + " 'Percentage': missing_pct\n", + " })\n", + " print(\"\\nMissing value details:\")\n", + " print(missing_info[missing_info['Missing_Count'] > 0].sort_values('Percentage', ascending=False))\n", + "\n", + " # Handle missing values\n", + " for col in df.columns:\n", + " if df[col].isnull().any() and col != target_col:\n", + " if df[col].dtype in ['float64', 'int64']:\n", + " # Fill numerical columns with median\n", + " df[col].fillna(df[col].median(), inplace=True)\n", + " print(f\"Filled '{col}' with median\")\n", + " else:\n", + " # Fill categorical columns with mode\n", + " df[col].fillna(df[col].mode()[0], inplace=True)\n", + " print(f\"Filled '{col}' with mode\")\n", + "else:\n", + " print(\"No missing values found!\")\n", + "\n", + "print(\"\\nMissing values after handling:\")\n", + "print(df.isnull().sum().sum())" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "print(\"\\n\" + \"=\"*80)\n", + "print(\"Task 2: Checking for duplicates...\")\n", + "duplicates = df.duplicated().sum()\n", + "print(f\"Number of duplicate rows: {duplicates}\")\n", + "\n", + "if duplicates > 0:\n", + " df = df.drop_duplicates()\n", + " print(f\"Removed {duplicates} duplicate rows\")\n", + " print(f\"Dataset shape after removing duplicates: {df.shape}\")\n", + "else:\n", + " print(\"No duplicates found!\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "print(\"\\n\" + \"=\"*80)\n", + "print(\"Task 3: Encoding categorical variables...\")\n", + "\n", + "# Identify categorical columns\n", + "categorical_cols = df.select_dtypes(include=['object']).columns.tolist()\n", + "if target_col in categorical_cols:\n", + " categorical_cols.remove(target_col)\n", + "\n", + "print(f\"Categorical columns found: {categorical_cols}\")\n", + "\n", + "if categorical_cols:\n", + " # Use Label Encoding for categorical columns\n", + " label_encoders = {}\n", + " for col in categorical_cols:\n", + " le = LabelEncoder()\n", + " df[col] = le.fit_transform(df[col].astype(str))\n", + " label_encoders[col] = le\n", + " print(f\"Encoded '{col}' using LabelEncoder\")\n", + " print(f\"Shape after encoding: {df.shape}\")\n", + "else:\n", + " print(\"No categorical columns to encode (all features are numerical - anonymized!)\")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "print(\"\\n\" + \"=\"*80)\n", + "print(\"Task 4: Applying feature scaling...\")\n", + "\n", + "# Separate features and target\n", + "X = df.drop(target_col, axis=1)\n", + "y = df[target_col]\n", + "\n", + "# Get feature names before scaling\n", + "feature_names = X.columns.tolist()\n", + "\n", + "# Apply StandardScaler\n", + "scaler = StandardScaler()\n", + "X_scaled = scaler.fit_transform(X)\n", + "X_scaled = pd.DataFrame(X_scaled, columns=feature_names)\n", + "\n", + "print(f\"Applied StandardScaler to {X_scaled.shape[1]} features\")\n", + "print(f\"Features shape: {X_scaled.shape}\")\n", + "print(f\"Target shape: {y.shape}\")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "print(\"\\n\" + \"=\"*80)\n", + "print(\"Task 5: Checking for target imbalance...\")\n", + "\n", + "target_counts = y.value_counts()\n", + "target_props = y.value_counts(normalize=True)\n", + "\n", + "print(f\"\\nTarget distribution:\")\n", + "print(target_counts)\n", + "print(f\"\\nTarget proportions:\")\n", + "print(target_props)\n", + "\n", + "# Calculate imbalance ratio\n", + "minority_class = target_counts.min()\n", + "majority_class = target_counts.max()\n", + "imbalance_ratio = majority_class / minority_class\n", + "\n", + "print(f\"\\nImbalance ratio: {imbalance_ratio:.2f}\")\n", + "\n", + "if imbalance_ratio > 1.5:\n", + " print(f\" IMBALANCED DATASET DETECTED!\")\n", + " print(f\" Majority class: {majority_class} samples ({target_props.max()*100:.1f}%)\")\n", + " print(f\" Minority class: {minority_class} samples ({target_props.min()*100:.1f}%)\")\n", + " print(f\" This is a classification problem with class imbalance.\")\n", + " print(f\" We should use F1-Score instead of Accuracy for evaluation!\")\n", + "else:\n", + " print(f\" Balanced dataset - both classes are well represented\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "print(\"\\nTask 1: Features (X) and Target (y) split completed\")\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 2,3,4,5: Write your code here:\n", + "print(\"\\n\" + \"=\"*80)\n", + "print(\"Tasks 2-5: StratifiedKFold Cross-Validation with CatBoostClassifier\")\n", + "print(\"=\"*80)\n", + "# Use StratifiedKFold for imbalanced classification\n", + "skfold = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)\n", + "\n", + "accuracy_scores = []\n", + "f1_scores = []\n", + "fold_num = 1\n", + "\n", + "# Store feature importance from each fold\n", + "feature_importance_list = []\n", + "\n", + "print(\"\\nTraining CatBoostClassifier with 5-fold cross-validation...\\n\")\n", + "\n", + "for train_idx, val_idx in skfold.split(X_scaled, y):\n", + " # Split data\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", + " # Train CatBoost model\n", + " catboost_model = CatBoostClassifier(\n", + " iterations=100,\n", + " learning_rate=0.1,\n", + " depth=6,\n", + " random_state=42,\n", + " verbose=0\n", + " )\n", + " catboost_model.fit(X_train, y_train)\n", + "\n", + " # Predict\n", + " y_pred = catboost_model.predict(X_val)\n", + "\n", + " # Evaluate using both Accuracy and F1 Score\n", + " acc = accuracy_score(y_val, y_pred)\n", + " f1 = f1_score(y_val, y_pred)\n", + "\n", + " accuracy_scores.append(acc)\n", + " f1_scores.append(f1)\n", + "\n", + " # Store feature importance\n", + " feature_importance_list.append(catboost_model.feature_importances_)\n", + "\n", + " print(f\"Fold {fold_num}: Accuracy = {acc:.4f} | F1-Score = {f1:.4f}\")\n", + " fold_num += 1\n", + "\n", + "print(\"-\"*80)\n", + "\n", + "# Determine which metric to use based on imbalance\n", + "if imbalance_ratio > 1.5:\n", + " primary_metric = \"F1-Score\"\n", + " primary_scores = f1_scores\n", + " print(f\"\\n PRIMARY METRIC: F1-Score (dataset is imbalanced)\")\n", + "else:\n", + " primary_metric = \"Accuracy\"\n", + " primary_scores = accuracy_scores\n", + " print(f\"\\n PRIMARY METRIC: Accuracy (dataset is balanced)\")\n", + "\n", + "print(f\"\\nAveraged {primary_metric} across all folds: {np.mean(primary_scores):.4f} ± {np.std(primary_scores):.4f}\")\n", + "print(f\"Averaged Accuracy across all folds: {np.mean(accuracy_scores):.4f} ± {np.std(accuracy_scores):.4f}\")\n", + "print(f\"Averaged F1-Score across all folds: {np.mean(f1_scores):.4f} ± {np.std(f1_scores):.4f}\")\n", + "\n", + "# Train final model on full data for feature importance\n", + "print(\"\\nTraining final model on full dataset for feature analysis...\")\n", + "final_model = CatBoostClassifier(\n", + " iterations=100,\n", + " learning_rate=0.1,\n", + " depth=6,\n", + " random_state=42,\n", + " verbose=0\n", + ")\n", + "final_model.fit(X_scaled, y)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "print(\"\\nTask 1: Plotting feature importance...\")\n", + "\n", + "# Get average feature importance across all folds\n", + "\n", + "avg_feature_importance = np.mean(feature_importance_list, axis=0)\n", + "\n", + "feature_importance_df = pd.DataFrame({\n", + " 'feature': feature_names,\n", + " 'importance': avg_feature_importance\n", + "}).sort_values('importance', ascending=False)\n", + "\n", + "# Plot feature importance\n", + "plt.figure(figsize=(14, max(8, len(feature_names) * 0.3)))\n", + "colors = plt.cm.viridis(np.linspace(0, 1, len(feature_importance_df)))\n", + "colors[0] = [1, 0.84, 0, 1] # Gold color for the top feature\n", + "\n", + "bars = plt.barh(range(len(feature_importance_df)),\n", + " feature_importance_df['importance'],\n", + " color=colors)\n", + "plt.yticks(range(len(feature_importance_df)), feature_importance_df['feature'])\n", + "plt.xlabel('Importance Score', fontsize=12, fontweight='bold')\n", + "plt.ylabel('Features', fontsize=12, fontweight='bold')\n", + "plt.title('Feature Importance from CatBoost Model\\n(Golden Feature Highlighted in Gold)',\n", + " fontsize=14, fontweight='bold')\n", + "plt.gca().invert_yaxis()\n", + "plt.grid(axis='x', alpha=0.3)\n", + "plt.tight_layout()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "print(\"\\n\" + \"=\"*80)\n", + "print(\"Task 2: Identifying the Golden Feature...\")\n", + "print(\"=\"*80)\n", + "\n", + "golden_feature = feature_importance_df.iloc[0]['feature']\n", + "golden_importance = feature_importance_df.iloc[0]['importance']\n", + "\n", + "print(f\"\\n THE GOLDEN FEATURE IS: '{golden_feature}'\")\n", + "print(f\" Importance Score: {golden_importance:.4f}\")\n", + "print(f\"\\n This feature is the most powerful predictor of credit default!\")\n", + "\n", + "print(\"\\nTop 10 Most Important Features:\")\n", + "print(feature_importance_df.head(10).to_string(index=False))" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:\n", + "X_golden = X_scaled[[golden_feature]]\n", + "print(f\"Golden feature shape: {X_golden.shape}\")\n", + "\n", + "# Task 2 & 3: Run KFold with single feature\n", + "accuracy_scores_golden = []\n", + "f1_scores_golden = []\n", + "fold_num = 1\n", + "\n", + "print(\"\\nTraining with golden feature only...\\n\")\n", + "\n", + "for train_idx, val_idx in skfold.split(X_golden, y):\n", + " # Split data\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", + " # Train CatBoost model with single feature\n", + " catboost_golden = CatBoostClassifier(\n", + " iterations=100,\n", + " learning_rate=0.1,\n", + " depth=6,\n", + " random_state=42,\n", + " verbose=0\n", + " )\n", + " catboost_golden.fit(X_train_golden, y_train)\n", + "\n", + " # Predict\n", + " y_pred_golden = catboost_golden.predict(X_val_golden)\n", + "\n", + " # Evaluate\n", + " acc_golden = accuracy_score(y_val, y_pred_golden)\n", + " f1_golden = f1_score(y_val, y_pred_golden)\n", + "\n", + " accuracy_scores_golden.append(acc_golden)\n", + " f1_scores_golden.append(f1_golden)\n", + "\n", + " print(f\"Fold {fold_num}: Accuracy = {acc_golden:.4f} | F1-Score = {f1_golden:.4f}\")\n", + " fold_num += 1\n", + "\n", + "print(\"-\"*80)\n", + "\n", + "# Comparison\n", + "print(\"\\n\" + \"=\"*80)\n", + "print(\"PERFORMANCE COMPARISON: FULL MODEL VS GOLDEN FEATURE ONLY\")\n", + "print(\"=\"*80)\n", + "\n", + "avg_acc_full = np.mean(accuracy_scores)\n", + "avg_acc_golden = np.mean(accuracy_scores_golden)\n", + "avg_f1_full = np.mean(f1_scores)\n", + "avg_f1_golden = np.mean(f1_scores_golden)\n", + "\n", + "print(f\"\\n FULL MODEL (All {len(feature_names)} features):\")\n", + "print(f\" Accuracy: {avg_acc_full:.4f}\")\n", + "print(f\" F1-Score: {avg_f1_full:.4f}\")\n", + "\n", + "print(f\"\\n🏆 GOLDEN FEATURE ONLY ('{golden_feature}'):\")\n", + "print(f\" Accuracy: {avg_acc_golden:.4f}\")\n", + "print(f\" F1-Score: {avg_f1_golden:.4f}\")\n", + "\n", + "print(f\"\\n PERFORMANCE DIFFERENCE:\")\n", + "print(f\" Accuracy Drop: {(avg_acc_full - avg_acc_golden):.4f} ({((avg_acc_full - avg_acc_golden)/avg_acc_full)*100:.2f}%)\")\n", + "print(f\" F1-Score Drop: {(avg_f1_full - avg_f1_golden):.4f} ({((avg_f1_full - avg_f1_golden)/avg_f1_full)*100:.2f}%)\")\n", + "\n", + "# Performance retention\n", + "acc_retention = (avg_acc_golden / avg_acc_full) * 100\n", + "f1_retention = (avg_f1_golden / avg_f1_full) * 100\n", + "\n", + "print(f\"\\n INSIGHT:\")\n", + "print(f\" The golden feature alone retains {acc_retention:.1f}% of the full model's accuracy\")\n", + "print(f\" The golden feature alone retains {f1_retention:.1f}% of the full model's F1-score\")\n", + "\n", + "if acc_retention > 85:\n", + " print(f\"\\n Amazing! The golden feature '{golden_feature}' is incredibly powerful!\")\n", + " print(f\" Using just this one feature achieves {acc_retention:.1f}% of full model performance!\")\n", + "elif acc_retention > 70:\n", + " print(f\"\\n ✓ The golden feature '{golden_feature}' is quite strong!\")\n", + " print(f\" It captures most of the predictive power on its own.\")\n", + "else:\n", + " print(f\"\\n The golden feature '{golden_feature}' is important but works best with other features.\")\n", + "\n", + "# Visualization of comparison\n", + "fig, axes = plt.subplots(1, 2, figsize=(14, 6))\n", + "\n", + "# Bar chart comparison\n", + "metrics = ['Accuracy', 'F1-Score']\n", + "full_model_scores = [avg_acc_full, avg_f1_full]\n", + "golden_scores = [avg_acc_golden, avg_f1_golden]\n", + "\n", + "x = np.arange(len(metrics))\n", + "width = 0.35\n", + "\n", + "axes[0].bar(x - width/2, full_model_scores, width, label='Full Model', color='steelblue')\n", + "axes[0].bar(x + width/2, golden_scores, width, label='Golden Feature Only', color='gold')\n", + "axes[0].set_ylabel('Score', fontsize=12)\n", + "axes[0].set_title('Model Performance Comparison', fontsize=14, fontweight='bold')\n", + "axes[0].set_xticks(x)\n", + "axes[0].set_xticklabels(metrics)\n", + "axes[0].legend()\n", + "axes[0].grid(axis='y', alpha=0.3)\n", + "\n", + "# Add value labels on bars\n", + "for i, v in enumerate(full_model_scores):\n", + " axes[0].text(i - width/2, v + 0.01, f'{v:.3f}', ha='center', va='bottom', fontweight='bold')\n", + "for i, v in enumerate(golden_scores):\n", + " axes[0].text(i + width/2, v + 0.01, f'{v:.3f}', ha='center', va='bottom', fontweight='bold')\n", + "\n", + "# Feature count vs performance\n", + "axes[1].plot([len(feature_names), 1], [avg_acc_full, avg_acc_golden],\n", + " 'o-', linewidth=2, markersize=10, label='Accuracy', color='steelblue')\n", + "axes[1].plot([len(feature_names), 1], [avg_f1_full, avg_f1_golden],\n", + " 's-', linewidth=2, markersize=10, label='F1-Score', color='coral')\n", + "axes[1].set_xlabel('Number of Features', fontsize=12)\n", + "axes[1].set_ylabel('Score', fontsize=12)\n", + "axes[1].set_title('Performance vs Feature Count', fontsize=14, fontweight='bold')\n", + "axes[1].set_xticks([1, len(feature_names)])\n", + "axes[1].set_xticklabels(['1\\n(Golden Only)', f'{len(feature_names)}\\n(All Features)'])\n", + "axes[1].legend()\n", + "axes[1].grid(alpha=0.3)\n", + "\n", + "plt.tight_layout()\n", + "plt.show()\n", + "\n", + "print(\"\\n\" + \"=\"*80)\n", + "print(\"MISSION COMPLETE! \")\n", + "print(\"=\"*80)\n", + "print(f\"The golden feature '{golden_feature}' has been successfully identified!\")\n", + "print(\"=\"*80)" + ], + "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/290/Q1.ipynb b/submissions_extracted/290/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..08f9e32b3ba30201725982719cfa81a93fc17c20 --- /dev/null +++ b/submissions_extracted/290/Q1.ipynb @@ -0,0 +1,341 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "\n", + "from IPython.display import clear_output\n", + "\n", + "%pip install catboost -q # Cat Boost must installed before import\n", + "\n", + "clear_output()" + ], + "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.impute import SimpleImputer\n", + "from sklearn.preprocessing import StandardScaler\n", + "from sklearn.model_selection import KFold\n", + "from sklearn.ensemble import RandomForestRegressor\n", + "from sklearn.metrics import mean_absolute_error\n", + "from catboost import CatBoostRegressor" + ], + "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", + "data_path = path + '/Q1_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(5)" + ], + "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", + "sns.histplot(df['Delivery_Time'], kde=True, bins=30)\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: Drop the 'Order_ID' column from the data:\n", + "df = df.drop(columns=['Order_ID'])" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Handle missing values appropriately:\n", + "missing_values = df.isnull().sum()\n", + "missing_values # The TARGET HAS NA so I will fill every column expect target i will remove the null rows in it" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "df = df.dropna(subset=['Delivery_Time'])\n", + "missing_values = df.isnull().sum()\n", + "missing_values # I removed them now I can fill the others" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "num_cols = df.select_dtypes(include=['int64', 'float64']).columns\n", + "cat_cols = df.select_dtypes(include=['object', 'category']).columns\n", + "\n", + "df[num_cols] = SimpleImputer(strategy='median').fit_transform(df[num_cols]) # Replace numbers by Median\n", + "df[cat_cols] = SimpleImputer(strategy='most_frequent').fit_transform(df[cat_cols]) # Replace strings by Most Frequent\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Check and remove duplicates if any exist:\n", + "df = df.drop_duplicates()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4:Encode categorical variables if needed:\n", + "df = pd.get_dummies(df, columns=cat_cols, drop_first=True)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Apply feature scaling for all features (Use StandardScaler):\n", + "X = df.drop(columns=['Delivery_Time'])\n", + "y = df['Delivery_Time']\n", + "\n", + "scaler = StandardScaler()\n", + "X = pd.DataFrame(scaler.fit_transform(X), columns=X.columns)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 6: Check for target imbalance and state if it is imbalanced or not:\n", + "# No need Because the task is continous (not classes to see balance or not)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Split the dataset into features (X) and target (y):\n", + "# I did it before Scaling\n", + "X.head(2)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "y.head(2)" + ], + "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", + "mae_scores = [] # Empty list so I can append the losses then take the average\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", + " # The model with the hyperparamters\n", + " random_forest = RandomForestRegressor(\n", + " n_estimators=200,\n", + " random_state=42,\n", + " n_jobs=-1\n", + " )\n", + " random_forest.fit(X_train, y_train)\n", + "\n", + " y_pred = random_forest.predict(X_val)\n", + " mae = mean_absolute_error(y_val, y_pred) # Calculate the MAE\n", + " mae_scores.append(mae) # append the mae to the list\n", + "\n", + "print(f\"Average MAE: {np.mean(mae_scores):.2f}\") # Take the average\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Plot feature importance from your trained model:\n", + "import pandas as pd\n", + "import matplotlib.pyplot as plt\n", + "\n", + "feature_importance = pd.DataFrame({\n", + " \"feature\": X.columns,\n", + " \"importance\": random_forest.feature_importances_\n", + "}).sort_values(by=\"importance\", ascending=True)\n", + "\n", + "plt.figure(figsize=(8, 6))\n", + "plt.barh(feature_importance[\"feature\"], feature_importance[\"importance\"])\n", + "plt.xlabel(\"Feature Importance\")\n", + "plt.title(\"Random Forest Feature Importance\")\n", + "plt.tight_layout()\n", + "plt.show()\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Plot predicted delivery time histogram:\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": [ + "# Task Bonus: Write your code here:\n", + "# Same\n", + "ensemble_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", + " # I have the Random Forest Model above named \"random_forest\" so I dont have to do it again\n", + "\n", + "\n", + " # CatBoost\n", + " cat_boost = CatBoostRegressor(\n", + " iterations=300,\n", + " learning_rate=0.1,\n", + " depth=6,\n", + " random_seed=42,\n", + " verbose=0\n", + " )\n", + "\n", + " random_forest.fit(X_train, y_train)\n", + " cat_boost.fit(X_train, y_train)\n", + "\n", + " random_forest_preds = random_forest.predict(X_val)\n", + " cat_boost_preds = cat_boost.predict(X_val)\n", + "\n", + " # Average preds\n", + " ensemble_preds = (random_forest_preds + cat_boost_preds) / 2\n", + "\n", + " mae = mean_absolute_error(y_val, ensemble_preds)\n", + " ensemble_mae_scores.append(mae)\n", + "\n", + "print(f\"Average Ensemble MAE: {np.mean(ensemble_mae_scores):.2f}\")\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/290/Q2.ipynb b/submissions_extracted/290/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..6a5471c146f0a7006185f3d94aba20dbfb63cb65 --- /dev/null +++ b/submissions_extracted/290/Q2.ipynb @@ -0,0 +1,344 @@ +{ + "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", + "from torch.utils.data import TensorDataset, DataLoader\n", + "import matplotlib.pyplot as plt\n", + "import torch.nn as nn\n", + "import torch.nn.functional as F" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 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_tensor = torch.tensor(X_train, dtype=torch.float32)\n", + "X_test_tensor = torch.tensor(X_test, dtype=torch.float32)\n", + "\n", + "y_train_tensor = torch.tensor(y_train, dtype=torch.float32).unsqueeze(1)\n", + "y_test_tensor = torch.tensor(y_test, dtype=torch.float32).unsqueeze(1)\n", + "\n", + "print(X_train_tensor.shape, y_train_tensor.shape)\n", + "print(X_test_tensor.shape, y_test_tensor.shape)" + ], + "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", + "print(\"Train dataset size:\", len(train_dataset))\n", + "print(\"Test dataset size:\", len(test_dataset))" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 3. Create DataLoaders\n", + "batch_size = 32\n", + "\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", + "print(\"Number of train batches:\", len(train_loader))\n", + "print(\"Number of test batches:\", len(test_loader))" + ], + "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 shape:\", xb.shape)\n", + "print(\"y batch shape:\", yb.shape)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 5. Display sample images\n", + "plt.figure(figsize=(10, 4))\n", + "for i in range(8):\n", + " img = xb[i].permute(1, 2, 0).numpy()\n", + " age = yb[i].item()\n", + "\n", + " plt.subplot(2, 4, i+1)\n", + " plt.imshow(img)\n", + " plt.title(f\"Age: {age:.0f}\")\n", + " plt.axis(\"off\")\n", + "\n", + "plt.tight_layout()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Create a model class with 4 linear layers:\n", + "class NAIFnn(nn.Module):\n", + " def __init__(self):\n", + " super().__init__()\n", + " # Flatten: 3*36*36 = 3888\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) # regression output\n", + "\n", + " self.dropout = nn.Dropout(0.2)\n", + "\n", + " def forward(self, x):\n", + " x = x.view(x.size(0), -1) # flatten\n", + " x = F.relu(self.fc1(x))\n", + " x = self.dropout(x)\n", + " x = F.relu(self.fc2(x))\n", + " x = self.dropout(x)\n", + " x = F.relu(self.fc3(x))\n", + " x = self.fc4(x)\n", + " return x\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Create a training loop function:\n", + "def train_one_epoch(model, loader, optimizer, criterion, device):\n", + " model.train()\n", + " running_loss = 0.0\n", + "\n", + " for xb, yb in loader:\n", + " xb = xb.to(device)\n", + " yb = yb.to(device)\n", + "\n", + " optimizer.zero_grad()\n", + " preds = model(xb)\n", + " loss = criterion(preds, yb)\n", + " loss.backward()\n", + " optimizer.step()\n", + "\n", + " running_loss += loss.item() * xb.size(0)\n", + "\n", + " epoch_loss = running_loss / len(loader.dataset)\n", + " return epoch_loss\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Create a validation loop function:\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 = xb.to(device)\n", + " yb = yb.to(device)\n", + "\n", + " preds = model(xb)\n", + " loss = criterion(preds, yb)\n", + " running_loss += loss.item() * xb.size(0)\n", + "\n", + " epoch_loss = running_loss / len(loader.dataset)\n", + " return epoch_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", + "print(\"Using device:\", device)\n", + "\n", + "model = NAIFnn().to(device)\n", + "\n", + "criterion = nn.MSELoss()\n", + "optimizer = torch.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 = 20\n", + "train_losses = []\n", + "val_losses = []\n", + "\n", + "for epoch in range(num_epochs):\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+1}/{num_epochs}] | Train Loss: {train_loss:.4f} | Val Loss: {val_loss:.4f}\")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Plot the training and validation loss over epochs:\n", + "plt.figure(figsize=(7,5))\n", + "plt.plot(train_losses, label=\"Train Loss\")\n", + "plt.plot(val_losses, label=\"Validation Loss\")\n", + "plt.xlabel(\"Epoch\")\n", + "plt.ylabel(\"MSE Loss\")\n", + "plt.title(\"Training vs Validation Loss\")\n", + "plt.legend()\n", + "plt.grid(True)\n", + "plt.show()\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "@torch.no_grad()\n", + "def get_predictions(model, loader, device):\n", + " model.eval()\n", + " xb, yb = next(iter(loader))\n", + " xb = xb.to(device)\n", + "\n", + " preds = model(xb).cpu().squeeze().numpy()\n", + " true = yb.squeeze().numpy()\n", + " imgs = xb.cpu()\n", + "\n", + " return imgs, preds, true\n", + "\n", + "\n", + "imgs, preds, true = get_predictions(model, test_loader, device)\n", + "\n", + "random_indices = np.random.choice(len(imgs), size=3, replace=False)\n", + "\n", + "plt.figure(figsize=(12, 6))\n", + "for i, idx in enumerate(random_indices):\n", + " plt.subplot(2, 4, i + 1)\n", + " plt.imshow(imgs[idx].permute(1, 2, 0))\n", + " plt.title(f\"P: {preds[idx]:.1f} | T: {true[idx]:.0f}\")\n", + " plt.axis(\"off\")\n", + "\n", + "plt.tight_layout()\n", + "plt.show()\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/290/Q3.ipynb b/submissions_extracted/290/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..4cb402df40441a232629f0525eceeef7649e2473 --- /dev/null +++ b/submissions_extracted/290/Q3.ipynb @@ -0,0 +1,261 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "\n", + "from IPython.display import clear_output\n", + "\n", + "%pip install catboost -q # Cat Boost must installed before import\n", + "\n", + "clear_output()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "import pandas as pd\n", + "import numpy as np\n", + "\n", + "\n", + "import matplotlib.pyplot as plt\n", + "import seaborn as sns\n", + "from sklearn.impute import SimpleImputer\n", + "from sklearn.preprocessing import StandardScaler\n", + "from sklearn.model_selection import StratifiedKFold\n", + "from sklearn.metrics import f1_score\n", + "from catboost import CatBoostClassifier\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "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": [ + "# Task 1: Write your code here:\n", + "data_path = 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(5)" + ], + "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: Handle missing values appropriately:\n", + "missing_values = df.isnull().sum()\n", + "missing_values" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Replace numbers by Median ** I saw by \"Describe\" the data hasnt \"object\" type **\n", + "num_cols = df.select_dtypes(include=['int64', 'float64']).columns\n", + "df[num_cols] = SimpleImputer(strategy='median').fit_transform(df[num_cols])\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Check and remove duplicates if any exist:\n", + "df = df.drop_duplicates()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Encode categorical variables if needed:\n", + "# There Is NO categorical variables" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Apply feature scaling to numerical features (Use StandardScaler):\n", + "X = df.drop(columns=['Target'])\n", + "y = df['Target']\n", + "\n", + "scaler = StandardScaler()\n", + "X = pd.DataFrame(scaler.fit_transform(X), columns=X.columns)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Check for target imbalance and state if it is imbalanced or not:\n", + "y.value_counts(normalize=True) # imbalanced\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Split the dataset into features (X) and target (y):\n", + "# I did it before Scaling" + ], + "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", + "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 = CatBoostClassifier(\n", + " iterations=200,\n", + " depth=6,\n", + " learning_rate=0.1,\n", + " loss_function='Logloss',\n", + " verbose=0,\n", + " random_state=42\n", + " )\n", + "\n", + " model.fit(X_train, y_train)\n", + " y_pred = model.predict(X_val)\n", + "\n", + " f1_scores.append(f1_score(y_val, y_pred))\n", + "\n", + "print(f\"Average F1 Score: {np.mean(f1_scores):.2f}\")\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Plot feature importance from your trained model:\n", + "feature_importance = pd.DataFrame({\n", + " 'Feature': X.columns,\n", + " 'Importance': model.get_feature_importance()\n", + "}).sort_values(by='Importance', ascending=False)\n", + "\n", + "plt.figure(figsize=(10,6))\n", + "plt.barh(\n", + " feature_importance['Feature'][:15][::-1],\n", + " feature_importance['Importance'][:15][::-1]\n", + ")\n", + "plt.xlabel(\"Importance Score\")\n", + "plt.title(\"Top 15 Feature Importances\")\n", + "plt.show()\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Identify and print the name of the most important feature (the 'golden feature'):\n", + "golden_feature = feature_importance.iloc[0]['Feature']\n", + "print(\"Golden Feature:\", golden_feature)" + ], + "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/291/Q1.ipynb b/submissions_extracted/291/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..09a2c9fcc3ba8307fcc00ac6397aa63c3ae2f83f --- /dev/null +++ b/submissions_extracted/291/Q1.ipynb @@ -0,0 +1,321 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "%pip install kagglehub catboost lightgbm tqdm -q\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(100)" + ], + "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)\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", + "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", + "#Delete the missing values because the have less percentage.\n", + "\n", + "print(f\"Before: {df.shape}\")\n", + "df = df.dropna()\n", + "print(f\"After dropping missing: {df.shape}\")" + ], + "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.shape" + ], + "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", + "\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\")\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_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", + "\n", + "#Target is right skewed." + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "from sklearn.model_selection import train_test_split, KFold\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", + "from sklearn.model_selection import StratifiedKFold\n", + "from sklearn.ensemble import RandomForestRegressor\n", + "from sklearn.metrics import mean_squared_error, mean_absolute_error\n", + "models = {\n", + " \"Random Forest Regressor\": RandomForestRegressor(n_estimators=200),\n", + "}\n", + "mae_scores = []\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", + " 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_scores.append(mean_absolute_error(y_test, y_pred))\n", + "\n", + "print(f\"MAE : {np.mean(mae_scores):.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=(10, 5))\n", + "plt.hist(y_pred, bins=50, edgecolor='black')\n", + "plt.title('Pridected Time')\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:" + ], + "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/291/Q2.ipynb b/submissions_extracted/291/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..15e315ed9082f5bca7d1dfe9232fb7b1ed485daf --- /dev/null +++ b/submissions_extracted/291/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 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.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", + "\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", + "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", + "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", + "\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].view(), 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", + " # 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", + " 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) # 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\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 setup\n", + "device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\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", + "# 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) - 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", + "# 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/292/Q1.ipynb b/submissions_extracted/292/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..390707da64fdd0fb2fa4cedf91306ad8055efa64 --- /dev/null +++ b/submissions_extracted/292/Q1.ipynb @@ -0,0 +1,463 @@ +{ + "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\n", + "from sklearn.ensemble import RandomForestClassifier\n", + "from sklearn.metrics import classification_report, confusion_matrix, accuracy_score\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "path_data = os.path.join(path, 'Q1_data.csv')\n", + "df = pd.read_csv(path_data)\n", + "\n", + "print(f\"Shape: {df.shape}\")\n", + "df.head()" + ], + "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:\n", + "plt.hist(df['Delivery_Time'].dropna(), bins=30, edgecolor='black', color='orange')\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 5: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "df.drop(\"Order_ID\",axis=1,inplace=True)\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "df['Delivery_Time'].mean()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "df.isnull().sum()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "df.isnull().sum()\n", + "df['Delivery_Time'] = df['Delivery_Time'].fillna(df['Delivery_Time'].mean())\n", + "df = df.dropna(subset=['Weather', 'Time_of_Day', 'Courier_Experience_yrs',\"Traffic_Level\"])" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "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 OneHotEncoder\n", + "categorical_cols = df.select_dtypes(include=[\"object\"]).columns\n", + "onehot_encoder = OneHotEncoder(sparse_output=False) # Instantiate OneHotEncoder\n", + "data_onehot_encoded = onehot_encoder.fit_transform(categorical_cols) # Apply fit_transform to the copied" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "for col in df.columns:\n", + " if df[col].dtype==object:\n", + " df[col]=onehot_encoder.fit_transform(df[col])\n", + "df" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "label_encoder = LabelEncoder()\n", + "\n", + "for col in df.select_dtypes(include=[\"object\"]).columns:\n", + " df[col] = label_encoder.fit_transform(df[col])" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "df" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "X=df.drop(\"Delivery_Time\",axis=1)\n", + "y=df[\"Delivery_Time\"]\n", + "\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "\n", + "X" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "scaler = StandardScaler()\n", + "X_scaled = scaler.fit_transform(X)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 6: Write your code here:\n", + "#not needed the task is not classifiction" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "# i split above for scaling" + ], + "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, mean_squared_error\n", + "\n", + "kf = KFold(n_splits=5, shuffle=True, random_state=42)\n", + "\n", + "model = RandomForestRegressor(n_estimators=100, max_depth=20, random_state=42)\n", + "\n", + "mse_scores = []\n", + "mae_scores = []\n", + "\n", + "for train_idx, test_idx in kf.split(X_scaled):\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", + " # Train model\n", + " model.fit(X_train, y_train)\n", + "\n", + " # Predict\n", + " y_pred = model.predict(X_test)\n", + "\n", + " # Evaluation metrics\n", + " mse_scores.append(mean_squared_error(y_test, y_pred))\n", + " mae_scores.append(mean_absolute_error(y_test, y_pred))\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\"MSE : {np.mean(mse_scores):.2f}\")\n", + "print(f\"MAE : {np.mean(mae_scores):.2f}\")\n", + "print(f\"RMSE: {np.sqrt(np.mean(mse_scores)):.2f}\")\n", + "print(\"-\"*40)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "\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()\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "# Feature importance\n", + "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(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.figure(figsize=(10, 5))\n", + "plt.hist(y_pred, bins=30, edgecolor='black')\n", + "plt.title(' delivery time predictions Distribution')\n", + "plt.xlabel(' delivery time')\n", + "plt.ylabel('Frequency')\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "models = {\n", + " \"Ridge Regression\": Ridge(alpha=1.0, max_iter=10000),\n", + " \"LASSO Regression\": Lasso(alpha=1.0, max_iter=10000),\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 = 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": [] + } + ], + "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/292/Q2.ipynb b/submissions_extracted/292/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..f7ff5a22e6ed77d72f9df92dc5fd2882b002e8e9 --- /dev/null +++ b/submissions_extracted/292/Q2.ipynb @@ -0,0 +1,432 @@ +{ + "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": [ + "type(X_train)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "labels_df.value_counts()" + ], + "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", + "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": [ + "X_train.shape\n", + "type(X_train)" + ], + "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", + "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", + "# 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", + "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", + "\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)#36*36 *3\n", + "\n", + " # Second linear layer: hidden layer -> hidden layer\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(32 *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", + " z3 = self.layer2(a2)\n", + " a3 = self.relu(z3)\n", + "\n", + " output = self.layer4(a2)\n", + "\n", + " return output" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "X_batch.shape" + ], + "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: torch.Size([32, 3, 36, 36])\n", + " y_batch = y_batch.view(32, -1).to(device) # shape: (batch_size, 1)\n", + "\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": [ + "\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 3: Write your validation loop here:\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(\"cpu\")# the gpu was not choseen so i put cpu only\n", + "\n", + "# Model parameters\n", + "input_dim = 36*36 *3\n", + "hidden_dim = 64 # Design choice\n", + "\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}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "num_epochs = 20\n", + "learning_rate = 0.001\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!')#proplem with the shapes there was no time to solve the small erorr" + ], + "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/292/Q3.ipynb b/submissions_extracted/292/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..4e26632b42b79d26b05fee27add42581d0cd9767 --- /dev/null +++ b/submissions_extracted/292/Q3.ipynb @@ -0,0 +1,429 @@ +{ + "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" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\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", + "path_data = os.path.join(path, 'Q3_data.csv')\n", + "df = pd.read_csv(path_data)\n", + "\n", + "print(f\"Shape: {df.shape}\")\n", + "df.head()" + ], + "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 1: Write your code here:\n", + "df.isnull().sum()\n", + "df.drop(\"D_142\",inplace=True,axis=1)# so many missing values so the appropriate thing to do is drop it" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "df[\"P_2\"].isnull().sum()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "df\n", + "for col in df.columns:\n", + " if df[col].isnull().sum() != 0:\n", + " df[col] = df[col].fillna(df[col].mean())\n", + "\n", + "df.isnull().sum()\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "\n", + "# 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" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "# there are no categorical variables" + ], + "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 4: Write your code here:\n", + "scaler = StandardScaler()\n", + "X_scaled = scaler.fit_transform(X)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "y.value_counts() #big imbalance" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "import seaborn as sns\n", + "sns.countplot(y)" + ], + "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", + "# i split above" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "!pip install catboost # i did not google it i promise" + ], + "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 catboost import CatBoostClassifier\n", + "\n", + "\n", + "skf = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)# will use to keep ratio for the classes\n", + "accuraces = []\n", + "precisions = []\n", + "recalls = []\n", + "f1s = []\n", + "\n", + "\n", + "model =CatBoostClassifier(verbose=0,\n", + " n_estimators=320,\n", + " max_depth=4)\n", + "\n", + "\n", + "for fold_idx, (train_index, test_index) in enumerate(skf.split(X, y)):\n", + "\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", + "\n", + "\n", + "\n", + " model.fit(X_train, y_train) # train\n", + " y_pred = model.predict(X_test) # validate\n", + "\n", + "\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", + "\n", + "\n", + " accuraces.append(accuracy)\n", + " precisions.append(precision)\n", + " recalls.append(recall)\n", + " f1s.append(f1)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "print(f\" Accuracy: {np.mean(accuraces):.4f}\")\n", + "print(f\" Precision: {np.mean(precisions):.4f}\")\n", + "print(f\" Recall: {np.mean(recalls):.4f}\")\n", + "print(f\" F1-Score: {np.mean(f1s):.4f}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "X1=df[]" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "cols = ['P_2', 'D_39', 'B_1', 'B_2']" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "# Feature importance\n", + "importance = pd.DataFrame({\n", + " 'feature':X.columns\n", + " ,\n", + "\n", + " 'importance': model.feature_importances_\n", + "}).sort_values('importance', ascending=False)\n", + "\n", + "plt.figure(figsize=(100, 100))\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()#P2 ia the golden" + ], + "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", + "\n", + "X=df[\"P_2\"]\n", + "y=df[\"Target\"]" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "y" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "X" + ], + "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 catboost import CatBoostClassifier\n", + "\n", + "\n", + "skf = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)# will use to keep ratio for the classes\n", + "accuraces2 = []\n", + "precisions2 = []\n", + "recalls2 = []\n", + "f1s2 = []\n", + "\n", + "\n", + "model =CatBoostClassifier(verbose=0,\n", + " n_estimators=320,\n", + " max_depth=4)\n", + "\n", + "\n", + "for fold_idx, (train_index, test_index) in enumerate(skf.split(X, y)):\n", + "\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", + "\n", + "\n", + "\n", + " model.fit(X_train, y_train) # train\n", + " y_pred = model.predict(X_test) # validate\n", + "\n", + "\n", + "\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", + "\n", + "\n", + " accuraces2.append(accuracy)\n", + " precisions2.append(precision)\n", + " recalls2.append(recall)\n", + " f1s2.append(f1)" + ], + "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/293/Q1.ipynb b/submissions_extracted/293/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..96e64ad56bb409e82c94fe724852f33acb5acc75 --- /dev/null +++ b/submissions_extracted/293/Q1.ipynb @@ -0,0 +1,267 @@ +{ + "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", + "\n", + "import os\n", + "#we need to import the panda\n", + "import pandas as pd\n", + "csv_path = os.path.join(path, \"Q1_data.csv\")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "# so here we will read the file\n", + "df = pd.read_csv(csv_path)\n", + "# so here we will the head which are the 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", + "#here only we nedd to show the describe\n", + "df.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "# so here we need to print the Delevery time\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", + "#here we need to call the function that prints that we have created\n", + "check_target_distribution(df, \"Delivery_Time\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "# so here firstly we need to drop the Order_id coulumn\n", + "#here we will drop and in rhe table it shows that it is dropped\n", + "df.drop(\"Order_ID\", axis=1)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "#here we will check for the 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", + "# so know after handeling them we need to deal with them\n", + "df_clean = df.dropna(subset=['Weather', 'Traffic_Level', 'Time_of_Day','Courier_Experience_yrs','Delivery_Time'])\n", + "print(f\"After dropping missing price/year/odometer: {df_clean.shape}\")\n", + "# know by that missing values should have een dropped by dropping there r" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "#here we need to chack 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)\n", + "# we have a duplicate that we need to remove\n", + "df_clean=df.drop_duplicates(inplace=True)\n", + "# so here we removed the duplicate values" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "# here we needd to lable the catorigal varlues for reference only i need to see the catacorecal coulumns\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 IPython.display import clear_output\n", + "df=df.info()\n", + "from sklearn.preprocessing import LabelEncoder\n", + "# here we nedd to make our catorigal coulumns\n", + "categorical_cols = df_clean.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", + "\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 6: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "# Use previously generated random data (example: classification data)\n", + "from sklearn.linear_model import LogisticRegression\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(\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", + "# 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 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/293/Q2.ipynb b/submissions_extracted/293/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..9bcf7a505c6635d225696157a044201dd776872f --- /dev/null +++ b/submissions_extracted/293/Q2.ipynb @@ -0,0 +1,385 @@ +{ + "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\n", + "import torch\n", + "from torch.utils.data import TensorDataset\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", + "print(X_train.flatten(start_dim=2))\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" + ], + "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)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 3. Create DataLoaders\n", + "from torch.utils.data import DataLoader\n", + "train_loader = DataLoader(\n", + " train_dataset,\n", + " batch_size=32,\n", + " shuffle=True,\n", + " num_workers=2\n", + ")\n", + "test_loader = DataLoader(\n", + " test_dataset,\n", + " batch_size=32,\n", + " shuffle=False,\n", + " num_workers=2\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", + "# 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", + "X_batch.flatten(start_dim=1)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 4. Print shape of one batch\n", + "\n", + "train_loader[0]" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 5. Display sample images\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", + "sample_image.flatten(start_dim=1)\n", + "sample_image.size()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import torch.nn as nn\n", + "class NN4Layer(nn.Module):\n", + "\n", + " def __init__(self, input_dim, hidden_dim,output_dim):\n", + "\n", + " super(NN4Layer, 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,hidden_dim )\n", + " # hidden_dim = num of neurons, Output for binary classification is 1\n", + " self.layer3 = nn.Linear(hidden_dim,hidden_dim )\n", + " # hidden_dim = num of neurons, Output for binary classification is 1\n", + " self.layer4 = nn.Linear(hidden_dim,hidden_dim )\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", + " # here we are makkinh the a and the z for each layer\n", + " def forward(self, x):\n", + " z1 = self.layer1(x)\n", + " a1 = self.segmoid(z1)\n", + " z2 = self.layer2(a1)\n", + " a2 = self.sigmoid(z2)\n", + " a3= self.sigmoid(a2)\n", + " z3=self.layer3(z3)\n", + " a4=self.sigmoid(a3)\n", + " z4=self.layer4(z4)\n", + "\n", + " output = self.layer3(a4) # 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", + "from torch.optim import Adam\n", + "device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n", + "\n", + "# Model parameters\n", + "input_dim = 36*36 # MNIST images flattened\n", + "hidden_dim = 14 # 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", + "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", + "# Run Training\n", + "train_losses = []\n", + "val_losses = []\n", + "val_accuracies = []\n", + "num_epochs = 20\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", + "# right here i know there is an error i tried to flatten the batch or whatever it is not working with me so i may complete also if i have this error" + ], + "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/293/Q3.ipynb b/submissions_extracted/293/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..7d4e112f0329011223be6448be6457341ac27096 --- /dev/null +++ b/submissions_extracted/293/Q3.ipynb @@ -0,0 +1,215 @@ +{ + "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", + "\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", + "csv_path = os.path.join(path, \"Q3_data.csv\")\n", + "\n", + "df = pd.read_csv(csv_path)\n", + "\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "#here we are inspecting the first few 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 1: Write your code here:\n", + "#here we will check for the 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", + "for col in df:\n", + " df[col] = df[col].fillna('unknown')\n", + "\n", + "\n", + "\n", + "print(\"Missing values remaining:\", df.isnull().sum().sum())\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", + "# we have a duplicate that we need to remove\n", + "df_clean=df.drop_duplicates(inplace=True)\n", + "# so here we removed the duplicate values" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "from sklearn.preprocessing import StandardScaler, LabelEncoder\n", + "scaler = StandardScaler()\n", + "df = df.drop(coulumns=\"Unnamed: 0\", axis=1)\n", + "df = scaler.fit_transform(df)\n", + "df= scaler.transform(df)" + ], + "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/294/Q1.ipynb b/submissions_extracted/294/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..e0a4565bdcf42c4df830fc3063dd735183018232 --- /dev/null +++ b/submissions_extracted/294/Q1.ipynb @@ -0,0 +1,305 @@ +{ + "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: Read Data\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: Inspect the first few rows using head()\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3:Display dataset information using info()\n", + "df.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Show statistical description using\n", + "df.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Plot the target distribution (delivery_time)\n", + "def check_target_distribution(df, target_column):\n", + " df[target_column].hist(bins=30, edgecolor='blue')\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": [ + "#tak1\n", + "df = df.drop(['Order_ID'], axis=1) #axis=1 drop column\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Handle missing values appropriately** (Hint: I guess you want to have a closer look at the columns with missing values :)\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": [ + "# Task 3: 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: Encode categorical variables if needed\n", + "# checking if we have categorical columns?\n", + "\n", + "categorical_cols = df.select_dtypes(include=[\"object\"]).columns\n", + "\n", + "print(\"Categorical Columns:\", list(categorical_cols))\n", + "\n", + "#since there's categorical values we should encode them\n", + "from sklearn.preprocessing import OneHotEncoder #import OneHotEncoder\n", + "\n", + "print('data before encoding:\\n', df) #show before encoding\n", + "onehot_encoder = OneHotEncoder(sparse_output=False) # Instantiate OneHotEncoder\n", + "data_onehot_encoded = onehot_encoder.fit_transform(df[categorical_cols]) # Apply fit_transform to the copied\n", + "print('\\nData after encoding:\\n', data_onehot_encoded) #show after encoding" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: pply feature scaling for all features** (Use StandardScaler)\n", + "from sklearn.preprocessing import StandardScaler\n", + "features = df.columns.drop(\"Delivery_Time\") # DON'T SCALE THE TARGET\n", + "\n", + "before=features.head() #visual to double check\n", + "\n", + "print('data before scaling:\\n', before) #show before scaling\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: Check for target imbalance and state if it is imbalanced or not\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\")\n", + "#observation: imbalanced data" + ], + "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'].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, f1_score\n", + "n_splits = 3 # K=3 Folds\n", + "skf = StratifiedKFold(n_splits=n_splits, shuffle=True, random_state=42) #imabalnced data\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "#3 rf\n", + "from sklearn.ensemble import RandomForestRegressor\n", + "model=RandomForestRegressor(n_estimators=200)\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]" + ], + "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/294/Q2.ipynb b/submissions_extracted/294/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..751bdbec11db557638fde93ccfb2edfba72d9122 --- /dev/null +++ b/submissions_extracted/294/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 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", + "labels_df.info()\n", + "\n", + "# transform to tensors\n", + "X_train = torch.tensor(X_train.values, dtype=torch.object)\n", + "X_test = torch.tensor(X_test.values, dtype=torch.object)\n", + "y_train = torch.tensor(y_train.values, dtype=torch.int64)\n", + "y_test = torch.tensor(y_test.values, dtype=torch.int64)\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) #no shuffling in test so it won't get leaked.\n", + "\n", + "# Print dataset sizes\n", + "print(\"Train dataset:\", len(train_dataset)) #to print the length of both datasets\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", + "\n" + ], + "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" + ], + "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}\") #printing shape\n", + "print(f\"Training batch labels shape: {y_batch.shape}\") #printing shape\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 5. Display sample images\n", + "# we will 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", + "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", + " #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", + " a3= self.relu(self.layer3(a2))\n", + "\n", + " # Output layer (regression output) because it's age\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.view(-1, 1).to(device)\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 = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n", + "# Model parameters\n", + "input_dim = X_train.shape[1]\n", + "hidden_dim = 32 # Design choice any number power of 2\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}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Start training for 20 epochs:\n", + "# Hyperparameters\n", + "num_epochs = 20\n", + "learning_rate = 0.01\n", + "\n", + "# Define 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": [ + "#run training (extra) just calling the functions\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\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": [] + } + ], + "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/294/Q3.ipynb b/submissions_extracted/294/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..c1124d3d0a7ca49a162d67a8fa3f6168e5b3a849 --- /dev/null +++ b/submissions_extracted/294/Q3.ipynb @@ -0,0 +1,343 @@ +{ + "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", + "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", + "# 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": [ + "# Task 2: 2. **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)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Encode categorical variables** if needed\n", + "# 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", + "label_encoders = encode_categorical_columns(df) #since no categorical value to need for encoding" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Apply feature scaling to numerical features (Use StandardScaler)\n", + "from sklearn.preprocessing import StandardScaler #import StandardScaler\n", + "features = df.columns.drop(\"Target\") #don;t scale target\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: Check for target imbalance and state if it is imbalanced or not\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, \"Target\")\n", + "#imbalanced data" + ], + "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", + "#StratifiedKFold because it's unbalanced\n", + "from sklearn.model_selection import StratifiedKFold\n", + "from sklearn.metrics import accuracy_score, f1_score\n", + "n_splits = 3 # K=3 Folds\n", + "skf = StratifiedKFold(n_splits=n_splits, shuffle=True, random_state=42) #imabalnced data" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "!pip install catboost" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "#3\n", + "# Import models\n", + "# Import models\n", + "from sklearn.neighbors import KNeighborsClassifier\n", + "from catboost import CatBoostClassifier" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "sklearn_models = { \"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": [ + "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}\") #it looks better because imabalnced data gives highlu optimistic results\n", + " print(f\" F1-Score: {np.mean(all_results[model_name]['f1']):.4f}\") #its better since its unbalanced" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1:\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:" + ], + "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/295/Q1.ipynb b/submissions_extracted/295/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..38572754745e0873a9466d22a2ff1e3d70a7e909 --- /dev/null +++ b/submissions_extracted/295/Q1.ipynb @@ -0,0 +1,325 @@ +{ + "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", + "# 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", + "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", + "missing_values = df.isnull().sum()\n", + "\n", + "print(\"Missing Values per Column:\")\n", + "print(missing_values)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "df=df.dropna(subset=['Weather','Traffic_Level', 'Time_of_Day', 'Courier_Experience_yrs', 'Delivery_Time'])\n", + "missing_values = df.isnull().sum()\n", + "\n", + "print(\"Missing Values after Dropping Rows:\")\n", + "print(missing_values)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "duplicates = df.duplicated().sum()\n", + "print(\"Number of Duplicate Samples: \")\n", + "print(duplicates)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "df.drop_duplicates(inplace=True)\n", + "\n", + "duplicates = df.duplicated().sum()\n", + "print(\"Number of Duplicate Samples: \")\n", + "print(duplicates)" + ], + "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", + "for col in categorical_cols:\n", + " print(f\"Encoding column: {col}\")\n", + " le = LabelEncoder()\n", + " df[col] = le.fit_transform(df[col])\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", + "\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", + "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", + "X = df.drop(\"Delivery_Time\", axis=1)\n", + "y = df[\"Delivery_Time\"]\n", + "\n", + "X_train, X_test, y_train, y_test = train_test_split(\n", + " 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", + "from sklearn.model_selection import KFold\n", + "from sklearn.metrics import mean_absolute_error\n", + "from sklearn.ensemble import RandomForestClassifier\n", + "import numpy as np\n", + "\n", + "model = RandomForestClassifier(\n", + " n_estimators=100,\n", + " max_depth=15,\n", + " class_weight='balanced',\n", + " random_state=42\n", + ")\n", + "\n", + "kf = KFold(n_splits=5, shuffle=True, random_state=42)\n", + "\n", + "mae_scores = []\n", + "\n", + "for train_idx, test_idx in kf.split(X):\n", + " X_train = X.iloc[train_idx]\n", + " X_test = X.iloc[test_idx]\n", + " y_train = y.iloc[train_idx]\n", + " y_test = y.iloc[test_idx]\n", + "\n", + " model.fit(X_train, y_train)\n", + " y_pred = model.predict(X_test)\n", + "\n", + " mae_scores.append(mean_absolute_error(y_test, y_pred))\n", + "\n", + "print(\"\\nModel Evaluation Metrics (K-Fold)\")\n", + "print(\"-\" * 40)\n", + "print(f\"MAE : {np.mean(mae_scores):.2f}\")\n", + "print(\"-\" * 40)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "importances = model.feature_importances_\n", + "features = X.columns\n", + "\n", + "importance_df = pd.DataFrame({\n", + " \"Feature\": features,\n", + " \"Importance\": importances\n", + "}).sort_values(by=\"Importance\", ascending=False)\n", + "\n", + "plt.figure(figsize=(10, 6))\n", + "plt.barh(importance_df[\"Feature\"], importance_df[\"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", + "plt.figure(figsize=(10, 5))\n", + "plt.hist(df['Delivery_Time'].dropna(), bins=30, edgecolor='black', color='orange')\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/295/Q2.ipynb b/submissions_extracted/295/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..e9e4f6f6bc9f4b1b4e0744ce39e8dd66d3a69fe6 --- /dev/null +++ b/submissions_extracted/295/Q2.ipynb @@ -0,0 +1,428 @@ +{ + "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)" + ], + "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)" + ], + "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", + ")" + ], + "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", + "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()" + ], + "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", + " # 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", + " x = x.view(x.size(0), -1) # FLATTEN IMAGE\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", + " 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.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", + "\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 = 64\n", + "output_dim = 4\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" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Start training for 20 epochs:\n", + "from torch.optim import AdamW\n", + "\n", + "num_epochs = 20\n", + "learning_rate = 0.001\n", + "\n", + "# Define criterion\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", + "\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", + "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 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": [] + }, + { + "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/295/Q3.ipynb b/submissions_extracted/295/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..25bcaa8ec3e028780d23f63225c7cdfc44a45174 --- /dev/null +++ b/submissions_extracted/295/Q3.ipynb @@ -0,0 +1,283 @@ +{ + "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')\n", + "\n", + "%pip install kagglehub catboost lightgbm tqdm -q" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\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", + "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", + "missing_values = df.isnull().sum()\n", + "\n", + "print(\"Missing Values per Column:\")\n", + "print(missing_values)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "df = df.dropna(subset=['P_2', 'B_2', 'D_43','D_42', 'D_137', 'D_138','D_142','D_143','D_144', 'D_145'])\n", + "missing_values = df.isnull().sum()\n", + "\n", + "print(\"Missing Values after Dropping Rows:\")\n", + "print(missing_values)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "duplicates = df.duplicated().sum()\n", + "print(\"Number of Duplicate Samples: \")\n", + "print(duplicates)" + ], + "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", + "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\") # 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", + "\n", + " df[target_column].hist()\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\"]\n", + "\n", + "X_train, X_test, y_train, y_test = train_test_split(\n", + " 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", + "from sklearn.model_selection import StratifiedKFold\n", + "from sklearn.metrics import accuracy_score, f1_score\n", + "from catboost import CatBoostClassifier\n", + "import numpy as np\n", + "\n", + "X = df.drop(\"Target\", axis=1)\n", + "y = df[\"Target\"]\n", + "\n", + "skf = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)\n", + "\n", + "acc_scores = []\n", + "f1_scores = []\n", + "\n", + "model = CatBoostClassifier(\n", + " iterations=100,\n", + " depth=8,\n", + " learning_rate=0.1,\n", + " verbose=0,\n", + " random_state=42\n", + ")\n", + "\n", + "for train_idx, test_idx in skf.split(X, y):\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)\n", + " y_pred = model.predict(X_test)\n", + "\n", + " acc_scores.append(accuracy_score(y_test, y_pred))\n", + " f1_scores.append(f1_score(y_test, y_pred))\n", + "\n", + "print(\"Model Evaluation (Stratified K-Fold)\")\n", + "print(\"-\" * 40)\n", + "print(f\"Average Accuracy : {np.mean(acc_scores):.4f}\")\n", + "print(f\"Average F1 Score : {np.mean(f1_scores):.4f}\")\n", + "print(\"-\" * 40)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "importances = model.feature_importances_\n", + "features = X.columns\n", + "\n", + "importance_df = pd.DataFrame({\n", + " \"Feature\": features,\n", + " \"Importance\": importances\n", + "}).sort_values(by=\"Importance\", ascending=False)\n", + "\n", + "plt.figure(figsize=(10, 6))\n", + "plt.barh(importance_df[\"Feature\"], importance_df[\"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", + "golden_feature = importance_df.sort_values(\n", + " by=\"Importance\", ascending=False\n", + ").iloc[0][\"Feature\"]\n", + "\n", + "print(\" Golden Feature:\", 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/296/Q1.ipynb b/submissions_extracted/296/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..cfcba0c5efa8513208f3d031679e25b5e46323ac --- /dev/null +++ b/submissions_extracted/296/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", + "from lightgbm import LGBMRegressor\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", + "Q1_data = pd.read_csv(Q1_path)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "Q1_data.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "Q1_data.info()\n", + "# there are some nulls in the data as you can see" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "Q1_data.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "Q1_data[\"Delivery_Time\"].hist()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "clean_data = Q1_data.drop(\"Order_ID\", axis=1)\n", + "clean_data" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "# we split the numeric data then the categorical data then fill with mean and mode respectivly\n", + "categorical_cols = clean_data.select_dtypes(include=[\"object\"]).columns\n", + "num_cols = clean_data.select_dtypes(include=[\"int64\", \"float64\"]).columns\n", + "\n", + "for col in categorical_cols:\n", + " clean_data[col] = clean_data[col].fillna(clean_data[col].mode()[0])\n", + "for col in num_cols:\n", + " clean_data[col] = clean_data[col].fillna(clean_data[col].mean())\n", + "\n", + "clean_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(clean_data)\n", + "clean_data.info()\n", + "# there was dublicate but i ran the code twice by mistake because i wanted to see the number of sampels" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "\n", + "\n", + "for col in categorical_cols:\n", + "\n", + " le = LabelEncoder()\n", + " clean_data[col] = le.fit_transform(clean_data[col].astype(str))\n", + "\n", + "clean_data.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "features_cols = clean_data.select_dtypes(include=[\"int64\", \"float64\", \"object\"]).columns.drop(\"Delivery_Time\")\n", + "print(features_cols)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "features_cols = clean_data.select_dtypes(include=[\"int64\", \"float64\", \"object\"]).columns.drop(\"Delivery_Time\")\n", + "scaler = StandardScaler()\n", + "clean_data[features_cols] = scaler.fit_transform(clean_data[features_cols])\n", + "\n", + "clean_data.head()\n", + "# as you can see i scaled everything exept the target" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 6: Write your code here:\n", + "# the target is continus so there is no such thing as imbalnce" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "X = clean_data[features_cols]\n", + "y = clean_data[\"Delivery_Time\"]\n", + "\n", + "X.head()\n" + ], + "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", + "mae_scores = []\n", + "\n", + "model = RandomForestRegressor(n_estimators=100, max_depth=20, random_state=42, n_jobs=-1)\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", + "\n", + " model.fit(X_train, y_train)\n", + " y_pred = model.predict(X_test)\n", + " mae_scores.append(mean_absolute_error(y_test, y_pred))\n", + "\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 = pd.DataFrame({\n", + " 'feature': features_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", + "y_pred_frame = pd.DataFrame({'Y_pred': y_pred})\n", + "y_pred_frame.hist()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:\n", + "kf = KFold(n_splits=5, shuffle=True, random_state=42)\n", + "mae_scores = []\n", + "\n", + "model1 = RandomForestRegressor(n_estimators=100, max_depth=20, random_state=42, n_jobs=-1)\n", + "model2 = LGBMRegressor(verbose=-1)\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", + "\n", + " model1.fit(X_train, y_train)\n", + " model2.fit(X_train, y_train)\n", + " y_pred1 = model.predict(X_test)\n", + " y_pred2 = model.predict(X_test)\n", + " A_pred = (y_pred1 + y_pred2)/2\n", + " mae_scores.append(mean_absolute_error(y_test, A_pred))\n", + "\n", + "\n", + "mae_scores = np.array(mae_scores)\n", + "\n", + "print(f\"5-Fold CV Results for 2 models:\")\n", + "print(f\"MAE: ${mae_scores.mean():,.2f}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# the MAE is signefectly better since we are avraging the predection of 2 models (1-RandomForestRegressor 2- LGBMRegressor )" + ], + "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