diff --git a/submissions_extracted/140/Q1.ipynb b/submissions_extracted/140/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..482560457a8eadca7d0144a65ffdf036ac97c0a0 --- /dev/null +++ b/submissions_extracted/140/Q1.ipynb @@ -0,0 +1,507 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import pandas as pd\n", + "import seaborn as sns\n", + "import matplotlib.pyplot as plt\n", + "from sklearn.preprocessing import OneHotEncoder,StandardScaler,MinMaxScaler,LabelEncoder\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", + "import numpy as np" + ], + "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(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": [ + "df[\"Delivery_Time\"].head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "plt.hist(df[\"Delivery_Time\"],bins=30)" + ], + "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", + "df.isna().sum()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "missing_cols = df.columns.drop([\"Distance_km\",\"Vehicle_Type\",\"Preparation_Time_min\"])\n", + "df[missing_cols]" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "#Not good to fill Target Variable's values, so better to drop them\n", + "df.dropna(subset=\"Delivery_Time\",inplace=True)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "df[\"Courier_Experience_yrs\"].unique()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "df[\"Courier_Experience_yrs\"].fillna(round(df[\"Courier_Experience_yrs\"].mean()),inplace=True)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "df[\"Time_of_Day\"].unique()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "df[\"Time_of_Day\"].fillna(df[\"Time_of_Day\"].mode()[0],inplace=True)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "df[\"Traffic_Level\"].unique()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "df[\"Traffic_Level\"].fillna(df[\"Traffic_Level\"].mode()[0],inplace=True)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "df[\"Weather\"].unique()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "df[\"Weather\"].fillna(df[\"Weather\"].mode()[0],inplace=True)" + ], + "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", + "print(df.duplicated().sum())\n", + "if df.duplicated().sum() > 0:\n", + " df.drop_duplicates(inplace=True)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "df.duplicated().sum()" + ], + "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", + "df.select_dtypes(include=[\"object\"]).columns" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "print(df[\"Weather\"].unique())\n", + "print(df[\"Traffic_Level\"].unique())\n", + "print(df[\"Time_of_Day\"].unique())\n", + "print(df[\"Vehicle_Type\"].unique())" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "cat_cols = ['Weather', 'Traffic_Level', 'Time_of_Day', 'Vehicle_Type']\n", + "ohe = OneHotEncoder()\n", + "ohe_result = ohe.fit_transform(df[['Weather', 'Time_of_Day', 'Vehicle_Type']])" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "temp_df = pd.DataFrame(columns=ohe.get_feature_names_out(),data=ohe_result.toarray())\n", + "temp_df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "dfOHE = pd.concat([df.drop(['Weather', 'Time_of_Day', 'Vehicle_Type'],axis=1),temp_df],axis=1)\n", + "dfOHE.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "df.shape" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "dfOHE.shape" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "dfOHE.dropna(inplace=True)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "le = LabelEncoder()\n", + "dfOHE[\"Traffic_Level\"] = le.fit_transform(dfOHE[\"Traffic_Level\"])" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "dfOHE.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "dcols = dfOHE.columns.drop(\"Delivery_Time\") ## desired columns (not scaling target)\n", + "sc = StandardScaler()\n", + "dfOHE[dcols] = sc.fit_transform(dfOHE[dcols])" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 6: Write your code here:\n", + "dfOHE[\"Delivery_Time\"].skew()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "plt.hist(dfOHE[\"Delivery_Time\"],bins=50)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "dfOHE.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "X = dfOHE.drop(\"Delivery_Time\",axis=1).values\n", + "y = dfOHE[\"Delivery_Time\"].values\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:\n", + "kf = StratifiedKFold(n_splits=5,shuffle=True,random_state=42)\n", + "model=RandomForestRegressor(n_estimators=100, max_depth=20, random_state=42)\n", + "mae_scores = []\n", + "predictions = []" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "for fold, (train_idx, test_idx) in enumerate(kf.split(X, y), start=1):\n", + " X_fold_train, X_fold_val = X[train_idx], X[test_idx]\n", + " y_fold_train, y_fold_val = y[train_idx], y[test_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", + " predictions.append(y_fold_pred)\n", + " # Calculate metrics\n", + " mae_scores.append(mean_absolute_error(y_fold_val, y_fold_pred))\n", + "\n", + "mae_scores = np.array(mae_scores).mean()\n", + "print(f\"5-Fold CV Results:\")\n", + "print(f\"MAE: {mae_scores}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "len(model.feature_importances_)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "len(dfOHE.columns.drop(\"Delivery_Time\"))" + ], + "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': dfOHE.columns.drop(\"Delivery_Time\"),\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(predictions,bins=30)" + ], + "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/140/Q2.ipynb b/submissions_extracted/140/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..f53273ab89b1cddd2ebde19c01c9e9b349c1f0d3 --- /dev/null +++ b/submissions_extracted/140/Q2.ipynb @@ -0,0 +1,370 @@ +{ + "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,TensorDataset\n", + "from torch.optim import Adam\n", + "from torchvision.transforms.functional import to_tensor\n", + "import torch.nn.functional as F\n", + "import matplotlib.pyplot as plt" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q2-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import os\n", + "import pandas as pd\n", + "import numpy as np\n", + "from PIL import Image\n", + "from sklearn.model_selection import train_test_split\n", + "\n", + "# Load Labels\n", + "labels_df = pd.read_csv(os.path.join(path, \"labels.csv\"))\n", + "img_dir = os.path.join(path, \"images\")\n", + "\n", + "images = []\n", + "ages = []\n", + "\n", + "# Load Images and Resize\n", + "print(\"Loading images...\")\n", + "for index, row in labels_df.iterrows():\n", + " img_name = row.iloc[0]\n", + " age = row.iloc[1]\n", + " img_path = os.path.join(img_dir, img_name)\n", + "\n", + " if os.path.exists(img_path):\n", + " img = Image.open(img_path).convert('RGB')\n", + " img_array = np.array(img) / 255.0 # Normalize pixel values to [0, 1]\n", + " images.append(img_array)\n", + " ages.append(age)\n", + "\n", + "X = np.array(images)\n", + "y = np.array(ages)\n", + "\n", + "# Transpose image dimensions to match PyTorch format (N, C, H, W)\n", + "X = np.transpose(X, (0, 3, 1, 2))\n", + "\n", + "# Split Data\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n", + "\n", + "print(f\"X_train shape: {X_train.shape}\")\n", + "print(f\"X_test shape: {X_test.shape}\")\n", + "print(f\"y_train shape: {y_train.shape}\")\n", + "print(f\"y_test shape: {y_test.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 1. Convert Numpy arrays to PyTorch Tensors\n", + "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", + "\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 3. Create DataLoaders\n", + "# Create Dataloaders to train and test data in batches\n", + "train_loader = DataLoader(train_dataset, batch_size=32, shuffle=True)\n", + "test_loader = DataLoader(test_dataset, batch_size=32, shuffle=False)\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 4. Print shape of one batch\n", + "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", + "\n", + " def __init__(self, input_dim,hidden_dim1,hidden_dim2,hidden_dim3):\n", + " super(NN4Layer, self).__init__()\n", + " self.seq = nn.Sequential(\n", + " nn.Linear(input_dim,hidden_dim1),\n", + " nn.ReLU(),\n", + "\n", + " nn.Linear(hidden_dim1,hidden_dim2),\n", + " nn.ReLU(),\n", + "\n", + " nn.Linear(hidden_dim2,hidden_dim3),\n", + " nn.ReLU(),\n", + "\n", + " nn.Linear(hidden_dim3,1)\n", + " )\n", + "\n", + "\n", + "\n", + "\n", + " # forward pass\n", + " def forward(self, x):\n", + " y = self.seq(x)\n", + " return y" + ], + "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.shape[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", + "\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.shape[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", + " # Binary predictions\n", + " predicted = (outputs > 0.5).float()\n", + "\n", + " # Accuracy calculation\n", + " correct += (predicted == y_batch).sum().item()\n", + " total += y_batch.size(0)\n", + "\n", + " avg_loss = running_loss / len(test_loader)\n", + " accuracy = correct / total\n", + "\n", + " return avg_loss, accuracy\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Define device, model, loss, optimizer:\n", + "# Device configuration\n", + "device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\n", + "print(f\"Using device: {device}\")\n", + "\n", + "num_epochs = 20\n", + "learning_rate = 0.001\n", + "\n", + "# Model, Criterion, Optimizer\n", + "input_dim = 3*36*36\n", + "hidden_dim1 = 64\n", + "hidden_dim2 = 32\n", + "hidden_dim3 = 32\n", + "model =NN4Layer(input_dim, hidden_dim1,hidden_dim2,hidden_dim3).to(device)\n", + "criterion = nn.MSELoss()\n", + "optimizer = Adam(model.parameters(), lr=learning_rate)\n", + "\n", + "\n", + "# Run Training\n", + "train_losses = []\n", + "val_losses = []\n", + "val_accuracies = []\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Start training for 20 epochs:\n", + "print('Starting Training...')\n", + "for epoch in range(num_epochs):\n", + " # Train one epoch\n", + " train_loss = train_one_epoch(model, optimizer, criterion, train_loader, device)\n", + "\n", + " # Validate\n", + " val_loss, val_accuracy = validate(model, criterion, test_loader, device)\n", + "\n", + " train_losses.append(train_loss)\n", + " val_losses.append(val_loss)\n", + " val_accuracies.append(val_accuracy)\n", + "\n", + " if (epoch + 1) % 5 == 0:\n", + " print(f'Epoch [{epoch+1}/{num_epochs}], Train Loss: {train_loss:.4f}, Val Loss: {val_loss:.4f}, Val Accuracy: {val_accuracy:.4f}')\n", + "\n", + "print('Training Complete!')" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "# Plotting results\n", + "plt.figure(figsize=(7, 5))\n", + "\n", + "plt.plot(train_losses, label='Train Loss')\n", + "plt.plot(val_losses, label='Validation Loss')\n", + "plt.title('Loss over Epochs')\n", + "plt.xlabel('Epoch')\n", + "plt.ylabel('Loss')\n", + "plt.legend()\n", + "\n", + "plt.tight_layout()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2 (Bonus): Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "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/140/Q3.ipynb b/submissions_extracted/140/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..c6c763d6d2417ee7d696a9bb9b45196c662b8866 --- /dev/null +++ b/submissions_extracted/140/Q3.ipynb @@ -0,0 +1,326 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import pandas as pd\n", + "import numpy as np\n", + "import matplotlib.pyplot as plt\n", + "import seaborn as sns\n", + "from sklearn.preprocessing import StandardScaler\n", + "from catboost import CatBoostClassifier\n", + "from sklearn.ensemble import RandomForestClassifier\n", + "from sklearn.model_selection import StratifiedKFold\n", + "from sklearn.metrics import f1_score, accuracy_score" + ], + "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(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": [ + "df.describe().loc[[\"mean\",\"std\",\"min\",\"max\"]]" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "df.shape" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "ms = df.isna().sum()\n", + "ms_cols = ms[ms > 0].index\n", + "ms_cols" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "df[ms_cols].mean()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "df.fillna(df[ms_cols].mean(),inplace=True)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "df.isna().sum()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "print(df.duplicated().sum())\n", + "df.drop_duplicates(inplace=True)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "df.select_dtypes(include=[\"object\"]).columns" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "sc=StandardScaler()\n", + "dCols = df.columns.drop(\"Target\") ## desired columns to scale (Not scaleing the Target)\n", + "df_scaled = df.copy()\n", + "df_scaled[dCols] = sc.fit_transform(df_scaled[dCols])" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "df_scaled.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "print(df[\"Target\"].value_counts(normalize=True)*100)\n", + "sns.countplot(x=df[\"Target\"])" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "X = df_scaled[dCols].values\n", + "y = df_scaled[\"Target\"].values" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "X.shape" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "y.shape" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:\n", + "kf = StratifiedKFold(n_splits=5,shuffle=True,random_state=42)\n", + "model = CatBoostClassifier()\n", + "accuracy_=[]\n", + "F1Score=[]" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "for fold_idx, (train_index, test_index) in enumerate(kf.split(X, y)):\n", + " # 1. Split data\n", + " X_train, X_test = X[train_index], X[test_index]\n", + " y_train, y_test = y[train_index], y[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", + " f1 = f1_score(y_test, y_pred, zero_division=0)\n", + "\n", + " accuracy_.append(accuracy)\n", + " F1Score.append(f1)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "print(f\"Accracy mean {np.mean(accuracy_)*100}\")\n", + "print(f\"F1 mean {np.mean(F1Score)*100}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Retrieve CatBoost feature importances and sort them\n", + "catboost_importance = list(zip(df.columns, 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=(30, 60))\n", + "plt.barh(features, importances, color='orange')\n", + "plt.xlabel('Importance Score')\n", + "plt.ylabel('Features')\n", + "plt.title('CatBoost Feature Importance')\n", + "plt.yticks()\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(f\"The most important feature is P_2\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/141/Q1.ipynb b/submissions_extracted/141/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..e5f15fecb5d0a3b75712084a2d3977b9ad35951b --- /dev/null +++ b/submissions_extracted/141/Q1.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/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", + "\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.drop(\"Order_ID\",axis = 1,inplace=True)\n", + "df.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "# target must be rows null erase\n", + "null_cols = [\"Delivery_Time\", \"Weather\", \"Traffic_Level\", \"Time_of_Day\", \"Courier_Experience_yrs\"]\n", + "df_clean = df.dropna(subset=null_cols).copy()\n", + "df_clean.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "def check_duplicates(df):\n", + " duplicates = df.duplicated().sum()\n", + " print(f\"Number of Duplicate Samples: {duplicates}\")\n", + " if duplicates > 0:\n", + " print(\"Dropping Duplicates...\")\n", + " df.drop_duplicates(inplace=True)\n", + " print(\"Duplicates Dropped.\")\n", + " else:\n", + " print(\"No Duplicate Samples Found.\")\n", + "\n", + "check_duplicates(df_clean)\n", + "df_clean.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "from sklearn.preprocessing import LabelEncoder, OneHotEncoder, StandardScaler\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])\n", + "df_clean.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "\n", + "numerical_cols = df_clean.select_dtypes(include=[\"int64\", \"float64\"]).columns.drop(\"Delivery_Time\") # DON'T SCALE THE TARGET\n", + "\n", + "scaler = StandardScaler()\n", + "df_clean[numerical_cols] = scaler.fit_transform(df_clean[numerical_cols])\n", + "df_clean.head()\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 6: Write your code here:\n", + "#it kinda unbalanced in the end but not that deep\n", + "check_target_distribution(df_clean, \"Delivery_Time\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "from sklearn.ensemble import RandomForestRegressor\n", + "X = df_clean.drop(\"Delivery_Time\", axis=1).astype(float)\n", + "y = df_clean['Delivery_Time'].astype(float)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:\n", + "from sklearn.model_selection import StratifiedKFold\n", + "\n", + "\n", + "from sklearn.metrics import mean_squared_error as sklearn_mse, mean_absolute_error, r2_score\n", + "mse = 0\n", + "model = RandomForestRegressor(n_estimators=200)\n", + "n_splits = 5 # K=5 Folds\n", + "\n", + "# Stratified 5-Fold Cross-Validation, shuffled\n", + "skf = StratifiedKFold(n_splits=n_splits, shuffle=True, random_state=42)\n", + "for fold_idx, (train_index, test_index) in enumerate(skf.split(X, y)):\n", + " print(f\"\\nFold {fold_idx + 1}/{n_splits}\")\n", + "\n", + " X_train, X_test = X.iloc[train_index], X.iloc[test_index]\n", + " y_train, y_test = y.iloc[train_index], y.iloc[test_index]\n", + " model.fit(X_train, y_train)\n", + "\n", + " # Predict\n", + " y_pred = model.predict(X_test)\n", + "\n", + " # Calculate metrics\n", + " mse_per = sklearn_mse(y_test, y_pred)\n", + " print(\"MSE : \", mse_per)\n", + " mse += mse_per\n", + "\n", + "print(f\" MSE: {mse / n_splits:.4f}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "import numpy as np\n", + "feature_importance = pd.DataFrame({\n", + " 'feature': X.columns,\n", + " 'importance': model.feature_importances_\n", + "}).sort_values('importance', ascending=False)\n", + "plt.figure(figsize=(10, 6))\n", + "plt.barh(feature_importance['feature'], feature_importance['importance'])\n", + "plt.xlabel('Importance')\n", + "plt.title('Feature Importance')\n", + "plt.gca().invert_yaxis()\n", + "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/141/Q2.ipynb b/submissions_extracted/141/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..30cf5b098d3162361c2377a3d9d2682b83948bcf --- /dev/null +++ b/submissions_extracted/141/Q2.ipynb @@ -0,0 +1,406 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "import torch.nn as nn\n", + "import torch.nn.functional as F\n", + "from torch.optim import AdamW\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", + "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", + "unique_label = len(np.unique(labels_df['age']))\n", + "print(\"Unique Label\",unique_label)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 1. Convert Numpy arrays to PyTorch Tensors\n", + "import torch\n", + "from torch.utils.data import TensorDataset\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", + "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", + "# 3. Create DataLoaders\n", + "train_loader = DataLoader(\n", + " train_dataset,\n", + " batch_size=32,\n", + " shuffle=True,\n", + " num_workers=2\n", + ")\n", + "# DataLoader for test/validation data\n", + "test_loader = DataLoader(\n", + " test_dataset,\n", + " batch_size=32,\n", + " shuffle=False,\n", + " num_workers=2\n", + ")\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 4. Print shape of one batch\n", + "\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", + "# 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", + "\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", + " self.layer4 = nn.Linear(hidden_dim, output_dim)\n", + "\n", + "\n", + " # activation function for non-linearity\n", + " self.relu = nn.ReLU()\n", + "\n", + " # Defines how input data flows through the network\n", + " def forward(self, x):\n", + " z1 = self.layer1(x)\n", + " a1 = self.relu(z1)\n", + "\n", + " z2 = self.layer2(a1)\n", + " a2 = self.relu(z2)\n", + "\n", + " z3 = self.layer3(a2)\n", + " a3 = self.relu(z3)\n", + "\n", + " z4 = self.layer4(a3)\n", + "\n", + " return z4" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your training loop here:\n", + "def train_one_epoch(model, optimizer, criterion, train_loader, device):\n", + " # Set the model to training mode\n", + " model.train()\n", + "\n", + " running_loss = 0.0\n", + "\n", + " for X_batch, y_batch in train_loader:\n", + " 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", + "\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", + "\n", + " outputs = model(X_batch)\n", + "\n", + " loss = criterion(outputs, y_batch)\n", + " running_loss += loss.item()\n", + "\n", + "\n", + " probabilities = F.softmax(outputs, dim=1)\n", + "\n", + "\n", + " predicted = torch.argmax(probabilities, dim=1)\n", + "\n", + " # Accuracy calculation\n", + " correct += (predicted == y_batch).sum().item()\n", + " total += y_batch.size(0)\n", + "\n", + " avg_loss = running_loss / len(test_loader)\n", + " accuracy = correct / total\n", + "\n", + " return avg_loss, accuracy" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Define device, model, loss, optimizer:\n", + "# Device setup\n", + "device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n", + "learning_rate = 0.001\n", + "criterion = nn.CrossEntropyLoss()\n", + "optimizer = AdamW(model.parameters(), learning_rate)\n", + "# Model parameters\n", + "input_dim = 3 * 36 * 36\n", + "\n", + "\n", + "hidden_dim = 64\n", + "\n", + "\n", + "output_dim = unique_label+13\n", + "\n", + "\n", + "model = NN4Layer(input_dim, hidden_dim, output_dim).to(device)\n", + "print(\"Model:\")\n", + "print(model)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Start training for 20 epochs:\n", + "def train_one_epoch(model, optimizer, criterion, train_loader, device):\n", + " # Set the model to training mode\n", + " model.train()\n", + "\n", + " running_loss = 0.0\n", + "\n", + " for X_batch, y_batch in train_loader:\n", + " # Move batch to the selected device\n", + " X_batch = X_batch.view(X_batch.size(0), -1).to(device)\n", + " y_batch = y_batch.to(device)\n", + " # Forward pass\n", + " outputs = model(X_batch)\n", + " loss = criterion(outputs, y_batch)\n", + "\n", + " # Backward pass & optimization\n", + " optimizer.zero_grad() # Clear previous gradients\n", + " loss.backward() # Compute gradients\n", + " optimizer.step() # Update model parameters\n", + "\n", + " running_loss += loss.item()\n", + "\n", + " # Average loss over all batches\n", + " avg_loss = running_loss / len(train_loader)\n", + "\n", + " return avg_loss\n", + "\n", + "\n", + "num_epochs = 20\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", + "#I don't how to solve the error I spent 1 hour in this tiny logic error. Please take my apolgizies\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" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/141/Q3.ipynb b/submissions_extracted/141/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..8bc0b90a1c050361e7875016673db24ba0fc1c0c --- /dev/null +++ b/submissions_extracted/141/Q3.ipynb @@ -0,0 +1,289 @@ +{ + "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", + "import os\n", + "\n", + "\n", + "\n", + "# Download latest version\n", + "\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q3-exam-data\")\n", + "\n", + "\n", + "\n", + "print(\"Path to dataset files:\", path)\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)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "df.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "df.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "\n", + "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", + "df = df.fillna(df.mean())\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", + "df.info()\n", + "#No need to encode since no object" + ], + "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])\n", + " plt.title(\"Target Distribution\")\n", + " plt.show()\n", + "\n", + "check_target_imbalance(df, \"Target\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "X = df.drop(\"Target\", axis=1).astype(float)\n", + "y = df['Target'].astype(float)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:\n", + "from sklearn.model_selection import StratifiedKFold\n", + "from catboost import CatBoostClassifier\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", + "sklearn_models = {\n", + " \"CatBoost\": CatBoostClassifier(\n", + " verbose=0,\n", + " n_estimators=320,\n", + " max_depth=4\n", + " )\n", + "}\n", + "\n", + "lr_accuracy = []\n", + "lr_f1 = []\n", + "all_results = {}\n", + "\n", + "for name in sklearn_models:\n", + " all_results[name] = {'accuracy': [], 'precision': [], 'recall': [], 'f1': []}\n", + "\n", + "for fold_idx, (train_index, test_index) in enumerate(skf.split(X, y)):\n", + " print(f\"\\nFold {fold_idx + 1}/{n_splits}\")\n", + "\n", + " # 1. Split data\n", + " X_train, X_test = X.iloc[train_index], X.iloc[test_index]\n", + " y_train, y_test = y.iloc[train_index], y.iloc[test_index]\n", + "\n", + " # 2. Train & Validate sklearn models\n", + " for model_name, model in sklearn_models.items():\n", + " print(f\"Training {model_name}...\")\n", + " model.fit(X_train, y_train) # train\n", + " y_pred = model.predict(X_test) # validate\n", + "\n", + " # 3. Save metrics for that model in this fold\n", + " accuracy = accuracy_score(y_test, y_pred)\n", + " precision = precision_score(y_test, y_pred, zero_division=0)\n", + " recall = recall_score(y_test, y_pred, zero_division=0)\n", + " f1 = f1_score(y_test, y_pred, zero_division=0)\n", + "\n", + " all_results[model_name]['accuracy'].append(accuracy)\n", + " all_results[model_name]['precision'].append(precision)\n", + " all_results[model_name]['recall'].append(recall)\n", + " all_results[model_name]['f1'].append(f1)\n", + "" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "for model_name in all_results:\n", + " print(f\"\\n{model_name}:\")\n", + " print(f\" Accuracy: {np.mean(all_results[model_name]['accuracy']):.4f}\")\n", + " print(f\" Precision: {np.mean(all_results[model_name]['precision']):.4f}\")\n", + " print(f\" Recall: {np.mean(all_results[model_name]['recall']):.4f}\")\n", + " print(f\" F1-Score: {np.mean(all_results[model_name]['f1']):.4f}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "#Top 10\n", + "importances = {}\n", + "importances['CatBoost'] = sklearn_models['CatBoost'].feature_importances_\n", + "\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", + " plt.barh(features[sorted_idx[-10:]], imp[sorted_idx[-10:]])\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(\"The Golden Feature is : \",features[sorted_idx[-1]])" + ], + "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/142/Q1.ipynb b/submissions_extracted/142/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..3c11bcdb863a2cfb94fdc85f7f512858ee530e76 --- /dev/null +++ b/submissions_extracted/142/Q1.ipynb @@ -0,0 +1,319 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q1-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import numpy as np\n", + "import pandas as pd\n", + "import matplotlib.pyplot as plt\n", + "import os\n", + "import kagglehub\n", + "\n", + "from sklearn.model_selection import train_test_split, StratifiedKFold, cross_val_score\n", + "from sklearn.preprocessing import StandardScaler, LabelEncoder, OneHotEncoder\n", + "from sklearn.metrics import classification_report, confusion_matrix, accuracy_score\n", + "import matplotlib.pyplot as plt\n", + "from sklearn.linear_model import LinearRegression" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "# Loading the data into the dataframe df_delivery\n", + "delivery_path = os.path.join(path, 'Q1_data.csv')\n", + "df_delivery = pd.read_csv(delivery_path)\n", + "df_delivery" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "df_delivery.head() # Showing the first 5 samples" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "df_delivery.info()\n", + "# I noticed there are some null rows in some cols and some categorial cols" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "df_delivery.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "plt.figure(figsize=(10, 5))\n", + "plt.hist(df_delivery['Delivery_Time'].dropna(), bins=70, edgecolor='black')\n", + "plt.title('delivery time Distribution')\n", + "plt.xlabel('delivery time')\n", + "plt.ylabel('Frequency')\n", + "plt.show()\n", + "# Notice how the graph is a bit skewed to the right and it has a mean of approx. 56" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "df_delivery = df_delivery.drop(columns=['Order_ID'])\n", + "df_delivery.columns" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "# let's take a look by using isnull.sum\n", + "print(df_delivery.isnull().sum())\n", + "# weather trafficlevel timeofday courier and delivery time has some missing data\n", + "df_delivery.info()\n", + "# first let's fix the weather, traffic level and time of day col by filling the null rows with the most frequent in data (mode)\n", + "\n", + "df_delivery['Weather'] = df_delivery['Weather'].fillna(df_delivery['Weather'].mode()[0])\n", + "df_delivery['Traffic_Level'] = df_delivery['Traffic_Level'].fillna(df_delivery['Traffic_Level'].mode()[0])\n", + "df_delivery['Time_of_Day'] = df_delivery['Time_of_Day'].fillna(df_delivery['Time_of_Day'].mode()[0])\n", + "\n", + "# fix the courier exp years by filling the mode also since the data has integer number of years\n", + "df_delivery['Courier_Experience_yrs'] = df_delivery['Courier_Experience_yrs'].fillna(df_delivery['Courier_Experience_yrs'].mode()[0])\n", + "\n", + "# finally with the deliv time we must drop them since we cannot predict without them\n", + "df_delivery = df_delivery.dropna(subset=['Delivery_Time'])\n", + "\n", + "\n", + "print(df_delivery.isnull().sum())\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "duplicate_rows = df_delivery.duplicated().sum()\n", + "if duplicate_rows > 0:\n", + " print(f\"Found {duplicate_rows} duplicate rows. Removing them...\")\n", + " df_delivery.drop_duplicates(inplace=True)\n", + " print(\"Duplicate rows removed.\")\n", + "else:\n", + " print(\"No duplicate rows found.\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "\n", + "categorical_cols = df_delivery.select_dtypes(include=[\"object\"]).columns # Check and select our categorical cols\n", + "print(categorical_cols)\n", + "\n", + "le = LabelEncoder()\n", + "print(\"Applying Label encoder Encoding\")\n", + "for i in categorical_cols:\n", + " df_delivery[i] = le.fit_transform(df_delivery[i])\n", + "\n", + "df_delivery.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "# We shouldn't do this now to avoid data leakage but since u asked...\n", + "all_cols = df_delivery.columns.drop(\"Delivery_Time\")\n", + "\n", + "# scale the features\n", + "scaler = StandardScaler()\n", + "df_delivery[all_cols] = scaler.fit_transform(df_delivery[all_cols])\n", + "df_delivery.head()\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 6: Write your code here:\n", + "# Target imbalance ? this is a linear regression problem and the target doesn't classes here" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "X = df_delivery[all_cols]\n", + "y = df_delivery['Delivery_Time']\n", + "X.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "y.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:\n", + "from sklearn.ensemble import RandomForestRegressor\n", + "from sklearn.model_selection import KFold\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", + "\n", + "\n", + "kfold = KFold(n_splits=5, shuffle=True, random_state=42)\n", + "\n", + "mae_scores = []\n", + "rmse_scores = []\n", + "ypred = []\n", + "ytest = []\n", + "for fold, (train_idx, test_idx) in enumerate(kfold.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", + " model.fit(X_train, y_train)\n", + " y_fold_pred = model.predict(X_test)\n", + " ytest.append(y_test)\n", + " ypred.append(y_fold_pred)\n", + " # Calculate metrics\n", + " mae_scores.append(mean_absolute_error(y_test, y_fold_pred))\n", + " rmse_scores.append(np.sqrt(mean_squared_error(y_test, y_fold_pred)))\n", + " print(\"-\" * 30)\n", + "\n", + "\n", + "mae_scores = np.array(mae_scores)\n", + "rmse_scores = np.array(rmse_scores)\n", + "\n", + "print(f\"5-Fold CV Results:\")\n", + "print(f\"MAE: ${mae_scores.mean():,.2f}\")\n", + "print(f\"RMSE: ${rmse_scores.mean():,.2f}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "feature_importance = pd.DataFrame({\n", + " 'feature': X.columns,\n", + " 'importance': model.feature_importances_\n", + "}).sort_values('importance', ascending=False)\n", + "\n", + "plt.figure(figsize=(10, 6))\n", + "plt.barh(feature_importance['feature'], feature_importance['importance'])\n", + "plt.xlabel('Importance')\n", + "plt.title('Feature Importance')\n", + "plt.gca().invert_yaxis()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "plt.figure(figsize=(6, 4))\n", + "plt.scatter(ytest, ypred, alpha=0.7)\n", + "plt.plot([min(y_test), max(y_test)], [min(y_test), max(y_test)], 'r--', linewidth=2)\n", + "plt.xlabel(\"Actual y_test (Ground Truth)\")\n", + "plt.ylabel(\"Predicted y_pred (Linear Regression)\")\n", + "plt.title(\"Linear Regression: Predictions vs. Ground Truth\")\n", + "plt.grid(True)\n", + "\n", + "plt.tight_layout()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/142/Q2.ipynb b/submissions_extracted/142/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..eba2e80cf2fd50e4c819eaf84c05ef1d6eb9a3eb --- /dev/null +++ b/submissions_extracted/142/Q2.ipynb @@ -0,0 +1,386 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q2-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import os\n", + "import pandas as pd\n", + "import numpy as np\n", + "from PIL import Image\n", + "from sklearn.model_selection import train_test_split\n", + "\n", + "# Load Labels\n", + "labels_df = pd.read_csv(os.path.join(path, \"labels.csv\"))\n", + "img_dir = os.path.join(path, \"images\")\n", + "\n", + "images = []\n", + "ages = []\n", + "\n", + "# Load Images and Resize\n", + "print(\"Loading images...\")\n", + "for index, row in labels_df.iterrows():\n", + " img_name = row.iloc[0]\n", + " age = row.iloc[1]\n", + " img_path = os.path.join(img_dir, img_name)\n", + "\n", + " if os.path.exists(img_path):\n", + " img = Image.open(img_path).convert('RGB')\n", + " img_array = np.array(img) / 255.0 # Normalize pixel values to [0, 1]\n", + " images.append(img_array)\n", + " ages.append(age)\n", + "\n", + "X = np.array(images)\n", + "y = np.array(ages)\n", + "\n", + "# Transpose image dimensions to match PyTorch format (N, C, H, W)\n", + "X = np.transpose(X, (0, 3, 1, 2))\n", + "\n", + "# Split Data\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n", + "\n", + "print(f\"X_train shape: {X_train.shape}\")\n", + "print(f\"X_test shape: {X_test.shape}\")\n", + "print(f\"y_train shape: {y_train.shape}\")\n", + "print(f\"y_test shape: {y_test.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 1. Convert Numpy arrays to PyTorch Tensors\n", + "from torch.utils.data import TensorDataset\n", + "from torch.utils.data import DataLoader\n", + "import torch\n", + "\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", + "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", + "first_sample, _ = train_dataset[0]\n", + "print(f\"Shape of one sample: {first_sample.shape}\")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 5. Display sample images\n", + "import matplotlib.pyplot as plt\n", + "images, labels = next(iter(train_loader))\n", + "\n", + "# Display the first 6 images in the batch\n", + "plt.figure(figsize=(8, 4))\n", + "\n", + "for i in range(6):\n", + " plt.subplot(2, 3, i + 1)\n", + "\n", + " # Convert from (C, H, W) to (H, W, C) for matplotlib\n", + " img = images[i].permute(1, 2, 0)\n", + "\n", + " plt.imshow(img)\n", + " plt.title(f\"Label: {labels[i].item()}\")\n", + " plt.axis('off')\n", + "\n", + "plt.tight_layout()\n", + "plt.show()\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your model class here:\n", + "import torch.nn 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", + " # 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", + " # 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", + "\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(): # 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", + " # Binary predictions\n", + " predicted = (outputs > 0.5).float()\n", + "\n", + " # Accuracy calculation\n", + " correct += (predicted == y_batch).sum().item()\n", + " total += y_batch.size(0)\n", + "\n", + " avg_loss = running_loss / len(test_loader)\n", + " accuracy = correct / total\n", + "\n", + " return avg_loss, accuracy\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Define device, model, loss, optimizer:\n", + "from torch.optim import AdamW\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 = 20 # Design choice\n", + "output_dim = 1\n", + "\n", + "# Instantiate model\n", + "model = NN4Layer(input_dim, hidden_dim, output_dim).to(device)\n", + "\n", + "# Print the model architecture\n", + "print(\"Model Architecture:\\n\")\n", + "print(model)\n", + "\n", + "# Calculate the total number of trainable parameters\n", + "total_params = sum(p.numel() for p in model.parameters() if p.requires_grad)\n", + "print(f\"\\nTotal trainable parameters: {total_params}\")\n", + "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", + "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/142/Q3.ipynb b/submissions_extracted/142/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..6dee48abf38a571ada73bb4c258d6df68adf973e --- /dev/null +++ b/submissions_extracted/142/Q3.ipynb @@ -0,0 +1,194 @@ +{ + "cells": [ + { + "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", + "import torch\n", + "import torch.nn as nn\n", + "from torch.optim import Adam\n", + "from torch.utils.data import DataLoader\n", + "from torchvision.datasets import MNIST\n", + "from torchvision.transforms import ToTensor, Compose, Normalize\n", + "\n", + "from sklearn.decomposition import PCA\n", + "from sklearn.manifold import TSNE\n", + "from sklearn.cluster import KMeans\n", + "\n", + "import matplotlib.pyplot as plt\n", + "import numpy as np\n", + "from collections import Counter\n", + "import os\n", + "import pandas as pd\n", + "\n", + "\n", + "ano_path = os.path.join(path, 'Q3_data.csv')\n", + "df = pd.read_csv(ano_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", + "#drop cols that has more than quarter of entries null\n", + "print((df.isnull().sum()>(20001/ 4)))\n", + "max_null = df[df.isnull().sum()>(20001/ 4)]\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "duplicate_rows = df.duplicated().sum()\n", + "if duplicate_rows > 0:\n", + " print(f\"Found {duplicate_rows} duplicate rows. Removing them...\")\n", + " df.drop_duplicates(inplace=True)\n", + " print(\"Duplicate rows removed.\")\n", + "else:\n", + " print(\"No duplicate rows found.\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:" + ], + "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/143/Q1.ipynb b/submissions_extracted/143/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..6a6b4844a152dbfff781627ef434e6522ce3b959 --- /dev/null +++ b/submissions_extracted/143/Q1.ipynb @@ -0,0 +1,287 @@ +{ + "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", + "from sklearn.ensemble import RandomForestRegressor\n", + "from sklearn.preprocessing import LabelEncoder,StandardScaler\n", + "from sklearn.model_selection import KFold\n", + "from sklearn.metrics import mean_squared_error as sklearn_mse, mean_absolute_error, r2_score\n", + "%matplotlib inline" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\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", + "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", + "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", + "df.head(1)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "def check_missing_values(df):\n", + " missing_values = df.isnull().sum()\n", + " print(\"Missing Values per Column:\")\n", + " print(missing_values[missing_values > 0])\n", + " if missing_values.any():\n", + " print(\"\\nHandle Missing Values as needed.\")\n", + " else:\n", + " print(\"\\nNo Missing Values Found.\")\n", + "\n", + "check_missing_values(df)\n", + "#with weather I will use the mode or most repeated value\n", + "df['Weather'] = df['Weather'].fillna(df['Weather'].mode()[0])\n", + "#Same logic with Traffic Level, Time of day since they are labels:\n", + "df['Traffic_Level'] = df['Traffic_Level'].fillna(df['Traffic_Level'].mode()[0])\n", + "df['Time_of_Day'] = df['Time_of_Day'].fillna(df['Time_of_Day'].mode()[0])\n", + "#with delevery time and experience yrs i will take the average since they are numbers:\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" + ], + "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", + "le = LabelEncoder()\n", + "for col in categorical_cols:\n", + " df[col] = le.fit_transform(df[col])\n", + "df.head()" + ], + "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", + "\n", + "# scale the `numerical_cols`\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", + "#Answer: this is not needed we are not making classification" + ], + "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_splits = 5 # K=5 Folds\n", + "model = RandomForestRegressor(n_estimators=200)\n", + "# 5-Fold Cross-Validation, shuffled\n", + "kf = KFold(n_splits=n_splits, shuffle=True, random_state=42)\n", + "lr_mae = []\n", + "\n", + "for fold_idx, (train_index, test_index) in enumerate(kf.split(X)): #the .split() function returns the idex of the test and train\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", + " # Validate\n", + " y_pred = model.predict(X_test)\n", + "\n", + " # Calculate evaluation metrics\n", + " mae = mean_absolute_error(y_test,y_pred)\n", + "\n", + " # Store results\n", + " lr_mae.append(mae)\n", + "print(\"The mean MAE across the folds:\",np.mean(lr_mae))" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "coeffs = model.coef_\n", + "print(coeffs)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "plt.hist(y_pred, bins = 30, color = 'red', edgecolor = 'black')\n", + "plt.grid(True)\n", + "plt.xlabel(\"Predicted Delivery Time\")\n", + "plt.ylabel(\"Frequency of predicted Delievery Time\")\n", + "plt.title(\"Distribution of Predicted Delivery Time\")\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/143/Q2.ipynb b/submissions_extracted/143/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..c696a6bd0fd9922e043006adae0d29c258745d1e --- /dev/null +++ b/submissions_extracted/143/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 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" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import os\n", + "import pandas as pd\n", + "import numpy as np\n", + "from PIL import Image\n", + "from sklearn.model_selection import train_test_split\n", + "\n", + "# Load Labels\n", + "labels_df = pd.read_csv(os.path.join(path, \"labels.csv\"))\n", + "img_dir = os.path.join(path, \"images\")\n", + "\n", + "images = []\n", + "ages = []\n", + "\n", + "# Load Images and Resize\n", + "print(\"Loading images...\")\n", + "for index, row in labels_df.iterrows():\n", + " img_name = row.iloc[0]\n", + " age = row.iloc[1]\n", + " img_path = os.path.join(img_dir, img_name)\n", + "\n", + " if os.path.exists(img_path):\n", + " img = Image.open(img_path).convert('RGB')\n", + " img_array = np.array(img) / 255.0 # Normalize pixel values to [0, 1]\n", + " images.append(img_array)\n", + " ages.append(age)\n", + "\n", + "X = np.array(images)\n", + "y = np.array(ages)\n", + "\n", + "# Transpose image dimensions to match PyTorch format (N, C, H, W)\n", + "X = np.transpose(X, (0, 3, 1, 2))\n", + "\n", + "# Split Data\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n", + "\n", + "print(f\"X_train shape: {X_train.shape}\")\n", + "print(f\"X_test shape: {X_test.shape}\")\n", + "print(f\"y_train shape: {y_train.shape}\")\n", + "print(f\"y_test shape: {y_test.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 1. Convert Numpy arrays to PyTorch Tensors\n", + "X_train = torch.tensor(X_train, dtype=torch.float32)\n", + "X_test = torch.tensor(X_test, dtype=torch.float32)\n", + "y_train = torch.tensor(y_train, dtype=torch.float32)\n", + "y_test = torch.tensor(y_test, dtype=torch.float32)\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" + ], + "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", + "# DataLoader for test/validation data\n", + "test_loader = DataLoader(\n", + " test_dataset,\n", + " batch_size=32,\n", + " shuffle=False, #((Only shuffle the train not the test))\n", + " num_workers=2\n", + ")\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 4. Print shape of one batch\n", + "X_batch, y_batch = next(iter(train_loader))\n", + "print(f\"Training batch input shape: {X_batch.shape}\")\n", + "print(f\"Training batch labels shape: {y_batch.shape}\")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 5. Display sample images\n", + "import matplotlib.pyplot as plt\n", + "images, labels = next(iter(train_loader))\n", + "\n", + "# 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].squeez())\n", + " plt.title(f\"Label: {labels[i].item()}\")\n", + " plt.axis('off')\n", + "\n", + "plt.tight_layout()\n", + "plt.show()\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import torch\n", + "import torch.nn as nn\n", + "from torchvision.datasets import MNIST\n", + "from torch.utils.data import DataLoader\n", + "from torch.optim import Adam\n", + "from torchvision.transforms.functional import to_tensor\n", + "import torch.nn.functional as F" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your model class here:\n", + "input_dim = 3*36*36\n", + "hidden_dim = 256\n", + "output_dim = 1\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", + " # 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", + " # 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", + " self.softmax = nn.Softmax()\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", + " #Fourth Layer\n", + " z4 = self.layer4(a3)\n", + " a4 = self.softmax(z4)\n", + "\n", + " # Output layer\n", + " output = a4\n", + "\n", + " return output\n", + "print(input_dim)" + ], + "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": [ + "from torch.optim import AdamW\n", + "learning_rate = 0.001\n", + "num_epochs = 20\n", + "# Task 4: Define device, model, loss, optimizer:\n", + "device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\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", + "# Run Training\n", + "train_losses = []\n", + "val_losses = []\n", + "val_accuracies = []\n", + "\n", + "print('Starting Training...')\n", + "for epoch in range(num_epochs):\n", + " # Train one epoch\n", + " train_loss = train_one_epoch(model, optimizer, criterion, train_loader, device)\n", + "\n", + " # Validate\n", + " val_loss, val_accuracy = validate(model, criterion, test_loader, device)\n", + "\n", + " train_losses.append(train_loss)\n", + " val_losses.append(val_loss)\n", + " val_accuracies.append(val_accuracy)\n", + "\n", + " print(f'Epoch [{epoch+1}/{num_epochs}], Train Loss: {train_loss:.4f}, Val Loss: {val_loss:.4f}, Val Accuracy: {val_accuracy:.4f}')\n", + "\n", + "print('Training Complete!')" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "plt.figure(figsize=(7, 5))\n", + "\n", + "plt.plot(train_losses, label='Train Loss')\n", + "plt.plot(val_losses, label='Validation Loss')\n", + "plt.title('Loss over Epochs')\n", + "plt.xlabel('Epoch')\n", + "plt.ylabel('Loss')\n", + "plt.legend()\n", + "\n", + "plt.tight_layout()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2 (Bonus): Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/143/Q3.ipynb b/submissions_extracted/143/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..4f4df3e358ec8f5976a1723e5730b2550e44d5fa --- /dev/null +++ b/submissions_extracted/143/Q3.ipynb @@ -0,0 +1,312 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "from torchvision.datasets import CIFAR10\n", + "from torchvision.transforms.functional import to_tensor\n", + "from torch.utils.data import DataLoader\n", + "import matplotlib.pyplot as plt\n", + "import torch.nn as nn\n", + "import torch.nn.functional as F\n", + "import torch\n", + "from torch.optim import AdamW\n", + "import pandas as pd\n", + "import numpy as np\n", + "import matplotlib.pyplot as plt\n", + "import seaborn as sns\n", + "import kagglehub\n", + "import os\n", + "from tqdm import tqdm\n", + "from sklearn.preprocessing import LabelEncoder,StandardScaler\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "\n", + "\n", + "# Download latest version\n", + "\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q3-exam-data\")\n", + "\n", + "\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "csv_path = os.path.join(path, \"Q3_data.csv\")\n", + "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", + "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", + "print(\"total misisng values\", df.isnull().sum().sum())\n", + "#fill missing values with the mean\n", + "for col in df.columns:\n", + " df[col] = df[col].fillna(df[col].mean())\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", + "print(categorical_cols)\n", + "#no need" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "numerical_cols = df.select_dtypes(include=[\"number\"]).columns.drop(\"Target\")\n", + "\n", + "scaler = StandardScaler()\n", + "\n", + "# scale the `numerical_cols`\n", + "df[numerical_cols] = scaler.fit_transform(df[numerical_cols])\n", + "\n", + "df.head()\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "percent_of_one = len(df[(df['Target'] == 1)])/len(df['Target'])\n", + "print(f\"percent of Target that equals 1: {percent_of_one*100:.2f}%\")\n", + "#Target = 1 is the minority class" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "from IPython.display import clear_output\n", + "\n", + "%pip install kagglehub catboost xgboost tqdm imbalanced-learn -q\n", + "\n", + "clear_output()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 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, f1_score\n", + "from catboost import CatBoostClassifier\n", + "F1 = []\n", + "acc = []\n", + "n_splits = 3 # K=3 Folds\n", + "model = CatBoostClassifier(\n", + " verbose=0,\n", + " n_estimators=200,\n", + " max_depth=4\n", + " )\n", + "skf = StratifiedKFold(n_splits=n_splits, shuffle=True, random_state=42)\n", + "sr_results = {'loss': [], 'acc': [], 'f1': []}\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", + " model.fit(X_train, y_train)\n", + "\n", + " # Calculate z & class probabilities for X_test\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", + " acc.append(accuracy)\n", + " F1.append(f1)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "importances = {}\n", + "\n", + "importances['CatBoost'] = model.feature_importances_\n", + "fig, axes = plt.subplots(1, 3, figsize=(18, 6))\n", + "axes = axes.flatten()\n", + "features = X.columns\n", + "\n", + "for i, (model_name, imp) in enumerate(importances.items()):\n", + " # Sort features by importance for a cleaner plot\n", + " sorted_idx = np.argsort(imp)\n", + "\n", + " ax = axes[i]\n", + " ax.barh(features[sorted_idx], imp[sorted_idx])\n", + " ax.set_title(f\"{model_name} Feature Importance\")\n", + " ax.set_xlabel(\"Importance Score\")\n", + "\n", + "plt.tight_layout()\n", + "plt.show()\n", + "# Create a 1x3 plot\n", + "sorted_idx = np.argsort(importances['CatBoost'][:5])\n", + "features = X.columns\n", + "\n", + "plt.tight_layout()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "sort_idx = np.argsort(model.feature_importances_)\n", + "print(features[sort_idx][:5])\n", + "plt.barh(features[sort_idx][:8],model.feature_importances_[:8])" + ], + "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/144/Q1.ipynb b/submissions_extracted/144/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..04c2814fd6a47788b7ccda4759d6022fdb475123 --- /dev/null +++ b/submissions_extracted/144/Q1.ipynb @@ -0,0 +1,223 @@ +{ + "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": [ + "# 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", + "# Check data types and structure\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", + "# delivery_time distribution (target variable)\n", + "plt.figure(figsize=(10, 5))\n", + "plt.hist(df_food['Delivery_Time'].dropna(), bins=20, edgecolor='black')\n", + "plt.title('delivery_time Distribution')\n", + "plt.xlabel('delivery_time')\n", + "plt.ylabel('Frequency')\n", + "plt.show()\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "df_food.drop(columns=['Order_ID'])" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "\n", + "df_clean = df_food.copy()\n", + "\n", + "\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", + "df_clean.shape\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "\n", + "duplicates = df_clean.duplicated().sum()\n", + "print(f\"Number of Duplicate Samples: {duplicates}\")\n", + "if duplicates > 0:\n", + " print(\"Dropping Duplicates...\")\n", + " df_clean.drop_duplicates(inplace=True)\n", + " print(\"Duplicates Dropped.\")\n", + "else:\n", + " print(\"No Duplicate Samples Found.\")\n", + "\n", + "df_clean.shape\n" + ], + "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()" + ], + "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/144/Q2.ipynb b/submissions_extracted/144/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..c8937ff34d658b6340ef5c82e1d71e84083e0ea8 --- /dev/null +++ b/submissions_extracted/144/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/144/Q3.ipynb b/submissions_extracted/144/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..47ad5b01c866d4b9e4ec4cbd69b7167d463abc1a --- /dev/null +++ b/submissions_extracted/144/Q3.ipynb @@ -0,0 +1,203 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "import pandas as pd\n", + "import numpy as np\n", + "import matplotlib.pyplot as plt\n", + "import seaborn as sns\n", + "import kagglehub\n", + "import os\n", + "from tqdm import tqdm\n", + "%matplotlib inline\n", + "# Download latest version\n", + "\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q3-exam-data\")\n", + "\n", + "\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "csv_path = os.path.join(path, \"Q3_data.csv\")\n", + "\n", + "df = pd.read_csv(csv_path)\n", + "\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", + "\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 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", + "from sklearn.preprocessing import LabelEncoder\n", + "le = LabelEncoder()\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/145/Q1.ipynb b/submissions_extracted/145/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..60e32cd45eec69659c107f16d47e73db45408f50 --- /dev/null +++ b/submissions_extracted/145/Q1.ipynb @@ -0,0 +1,241 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import pandas as pd\n", + "import os\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: Write your code here:\n", + "#Read the dataset\n", + "data_path = os.path.join(path, 'Q1_data.csv')\n", + "df_data = pd.read_csv(data_path)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "#head()\n", + "df_data.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "#Display dataset\n", + "df_data.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "df_data.describe()\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "#Plot the target distribution\n", + "plt.figure(figsize=(10, 5))\n", + "plt.hist(df_data['Delivery_Time'].dropna(), bins=50, edgecolor='black')\n", + "plt.title('Target Distribution')\n", + "plt.xlabel('Time')\n", + "plt.ylabel('Frequency')\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "print(\"Before dropping:\\n\", df_data)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "#Drop the 'Order_ID'\n", + "df_clean = df_data.copy()\n", + "df_clean=df_data.drop(columns=['Order_ID'])\n", + "print(\"After dropping:\\n\" ,df_clean)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "# missing values\n", + "missing_values = df_clean.isnull().sum()\n", + "print(\"Missing values:\\n\" ,missing_values)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "#Encode categorical variables\n", + "duplicates=df_clean.drop_duplicates(inplace=True)\n", + "duplicates" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "# scaling\n", + "from sklearn.preprocessing import LabelEncoder\n", + "categorical_cols = df_clean.select_dtypes(include=[\"object\"]).columns\n", + "for col in categorical_cols:\n", + " print(f\"Encoding column: {col}\")\n", + " le = LabelEncoder()\n", + " df_clean[col] = le.fit_transform(df_clean[col])\n", + "df_clean" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "from sklearn.preprocessing import StandardScaler\n", + "data_for_scale=df_clean.copy()\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 6: Write your code here:\n", + "#Check for target imbalance\n", + "import seaborn as sns\n", + "def check_target_imbalance(df_data, target_column):\n", + " print(\"Target Distribution:\")\n", + " print(df_data[target_column].value_counts(normalize=True))\n", + " sns.countplot(x=df_data[target_column])\n", + " plt.title(\"Target Distribution\")\n", + " plt.show()\n", + "\n", + "check_target_imbalance(df_data, \"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:" + ], + "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/145/Q2.ipynb b/submissions_extracted/145/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..c8937ff34d658b6340ef5c82e1d71e84083e0ea8 --- /dev/null +++ b/submissions_extracted/145/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/145/Q3.ipynb b/submissions_extracted/145/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..b4bbe7267798a6249b1e8c3260853945e80cbe31 --- /dev/null +++ b/submissions_extracted/145/Q3.ipynb @@ -0,0 +1,234 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import pandas as pd\n", + "import os\n", + "import matplotlib.pyplot as plt" + ], + "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", + "#Read the dataset\n", + "data_path = os.path.join(path, 'Q3_data.csv')\n", + "df_data = pd.read_csv(data_path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "df_data.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "#Display dataset\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", + "#Handle missing values\n", + "missing_values = df_data.isnull().sum()\n", + "print(\"Missing values:\\n\" ,missing_values)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "#Check and remove duplicates\n", + "df_data.duplicated()\n", + "duplicates = df_data.drop_duplicates(inplace=True)\n", + "print(duplicates)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "#Encode categorical variables\n", + "from sklearn.preprocessing import LabelEncoder\n", + "categorical_cols = df_data.select_dtypes(include=[\"object\"]).columns\n", + "for col in categorical_cols:\n", + " print(f\"Encoding column: {col}\")\n", + " le = LabelEncoder()\n", + " df_data[col] = le.fit_transform(df_data[col])\n", + "df_data" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "#scaling\n", + "from sklearn.preprocessing import StandardScaler\n", + "data_for_scale=df_data.copy()\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 5: Write your code here:\n", + "#Check for target imbalance\n", + "import seaborn as sns\n", + "def check_target_imbalance(df_data, target_column):\n", + " print(\"Target Distribution:\")\n", + " print(df_data[target_column].value_counts(normalize=True))\n", + " sns.countplot(x=df_data[target_column])\n", + " plt.title(\"Target Distribution\")\n", + " plt.show()\n", + "\n", + "check_target_imbalance(df_data, \"Target\")" + ], + "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_s = df_data.drop(\"target\", axis=1).astype(float)\n", + "y_s = df_data[\"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 KFold\n", + "\n", + "\n", + "X, y = X_s.copy(), y_s.copy()\n", + "\n", + "# 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 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/146/Q1.ipynb b/submissions_extracted/146/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..e6da5cd5e820b1e28c6cd3b22273be35676d5949 --- /dev/null +++ b/submissions_extracted/146/Q1.ipynb @@ -0,0 +1,260 @@ +{ + "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.preprocessing import StandardScaler\n", + "from sklearn.preprocessing import OneHotEncoder\n", + "from sklearn.model_selection import train_test_split, StratifiedKFold, cross_val_score\n", + "from sklearn.preprocessing import StandardScaler, LabelEncoder\n", + "from sklearn.ensemble import RandomForestClassifier\n", + "from sklearn.metrics import classification_report, confusion_matrix, accuracy_score\n", + "\n", + "import warnings\n", + "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", + "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", + "print(f\"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", + "#delivery_time\n", + "plt.figure(figsize=(10, 5))\n", + "plt.hist(df_delivery['Delivery_Time'].dropna(), bins=50, edgecolor='black')\n", + "plt.title('Delivery time Distribution')\n", + "plt.xlabel('delivery')\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" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "def check_missing_values(df):\n", + " missing_values = df.isnull().sum()\n", + " print(\"Missing Values per Column:\")\n", + " print(missing_values[missing_values > 0])\n", + " if missing_values.any():\n", + " print(\"\\nHandle Missing Values as needed.\")\n", + " else:\n", + " print(\"\\nNo Missing Values Found.\")\n", + "check_missing_values(df_delivery)\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", + "check_duplicates(df_delivery)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "#Apply feature scaling for all features (Use StandardScaler)\n", + "\n", + "categorical_cols =(df_delivery)\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", + "# 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", + " plt.title(\"Target Distribution\")\n", + " plt.show()\n", + "check_target_imbalance(df_delivery, \"delivery_time\")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 6: Write your code here:\n", + "def check_target_imbalance(df, target_column):\n", + " print(\"Target Distribution:\")\n", + " print(df[target_column].value_counts(normalize=True))\n", + " plt.title(\"Target Distribution\")\n", + " plt.show()\n", + "check_target_imbalance(df_delivery, \"delivery_time\")" + ], + "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:\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/146/Q2.ipynb b/submissions_extracted/146/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..c8937ff34d658b6340ef5c82e1d71e84083e0ea8 --- /dev/null +++ b/submissions_extracted/146/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/146/Q3.ipynb b/submissions_extracted/146/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..153a8f58c629c435a5688b1c9344c532c5bff03c --- /dev/null +++ b/submissions_extracted/146/Q3.ipynb @@ -0,0 +1,222 @@ +{ + "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.preprocessing import StandardScaler\n", + "from sklearn.preprocessing import OneHotEncoder\n", + "from sklearn.model_selection import train_test_split, StratifiedKFold, cross_val_score\n", + "from sklearn.preprocessing import StandardScaler, LabelEncoder\n", + "from sklearn.ensemble import RandomForestClassifier\n", + "from sklearn.metrics import classification_report, confusion_matrix, accuracy_score\n", + "\n", + "import warnings\n", + "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", + "anony_path = os.path.join(path, 'Q3_data.csv')\n", + "df_anony = pd.read_csv(anony_path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "df_anony.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "df_anony.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "df_anony.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", + " print(\"\\nNo Missing Values Found.\")\n", + "check_missing_values(df_anony)" + ], + "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_anony)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "from sklearn.preprocessing import LabelEncoder\n", + "le = LabelEncoder()\n", + "\n", + "# Encode the target column\n", + "df['Air Quality'] = le.fit_transform(df['Air Quality'])\n", + "\n", + "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:\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/147/Q1.ipynb b/submissions_extracted/147/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..1ab5cc82e148fee47d55bbea71ebe91c04c2c6d7 --- /dev/null +++ b/submissions_extracted/147/Q1.ipynb @@ -0,0 +1,316 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "from IPython.display import clear_output\n", + "\n", + "%pip install kagglehub catboost lightgbm tqdm -q\n", + "\n", + "clear_output()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import pandas as pd\n", + "import numpy as np\n", + "import matplotlib.pyplot as plt\n", + "import seaborn as sns\n", + "import kagglehub\n", + "import os\n", + "from tqdm import tqdm\n", + "from sklearn.preprocessing import StandardScaler, LabelEncoder\n", + "from sklearn.model_selection import StratifiedKFold\n", + "from sklearn.metrics import mean_squared_error as sklearn_mse, mean_absolute_error, r2_score\n", + "\n", + "%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)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "df.head() # Showing the first 5 rows!!" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "df.info() # Showing the characteristics of each feature with also the target y (delivery time)!!" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "df.describe() # Statistics information!!" + ], + "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_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):\n", + "\n", + " # Get missing values using pandas\n", + " missing_values = df_N.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_N)\n", + "# I believe that there are missing values but my code showed inverse!" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "def check_duplicates(df_N):\n", + " duplicates = df_N.duplicated().sum()\n", + " print(f\"Number of Duplicate Samples: {duplicates}\")\n", + " if duplicates > 0:\n", + " print(\"Dropping Duplicates...\")\n", + " df_N.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", + "categorical_cols=df_N.select_dtypes(include=[\"object\"]).columns\n", + "\n", + "print(\"Categorical Columns:\", list(categorical_cols))\n", + "## Error is happening I don't know why\n", + "\n", + "for col in categorical_cols:\n", + " le = LabelEncoder()\n", + " df_N[col] = le.fit_transform(df_N[col].astype(str))\n", + "\n", + "df_N.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "\n", + "# Task 5: Write your code here:\n", + "features = df_N.columns.drop(\"Delivery_Time\").astype(float) #features\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", + "target_column=df[\"Delivery_Time\"]\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_N.drop(\"Delivery_Time\", axis=1).astype(float)\n", + "y = df['Delivery_Time'].astype(float)\n", + "#I will be using stratifiedKFold for ensuring! which is for the imbalanced data" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:\n", + "n_splits = 5 # K=5 Folds\n", + "\n", + "# Stratified 5-Fold Cross-Validation, shuffled\n", + "skf = StratifiedKFold(n_splits=n_splits, shuffle=True, random_state=42)\n", + "\n", + "lr_losses = []\n", + "lr_mse = []\n", + "lr_rmse = []\n", + "lr_r2 = []\n", + "\n", + "for fold_idx, (train_index, test_index) in enumerate(kf.split(X)): # enumerate returns two vals!\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 = mean_absolute_error(y_test, y_pred)\n", + " rmse = np.sqrt(mean_squared_error(y_test, y_pred))\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", + "print(f\"MAE: ${mae:,.2f}\")\n", + "print(f\"RMSE: ${rmse:,.2f}\")\n", + "avg_loss = np.mean(lr_losses, axis=0)\n", + "print(avg_loss)" + ], + "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=(10, 5))\n", + "plt.hist(y_pred.dropna(), bins=50, edgecolor='black')\n", + "plt.title('Delivery Time Distribution')\n", + "plt.xlabel('Delivery Time')\n", + "plt.ylabel('Frequency')\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/147/Q2.ipynb b/submissions_extracted/147/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..e99187582baa7133a70fe19deeb3f33f5be9b606 --- /dev/null +++ b/submissions_extracted/147/Q2.ipynb @@ -0,0 +1,356 @@ +{ + "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.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.values, dtype=torch.float32)\n", + "X_test = torch.tensor(X_test.values, dtype=torch.float32)\n", + "y_train = torch.tensor(y_train.values, dtype=torch.float32)\n", + "y_test = torch.tensor(y_test.values, dtype=torch.float32)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 2. Create TensorDataset objects\n", + "train_dataset = TensorDataset(X_train, y_train)\n", + "test_dataset = TensorDataset(X_test, y_test)\n", + "\n", + "print(\"Train dataset:\", len(train_dataset))\n", + "print(\"Test dataset:\", len(test_dataset))" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 3. Create DataLoaders\n", + "train_loader = DataLoader(train_dataset, batch_size=32, shuffle=True)\n", + "test_loader = DataLoader(test_dataset, batch_size=32, shuffle=False)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 4. Print shape of one batch\n", + "X_batch, y_batch = next(iter(train_loader))\n", + "print(f\"Training batch input shape: {X_batch.shape}\")\n", + "print(f\"Training batch labels shape: {y_batch.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 5. Display sample images\n", + "images, labels = next(iter(train_loader))\n", + "\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", + " def __init__(self, input_dim, hidden_dim):\n", + " super(NN4Layer, self).__init__()\n", + "\n", + " # First linear layer: input features -> hidden layer\n", + " self.layer1 = nn.Linear(input_dim, hidden_dim)\n", + "\n", + " # Second linear layer: hidden layer -> hidden layer\n", + " self.layer2 = nn.Linear(hidden_dim, hidden_dim)\n", + "\n", + " # Third layer: hidden layer -> 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:\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", + "\n", + "num_epochs = 20\n", + "learning_rate = 0.001\n", + "\n", + "criterion = nn.MSELoss() #Regression Problem!\n", + "\n", + "optimizer = AdamW(model.parameters(), learning_rate)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Start training for 20 epochs:\n", + "train_losses = []\n", + "val_losses = []\n", + "\n", + "print('Starting Training...')\n", + "for epoch in range(num_epochs):\n", + " # Train one epoch\n", + " train_loss = train_one_epoch(model, optimizer, criterion, train_loader, device)\n", + "\n", + " # Validate\n", + " val_loss = validate(model, criterion, test_loader, device)\n", + "\n", + " train_losses.append(train_loss)\n", + " val_losses.append(val_loss)\n", + "\n", + " if (epoch + 1) % 5 == 0:\n", + " print(\n", + " f'Epoch [{epoch+1}/{num_epochs}], '\n", + " f'Train Loss: {train_loss:.4f}, '\n", + " f'Val Loss: {val_loss:.4f}'\n", + " )\n", + "\n", + "print('Training Complete!')" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "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/147/Q3.ipynb b/submissions_extracted/147/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..7274a7e2d93778bcffcf80df86c789ad6d3fb61b --- /dev/null +++ b/submissions_extracted/147/Q3.ipynb @@ -0,0 +1,437 @@ +{ + "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 seaborn as sns\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", + "from sklearn.model_selection import StratifiedKFold\n", + "from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score\n", + "\n", + "# Download latest version\n", + "\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q3-exam-data\")\n", + "\n", + "\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "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()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "df.info() #This won't show everything as I think the number of features is high, hence just a summary\n", + "print(\"\\n\\n--------------------------------------\\n\\n\")\n", + "df.info(all, show_counts= all) #This in compare to regular df.info(), shows the dataset information" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "df.describe() # Showing the statistics information" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "def check_missing_values(df):\n", + " missing_values = df.isnull().sum()\n", + " print(\"Missing Values per Column:\")\n", + " print(missing_values[missing_values > 0])\n", + " if missing_values.any():\n", + " print(\"\\nHandle Missing Values as needed.\")\n", + " else:\n", + " print(\"\\nNo Missing Values Found.\")\n", + "\n", + "check_missing_values(df)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "def check_duplicates(df):\n", + " duplicates = df.duplicated().sum()\n", + " print(f\"Number of Duplicate Samples: {duplicates}\")\n", + " if duplicates > 0:\n", + " print(\"Dropping Duplicates...\")\n", + " df.drop_duplicates(inplace=True)\n", + " print(\"Duplicates Dropped.\")\n", + " else:\n", + " print(\"No Duplicate Samples Found.\")\n", + "\n", + "check_duplicates(df)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "categorical_cols = df.select_dtypes(include=[\"object\"]).columns\n", + "for col in categorical_cols:\n", + " print(f\"Encoding column: {col}\")\n", + " le = LabelEncoder()\n", + " df[col] = le.fit_transform(df[col])\n", + "df" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "numerical_cols = df.select_dtypes(include=[\"int64\", \"float64\"]).columns.drop(\"Target\") #Feature Scaling!!\n", + "scaler = StandardScaler()\n", + "df[numerical_cols] = scaler.fit_transform(df[numerical_cols])\n", + "df" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "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", + "#It is inbalanced!!" + ], + "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", + "#We will be using StratifiedKFold as our data is imbalanced!\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", + "#We will list the following metrics eventhough accuarcy and F1 score were asked!\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", + "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", + "train_dataset = TensorDataset(X_train, y_train)\n", + "test_dataset = TensorDataset(X_test, y_test)\n", + "\n", + "# Create Dataloaders to train and test data in batches\n", + "train_loader = DataLoader(train_dataset, batch_size=32, shuffle=True)\n", + "test_loader = DataLoader(test_dataset, batch_size=32, shuffle=False)\n", + "\n", + "# Print dataset sizes\n", + "print(\"Train dataset:\", len(train_dataset))\n", + "print(\"Test dataset:\", len(test_dataset))\n", + "\n", + "# Get the first batch from the training DataLoader\n", + "X_batch, y_batch = next(iter(train_loader))\n", + "print(f\"Training batch input shape: {X_batch.shape}\")\n", + "print(f\"Training batch labels shape: {y_batch.shape}\")\n", + "\n", + "\n", + "\n", + "class NN4Layer(nn.Module):\n", + "\n", + " def __init__(self, input_dim, hidden_dim, output_dim):\n", + " super(NN4Layer, self).__init__()\n", + "\n", + " # First linear layer: input features -> hidden layer\n", + " self.layer1 = nn.Linear(input_dim, hidden_dim)\n", + "\n", + " # Second linear layer: hidden layer -> hidden layer\n", + " self.layer2 = nn.Linear(hidden_dim, hidden_dim)\n", + "\n", + " # 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", + "\n", + "\n", + "#Training Loop\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", + " accuracy = accuracy_score(y_test, y_batch)\n", + " precision = precision_score(y_test, y_batch, zero_division=0)\n", + " recall = recall_score(y_test, y_batch, zero_division=0)\n", + " f1 = f1_score(y_test, y_batch, zero_division=0)\n", + "\n", + "\n", + " lr_accuracy.append(accuracy)\n", + " lr_precision.append(precision)\n", + " lr_recall.append(recall)\n", + " lr_f1.append(f1)\n", + "\n", + " # Average loss over all batches\n", + " avg_loss = running_loss / len(train_loader)\n", + "\n", + " return avg_loss\n", + "\n", + "\n", + "\n", + "#Validiation Loop\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\n", + "\n", + "# Device setup\n", + "device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n", + "\n", + "# Model parameters\n", + "input_dim = X_train.shape[1] # Number of tabular features\n", + "hidden_dim = 14 # Design choice\n", + "output_dim = 189 # P-2:......B:188\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)\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!')\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", + "#Couldn't figure it out as my code is not working :(\n", + "#If the code was working properly then the golden feaure will be shown clearly!" + ], + "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/148/Q1.ipynb b/submissions_extracted/148/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..c661f241328697b7f08ec0d39e9530fe205693ad --- /dev/null +++ b/submissions_extracted/148/Q1.ipynb @@ -0,0 +1,414 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "import os\n", + "import pandas as pd\n", + "import numpy as np\n", + "import matplotlib.pyplot as plt\n", + "import seaborn as sns\n", + "from tqdm import tqdm\n", + "from PIL import Image\n", + "from sklearn.model_selection import train_test_split\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.ylabel(\"\")\n", + " plt.grid(False)\n", + "\n", + " plt.show()\n", + "\n", + "check_target_distribution(df, \"delivery_time\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "df.drop(columns=['Order_ID'])" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "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", + "from sklearn.preprocessing import OneHotEncoder #import OneHotEncoder\n", + "\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\n", + "\n", + "\n", + "#categorical_cols = df.select_dtypes(include=[\"object\"]).columns\n", + "\n", + "#print(\"Categorical Columns:\", list(categorical_cols))" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "from sklearn.preprocessing import StandardScaler #import StandardScaler\n", + "\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:\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", + "\n", + "X = df_clean[feature_cols]\n", + "y = df_clean['delivery_time']\n", + "\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n", + "print(f\"Train: {X_train.shape}, Test: {X_test.shape}\")" + ], + "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", + "#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", + "lr_losses = []\n", + "lr_mse = []\n", + "lr_rmse = []\n", + "lr_r2 = []\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", + "#3\n", + "model = RandomForestRegressor(n_estimators=100, max_depth=20, random_state=42, n_jobs=-1)\n", + "model.fit(X_train_scaled, y_train)\n", + "print(\"Model trained!\")\n", + "\n", + "#4: evaluate\n", + "y_pred = model.predict(X_test_scaled) #data_standard_scaled\n", + "mae = mean_absolute_error(y_test, y_pred)\n", + "print(f\"MAE: ${mae:,.2f}\")\n", + "\n", + "#5\n", + "\n", + "model = {\n", + "\n", + " \"Random Forest Regressor\": RandomForestRegressor(n_estimators=200)\n", + "}\n", + "\n", + "all_results = {}\n", + "\n", + "for name in models:\n", + " all_results[name] = {'mse': [], 'rmse': [], 'r2': []}\n", + "\n", + "for fold_idx, (train_index, test_index) in enumerate(kf.split(X)):\n", + " print(f\"\\nFold {fold_idx + 1}/{n_splits}\")\n", + "\n", + " X_train, X_test = X.iloc[train_index], X.iloc[test_index]\n", + " y_train, y_test = y.iloc[train_index], y.iloc[test_index]\n", + "\n", + "for model_name, model in model.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)\n", + "\n", + "for model_name in all_results:\n", + " print(f\"\\n{model_name}:\")\n", + " print(f\" MSE: {np.mean(all_results[model_name]['mse']):.4f}\")\n", + " print(f\" RMSE: {np.mean(all_results[model_name]['rmse']):.4f}\")\n", + " print(f\" R2: {np.mean(all_results[model_name]['r2']):.4f}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "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", + "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 Delivery time\")\n", + "plt.ylabel(\"Predicted delivery time\")\n", + "plt.title(\"Predicted delivery time\")\n", + "plt.grid(True)\n", + "\n", + "plt.tight_layout()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:\n", + "from sklearn.ensemble import RandomForestRegressor\n", + "from catboost import CatBoostRegressor\n", + "\n", + "models = {\n", + " \"Decision Tree Regressor\": DecisionTreeRegressor(max_depth=10),\n", + " \"CatBoost\": CatBoostRegressor(verbose=0)\n", + "}\n", + "\n", + "# Storage for results\n", + "all_results = {}\n", + "\n", + "for name in models:\n", + " all_results[name] = {'mse': [], 'rmse': [], 'r2': []}\n", + "\n", + "\n", + "kf = KFold(n_splits=5, shuffle=True, random_state=42)\n", + "\n", + "for fold_idx, (train_index, test_index) in enumerate(kf.split(X)):\n", + " print(f\"\\nFold {fold_idx + 1}/{n_splits}\")\n", + "\n", + " X_train, X_test = X.iloc[train_index], X.iloc[test_index]\n", + " y_train, y_test = y.iloc[train_index], y.iloc[test_index]\n", + "\n", + " for model_name, model in models.items():\n", + " print(f\"Training {model_name}...\")\n", + "\n", + " # Train\n", + " model.fit(X_train, y_train)\n", + "\n", + " # Predict\n", + " y_pred = model.predict(X_test)\n", + "\n", + " # Calculate metrics\n", + " mse = sklearn_mse(y_test, y_pred)\n", + " rmse = np.sqrt(mse)\n", + " r2 = r2_score(y_test, y_pred)\n", + "\n", + " # Store results\n", + " all_results[model_name][\"mse\"].append(mse)\n", + " all_results[model_name][\"rmse\"].append(rmse)\n", + " all_results[model_name][\"r2\"].append(r2)\n", + "\n", + " 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/148/Q2.ipynb b/submissions_extracted/148/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..49af0149c1de00d483d6bdd49a303ebc29b09211 --- /dev/null +++ b/submissions_extracted/148/Q2.ipynb @@ -0,0 +1,388 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "import os\n", + "import pandas as pd\n", + "import numpy as np\n", + "import matplotlib.pyplot as plt\n", + "import seaborn as sns\n", + "from tqdm import tqdm\n", + "from PIL import Image\n", + "from sklearn.model_selection import train_test_split\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": [ + "\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", + "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)" + ], + "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", + "\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", + "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": [ + "# Task 1: Write your model class here:\n", + "\n", + "class NN4Layer(nn.Module):\n", + "\n", + " def __init__(self, input_dim, hidden_dim, output_dim):\n", + " super(NN4Layer, self).__init__()\n", + "\n", + " # First linear layer: input features -> hidden layer\n", + " self.layer1 = nn.Linear(input_dim, hidden_dim)\n", + "\n", + " # Second linear layer: hidden layer -> hidden layer\n", + " self.layer2 = nn.Linear(hidden_dim, hidden_dim)\n", + "\n", + " # Third linear layer: hidden layer -> hidden layer\n", + " self.layer3 = nn.Linear(hidden_dim, hidden_dim)\n", + "\n", + " # Output layer: hidden layer -> number of classes (logits)\n", + " self.layer4 = nn.Linear(hidden_dim, output_dim)\n", + "\n", + " # ReLU activation for non-linearity\n", + " self.relu = nn.ReLU()\n", + "\n", + " # Defines how input data flows through the network\n", + " def forward(self, x):\n", + " # First hidden layer\n", + " a1 = self.relu(self.layer1(x))\n", + "\n", + " # Second hidden layer\n", + " a2 = self.relu(self.layer2(a1))\n", + "\n", + " # Third hidden layer\n", + " a3 = self.relu(self.layer3(a2))\n", + "\n", + " # Output layer (raw scores / logits)\n", + " output = self.layer4(a3) # we said we'll use softmax, where is it? ¯\\(ツ)/¯\n", + "\n", + " return output" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your training loop here:\n", + "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", + "# 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:\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", + "plt.xlabel(\"Actual image\")\n", + "plt.ylabel(\"Predicted image\")\n", + "plt.title(\"Linear Regression: Predictions vs Actual\")\n", + "plt.grid(True)\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/148/Q3.ipynb b/submissions_extracted/148/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..5d357ac46bd0f252f9bd2b7944ab6a78293a798c --- /dev/null +++ b/submissions_extracted/148/Q3.ipynb @@ -0,0 +1,291 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "import os\n", + "import pandas as pd\n", + "import numpy as np\n", + "import matplotlib.pyplot as plt\n", + "import seaborn as sns\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", + "csv_path = os.path.join(path, \"Q3_data.csv\")\n", + "\n", + "df = pd.read_csv(csv_path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "df.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "df.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "def check_missing_values(df):\n", + " missing_values = df.isnull().sum()\n", + " print(\"Missing Values per Column:\")\n", + " print(missing_values[missing_values > 0])\n", + " if missing_values.any():\n", + " print(\"\\nHandle Missing Values as needed.\")\n", + " else:\n", + " print(\"\\nNo Missing Values Found.\")\n", + "\n", + "check_missing_values(df)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "def check_duplicates(df):\n", + "\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", + "from sklearn.preprocessing import OneHotEncoder #import OneHotEncoder\n", + "\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 4: Write your code here:\n", + "from sklearn.preprocessing import StandardScaler #import StandardScaler\n", + "standard_scaler = StandardScaler() # Instantiate StandardScaler\n", + "data_standard_scaled = standard_scaler.fit_transform(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", + "\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).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", + "#2,3\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", + "skmodel = {\n", + " \"CatBoost\": CatBoostClassifier(\n", + " verbose=0,\n", + " n_estimators=320,\n", + " max_depth=4)\n", + "}\n", + "\n", + "all_results = {}\n", + "\n", + "for name in skmodel:\n", + " all_results[name] = {'accuracy': [], 'precision': [], 'recall': [], 'f1': []}\n", + "\n", + "n_splits = 5 # K\n", + "skf = StratifiedKFold(n_splits=n_splits, shuffle=True, random_state=42)\n", + "\n", + "for fold_idx, (train_index, test_index) in enumerate(skf.split(X, y)):\n", + " print(f\"\\nFold {fold_idx + 1}/{n_splits}\")\n", + "\n", + " # 1. Split data\n", + " X_train, X_test = X.iloc[train_index], X.iloc[test_index]\n", + " y_train, y_test = y.iloc[train_index], y.iloc[test_index]\n", + "\n", + " # 2. Train & Validate sklearn models\n", + " for model_name, model in skmodel.items():\n", + " print(f\"Training {model_name}...\")\n", + " model.fit(X_train, y_train) # train\n", + " y_pred = model.predict(X_test) # validate\n", + "\n", + " # 3. Save metrics for that model in this fold\n", + " accuracy = accuracy_score(y_test, y_pred)\n", + " precision = precision_score(y_test, y_pred, zero_division=0)\n", + " recall = recall_score(y_test, y_pred, zero_division=0)\n", + " f1 = f1_score(y_test, y_pred, zero_division=0)\n", + "\n", + " all_results[model_name]['accuracy'].append(accuracy)\n", + " all_results[model_name]['precision'].append(precision)\n", + " all_results[model_name]['recall'].append(recall)\n", + " all_results[model_name]['f1'].append(f1)\n", + "\n", + "#4\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", + "importances = {}\n", + "importances['CatBoost'] = model['CatBoost'].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", + "print(f\"the Golden Feature:\" features[sorted_idx[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/149/Q1.ipynb b/submissions_extracted/149/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..bfaa2edf9d3895e595d16fcc7d1b717d21a2c8cc --- /dev/null +++ b/submissions_extracted/149/Q1.ipynb @@ -0,0 +1,270 @@ +{ + "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", + "\n", + "import numpy as np\n", + "\n", + "\n", + "data_path = os.path.join(path, 'Q1_data.csv')\n", + "# print(data_path) # just to make sure if the path is correct\n", + "data = pd.read_csv(data_path)" + ], + "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": [ + "import matplotlib.pyplot as plt\n", + "\n", + "# Price distribution (target variable)\n", + "plt.figure(figsize=(10, 5))\n", + "plt.hist(data['Delivery_Time'].dropna(), bins=50, edgecolor='black')\n", + "plt.title('Delivery Time Distribution')\n", + "\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "clean_data = data.drop(columns=['Order_ID'])\n", + "clean_data.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 2. 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", + " df['Weather'].fillna(df['Weather'].mode()[0])\n", + " df['Traffic_Level'].fillna(df['Traffic_Level'].mode()[0])\n", + " df['Courier_Experience_yrs'].fillna(df['Courier_Experience_yrs'].mode()[0])\n", + " df['Delivery_Time'].fillna(df['Delivery_Time'].mean())\n", + " print(\"handled\")\n", + "\n", + " else:\n", + " print(\"\\nNo Missing Values Found.\")\n", + "\n", + "check_missing_values(clean_data)\n", + "\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(clean_data)\n", + "clean_data.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "\n", + "from sklearn.preprocessing import LabelEncoder\n", + "categorical_cols = ['Weather', 'Traffic_Level', 'Time_of_Day', 'Vehicle_Type']\n", + "\n", + "for col in categorical_cols:\n", + " le = LabelEncoder()\n", + " clean_data[col] = le.fit_transform(clean_data[col].astype(str))\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "from sklearn.preprocessing import StandardScaler #import StandardScaler\n", + "\n", + "print('data before scaling:\\n', clean_data) #show before scaling\n", + "StandardScaler = StandardScaler() # Instantiate StandardScaler\n", + "data_standard_scaled = StandardScaler.fit_transform(clean_data) # Apply fit_transform\n", + "\n", + "print('\\nData after scaling:\\n', clean_data) #show after scaling" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "clean_data.info()\n", + "\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(clean_data, \"Delivery_Time\")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 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 = clean_data[feature_cols]\n", + "y = clean_data['Delivery_Time']" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "from sklearn.model_selection import KFold\n", + "\n", + "kf = KFold(n_splits=5, shuffle=True, random_state=42)\n", + "\n", + "for fold, (train_idx, test_idx) in enumerate(kf.split(X), start=1):\n", + " # indexing for each fold\n", + " X_train, X_test = X.iloc[train_idx], X.iloc[test_idx]\n", + " y_train, y_test = y.iloc[train_idx], y.iloc[test_idx]\n", + " # 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": [ + "# Feature importance\n", + "feature_importance = pd.DataFrame({\n", + " 'feature': feature_cols,\n", + " 'importance': model.feature_importances_\n", + "}).sort_values('importance', ascending=False)\n", + "\n", + "plt.figure(figsize=(10, 6))\n", + "plt.barh(feature_importance['feature'], feature_importance['importance'])\n", + "plt.xlabel('Importance')\n", + "plt.title('Feature Importance')\n", + "plt.gca().invert_yaxis()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/149/Q2.ipynb b/submissions_extracted/149/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..c8b1df08cb5076da3e118ab861b4f6b18a1b2cfc --- /dev/null +++ b/submissions_extracted/149/Q2.ipynb @@ -0,0 +1,340 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q2-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import os\n", + "import pandas as pd\n", + "import numpy as np\n", + "from PIL import Image\n", + "from sklearn.model_selection import train_test_split\n", + "\n", + "# Load Labels\n", + "labels_df = pd.read_csv(os.path.join(path, \"labels.csv\"))\n", + "img_dir = os.path.join(path, \"images\")\n", + "\n", + "images = []\n", + "ages = []\n", + "\n", + "# Load Images and Resize\n", + "print(\"Loading images...\")\n", + "for index, row in labels_df.iterrows():\n", + " img_name = row.iloc[0]\n", + " age = row.iloc[1]\n", + " img_path = os.path.join(img_dir, img_name)\n", + "\n", + " if os.path.exists(img_path):\n", + " img = Image.open(img_path).convert('RGB')\n", + " img_array = np.array(img) / 255.0 # Normalize pixel values to [0, 1]\n", + " images.append(img_array)\n", + " ages.append(age)\n", + "\n", + "X = np.array(images)\n", + "y = np.array(ages)\n", + "\n", + "# Transpose image dimensions to match PyTorch format (N, C, H, W)\n", + "X = np.transpose(X, (0, 3, 1, 2))\n", + "\n", + "# Split Data\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n", + "\n", + "print(f\"X_train shape: {X_train.shape}\")\n", + "print(f\"X_test shape: {X_test.shape}\")\n", + "print(f\"y_train shape: {y_train.shape}\")\n", + "print(f\"y_test shape: {y_test.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import torch\n", + "from torch.utils.data import TensorDataset\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": [ + "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": [ + "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 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": [ + "X_batch, y_batch = next(iter(train_loader))\n", + "print(f\"Training batch input shape: {X_batch.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 5. Display sample images\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import torch\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", + " # 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", + "\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.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": [ + "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": [ + "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 = 36 * 36 # images shape\n", + "hidden_dim = 14 # design choice\n", + "output_dim = 10 # Digits 0–9\n", + "\n", + "model = NN4Layer(input_dim, hidden_dim, output_dim).to(device)\n", + "\n", + "learning_rate = 0.001\n", + "\n", + "criterion = nn.CrossEntropyLoss()\n", + "# Define optimizer\n", + "optimizer = Adam(model.parameters(), learning_rate)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "num_epochs = 20\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": [ + "# i don't know how to use plot LOL ¯\\(ツ)/¯" + ], + "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/149/Q3.ipynb b/submissions_extracted/149/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..2a63170e43e6202154d5c031d48b6ac384a5c24c --- /dev/null +++ b/submissions_extracted/149/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": [ + "import pandas as pd\n", + "\n", + "df = pd.read_csv(path + \"/Q3_data.csv\")\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": [ + "# # 2. 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", + " df.drop(columns=['D_87'])\n", + " df.drop(columns=['D_88'])\n", + " df.drop(columns=['B_39'])\n", + " df.drop(columns=['D_110'])\n", + " df.drop(columns=['D_111'])\n", + " df.drop(columns=['D_108'])\n", + " df.drop(columns=['B_42'])\n", + " df.drop(columns=['D_73'])\n", + " df.drop(columns=['D_136'])\n", + " df.drop(columns=['D_138'])\n", + " df.drop(columns=['D_134'])\n", + " df.drop(columns=['D_137'])\n", + " df.drop(columns=['R_9'])\n", + " df.drop(columns=['B_29'])\n", + " df.drop(columns=['D_106'])\n", + " df.drop(columns=['D_132'])\n", + " df.drop(columns=['D_49'])\n", + " df.drop(columns=['D_66'])\n", + " df.drop(columns=['R_26'])\n", + " df.drop(columns=['D_76'])\n", + " df.drop(columns=['D_142'])\n", + " df.drop(columns=['D_53'])\n", + "\n", + "\n", + " print(\"handled\")\n", + "\n", + " else:\n", + " print(\"\\nNo Missing Values Found.\")\n", + "\n", + "check_missing_values(df)" + ], + "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", + "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])" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "from sklearn.preprocessing import StandardScaler\n", + "\n", + "numerical_cols = df.select_dtypes(include=[\"number\"]).columns.drop(\"Target\")\n", + "\n", + "scaler = StandardScaler()\n", + "\n", + "# TODO: Apply fit_transform to scale the numerical columns\n", + "df[numerical_cols] = scaler.fit_transform(df[numerical_cols])\n", + "\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import matplotlib.pyplot as plt\n", + "\n", + "df.info()\n", + "\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, \"Target\")\n", + "\n", + "# wow a big one LOL" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Define features (X) and target (y)\n", + "feature_cols = df.select_dtypes(include=[\"number\"]).columns.drop(\"Target\")\n", + "X = df[feature_cols]\n", + "y = df['Target']" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "from sklearn.model_selection import KFold\n", + "\n", + "kf = KFold(n_splits=5, shuffle=True, random_state=42)\n", + "\n", + "for fold, (train_idx, test_idx) in enumerate(kf.split(X), start=1):\n", + " # indexing for each fold\n", + " X_train, X_test = X.iloc[train_idx], X.iloc[test_idx]\n", + " y_train, y_test = y.iloc[train_idx], y.iloc[test_idx]\n", + " # 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": [ + "# Feature importance\n", + "feature_importance = pd.DataFrame({\n", + " 'feature': feature_cols,\n", + " 'importance': model.feature_importances_\n", + "}).sort_values('importance', ascending=False)\n", + "\n", + "plt.figure(figsize=(10, 6))\n", + "plt.barh(feature_importance['feature'], feature_importance['importance'])\n", + "plt.xlabel('Importance')\n", + "plt.title('Feature Importance')\n", + "plt.gca().invert_yaxis()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/15/Q1.ipynb b/submissions_extracted/15/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..52c9b00feae9cf961a6b55cd740b9c50f86c876b --- /dev/null +++ b/submissions_extracted/15/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, 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", + "\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", + "print(f\"Dataset shape: {df_delivery.shape}\")\n", + "#df_delivery.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "# here the head() task\n", + "\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 (target variable)\n", + "plt.figure(figsize=(10, 5))\n", + "plt.hist(df_delivery['Delivery_Time'].dropna(), bins=50, edgecolor='black')\n", + "plt.title('Delivery_Time Distribution')\n", + "plt.xlabel('Delivery_Time')\n", + "plt.ylabel('Frequency')\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Define stat columns\n", + "stat_cols = [ 'Order_ID' ]\n", + "\n", + "# Drop rows with missing stat values\n", + "df_clean = df_delivery.dropna(subset=stat_cols).copy()\n", + "print(f\"Shape after cleaning: {df_clean.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n" + ], + "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_delivery):\n", + " duplicates = df_delivery.duplicated().sum()\n", + " print(f\"Number of Duplicate Samples: {duplicates}\")\n", + " if duplicates > 0:\n", + " print(\"Dropping Duplicates...\")\n", + " df_delivery.drop_duplicates(inplace=True)\n", + " print(\"Duplicates Dropped.\")\n", + " else:\n", + " print(\"No Duplicate Samples Found.\")\n", + "\n", + "check_duplicates(df_delivery)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "\n", + "# Random data generation for encoding\n", + "import pandas as pd\n", + "\n", + "categories = pd.DataFrame({\"Traffic_Level\":['Low','Medium''Low','Medium','Low']}) # DataFrame of one column\n", + "\n", + "categories_wether = pd.DataFrame({\"Weather\":['Windy\t','Clear''Foggy','Rainy','Clear']})\n", + "\n", + "print(\"Before encoding:\")\n", + "categories\n", + "\n", + "from sklearn.preprocessing import OneHotEncoder #import OneHotEncoder\n", + "\n", + "print('data before encoding:\\n', categories,categories_wether) #show before encoding\n", + "\n", + "onehot_encoder = OneHotEncoder(sparse_output=False) # Instantiate OneHotEncoder\n", + "data_onehot_encoded = onehot_encoder.fit_transform(categories,categories_wether) # 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", + "# Scale features - fit on train, transform both\n", + "from sklearn.preprocessing import LabelEncoder\n", + "\n", + "for col in X_train.select_dtypes(include='object'):\n", + " le = LabelEncoder()\n", + " X_train[col] = le.fit_transform(X_train[col])\n", + " X_test[col] = le.transform(X_test[col])\n", + "\n", + "scaler = StandardScaler()\n", + "X_train_scaled = scaler.fit_transform(X_train)\n", + "X_test_scaled = scaler.transform(X_test)\n", + "\n", + "print(f\"\\nScaled ranges - Min: {X_train_scaled.min():.2f}, Max: {X_train_scaled.max():.2f}\")\n", + "pd.DataFrame(X_train_scaled, columns=X_train.columns).head(3)\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 6: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "# Define features (X) and target (y)\n", + "feature_cols = ['Order_ID','Distance_km','Weather','Traffic_Level','Time_of_Day','Vehicle_Type','Preparation_Time_min','Courier_Experience_yrs']\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", + "# 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", + "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/15/Q2.ipynb b/submissions_extracted/15/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..d6e69b6da47bcdab4527dbf6b74367b8fe848d34 --- /dev/null +++ b/submissions_extracted/15/Q2.ipynb @@ -0,0 +1,395 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "from torch.utils.data import DataLoader, TensorDataset\n", + "import kagglehub\n", + "import os\n", + "import pandas as pd\n", + "import numpy as np\n", + "from PIL import Image\n", + "from sklearn.model_selection import train_test_split\n", + "import 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", + "import torch" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "\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": [ + "\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", + "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", + "\n", + "print(\"X_train_tensor:\", X_train_tensor.shape, X_train_tensor.dtype)\n", + "print(\"X_test_tensor :\", X_test_tensor.shape, X_test_tensor.dtype)\n", + "print(\"y_train_tensor:\", y_train_tensor.shape, y_train_tensor.dtype)\n", + "print(\"y_test_tensor :\", y_test_tensor.shape, y_test_tensor.dtype)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 2. Create TensorDataset objects\n", + "\n", + "\n", + "# Create TensorDatasets for training and testing\n", + "train_dataset = TensorDataset(X_train_tensor, y_train_tensor)\n", + "test_dataset = TensorDataset(X_test_tensor, y_test_tensor)\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" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 3. Create DataLoaders\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", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 4. Print shape of one batch\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(1):\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": [ + "# 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", + "\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.layer3(a2)\n", + " a3 = self.relu(z3)\n", + "\n", + " # Output layer (raw scores / logits)\n", + " output = self.layer4(a3) # there is something missing here, remember? :)\n", + "\n", + " return output\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your training loop here:\n", + "def train_one_epoch(model, optimizer, criterion, train_loader, device):\n", + " # Set the model to training mode\n", + " model.train()\n", + "\n", + " running_loss = 0.0\n", + "\n", + " for X_batch, y_batch in train_loader:\n", + " # Move batch to the selected device\n", + " X_batch = X_batch.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", + "\n", + "# Device setup\n", + "device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n", + "\n", + "# Model parameters\n", + "input_dim = # MNIST images flattened\n", + "hidden_dim = 14 # Design choice\n", + "output_dim = 10 # Digits 0–9\n", + "\n", + "# Instantiate model\n", + "model = NN4Layer(input_dim, hidden_dim, output_dim).to(device)\n", + "\n", + "# Print the model architecture\n", + "print(\"Model Architecture:\\n\")\n", + "print(model)\n", + "\n", + "# Calculate the total number of trainable parameters\n", + "total_params = sum(p.numel() for p in model.parameters() if p.requires_grad)\n", + "print(f\"\\nTotal trainable parameters: {total_params}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Start training for 20 epochs:\n", + "num_epochs = 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/15/Q3.ipynb b/submissions_extracted/15/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..73098e39183e14c0de4c04773ab4ad79bfa817f2 --- /dev/null +++ b/submissions_extracted/15/Q3.ipynb @@ -0,0 +1,209 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "import pandas as pd\n", + "import numpy as np\n", + "import matplotlib.pyplot as plt\n", + "import seaborn as sns\n", + "import kagglehub\n", + "import os\n", + "from tqdm import tqdm\n", + "\n", + "# Download latest version\n", + "\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q3-exam-data\")\n", + "\n", + "\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "csv_path = os.path.join(path, \"Q3_data.csv\")\n", + "\n", + "df = pd.read_csv(csv_path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "df.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "df.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "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)\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "# 4. 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)" + ], + "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", + "numerical_cols = df.select_dtypes(include=[\"int64\", \"float64\"]).columns.drop(\"D_145\",\"D_144\") # 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:" + ], + "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/150/Q1.ipynb b/submissions_extracted/150/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..2e13efc7f93366bab17f9b51936b03ef0b31c9ec --- /dev/null +++ b/submissions_extracted/150/Q1.ipynb @@ -0,0 +1,332 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q1-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "\n", + "import pandas as pd\n", + "import matplotlib.pyplot as plt\n", + "import os\n", + "\n", + "q1 = os.path.join(path, 'Q1_data.csv')\n", + "df = pd.read_csv(q1)\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", + "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", + "\n", + "df = df.drop(['Order_ID'], axis=1)\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "def check_missing_values(df):\n", + " missing_values = df.isnull().sum()\n", + " print(\"Missing Values per Column:\")\n", + " print(missing_values[missing_values > 0])\n", + " if missing_values.any():\n", + " print(\"\\nHandle Missing Values as needed.\")\n", + " else:\n", + " print(\"\\nNo Missing Values Found.\")\n", + "\n", + "check_missing_values(df)\n", + "\n", + "\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "print(\"Checking for duplicate rows...\")\n", + "duplicate_rows = df.duplicated().sum()\n", + "if duplicate_rows > 0:\n", + " print(f\"Found {duplicate_rows} duplicate rows. Removing them...\")\n", + " df.drop_duplicates(inplace=True)\n", + " print(\"Duplicate rows removed.\")\n", + "else:\n", + " print(\"No duplicate rows found.\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "# 3. Do we have categorical columns?\n", + "categorical_cols = df.select_dtypes(include=[\"object\"]).columns\n", + "\n", + "print(\"Categorical Columns:\", list(categorical_cols))\n", + "\n", + "\n", + "# the output tells us there is categorical columns so we should use encoding\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) # Instantiate OneHotEncoder\n", + "data_onehot_encoded = onehot_encoder.fit_transform(categorical_cols) # Apply fit_transform to the copied\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", + "features = df.columns.drop(\"Delivery_Time\") # DON'T SCALE THE TARGET\n", + "\n", + "scaler = StandardScaler()\n", + "df[features] = scaler.fit_transform(df[features])\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 6: Write your code here:\n", + "import seaborn as sns\n", + "def check_target_imbalance(df, target_column):\n", + " print(\"Target Distribution:\")\n", + " print(df[target_column].value_counts(normalize=True))\n", + " sns.countplot(x=df[target_column])\n", + " plt.title(\"Target Distribution\")\n", + " plt.show()\n", + "\n", + "check_target_imbalance(df, \"Delivery_Time\")\n", + "\n", + "\n", + "#targer lef skewed (imblabnced)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "# Define features (X) and target (y)\n", + "\n", + "X = df.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", + "import numpy as np\n", + "from sklearn.ensemble import RandomForestRegressor\n", + "from sklearn.model_selection import StratifiedKFold\n", + "\n", + "from sklearn.metrics import mean_squared_error, mean_absolute_error\n", + "n_splits = 5 # K=5 Folds\n", + "\n", + "# Stratified 5-Fold Cross-Validation, shuffled\n", + "skf = StratifiedKFold(n_splits=n_splits, shuffle=True, random_state=42)\n", + "from sklearn.model_selection import StratifiedKFold\n", + "\n", + "# Use previously generated random classification data\n", + "X, y = X.copy(), y.copy()\n", + "\n", + "# Show full dataset class distribution\n", + "full_ratio = (y.value_counts(normalize=True) * 100).sort_index()\n", + "print(\"Full Dataset Class Distribution\")\n", + "print(\" y class percentages:\", {k: f\"{v:.2f}%\" for k, v in full_ratio.items()})\n", + "print(\"-\" * 40)\n", + "\n", + "# Define Stratified K-Fold\n", + "skf = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)\n", + "\n", + "print(\"Stratified K-Fold Cross Validation\\n\" + \"-\"*40)\n", + "\n", + "for fold, (train_idx, test_idx) in enumerate(skf.split(X, y), start=1):\n", + " # indexing for each fold\n", + " X_train, X_test = X.iloc[train_idx], X.iloc[test_idx]\n", + " y_train, y_test = y.iloc[train_idx], y.iloc[test_idx]\n", + "\n", + " print(f\"Fold {fold}\")\n", + " print(\" X_train shape:\", X_train.shape)\n", + " print(\" X_test shape :\", X_test.shape)\n", + " print(\" y_train shape:\", y_train.shape)\n", + " print(\" y_test shape :\", y_test.shape)\n", + "\n", + " # showing class distribution\n", + " train_ratio = (y_train.value_counts(normalize=True) * 100).sort_index()\n", + " test_ratio = (y_test.value_counts(normalize=True) * 100).sort_index()\n", + "\n", + " print(\" y_train class percentages:\", {k: f\"{v:.2f}%\" for k, v in train_ratio.items()})\n", + " print(\" y_test class percentages :\", {k: f\"{v:.2f}%\" for k, v in test_ratio.items()})\n", + "\n", + " print(\"-\" * 40)\n", + "\n", + "model = RandomForestRegressor(n_estimators=200) # instantiate\n", + "model.fit(X_train, y_train) # fit\n", + "y_pred = model.predict(X_test) # predict\n", + "\n", + "# Calculate metric\n", + "\n", + "mae = mean_absolute_error(y_test, y_pred)\n", + "\n", + "\n", + "print(\"MAE :\", mae)\n", + "\n", + "avg=np.mean(mae)\n", + "print(avg)\n", + "\n", + "\n", + "\n", + "\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 ,\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.plot(y_pred)\n", + "plt.xlabel('y')\n", + "plt.title('predicted delivery time')\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/150/Q2.ipynb b/submissions_extracted/150/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..eae3feac2af90daf2aad30e36254911c18682774 --- /dev/null +++ b/submissions_extracted/150/Q2.ipynb @@ -0,0 +1,391 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q2-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import os\n", + "import pandas as pd\n", + "import numpy as np\n", + "from PIL import Image\n", + "from sklearn.model_selection import train_test_split\n", + "\n", + "# Load Labels\n", + "labels_df = pd.read_csv(os.path.join(path, \"labels.csv\"))\n", + "img_dir = os.path.join(path, \"images\")\n", + "\n", + "images = []\n", + "ages = []\n", + "\n", + "# Load Images and Resize\n", + "print(\"Loading images...\")\n", + "for index, row in labels_df.iterrows():\n", + " img_name = row.iloc[0]\n", + " age = row.iloc[1]\n", + " img_path = os.path.join(img_dir, img_name)\n", + "\n", + " if os.path.exists(img_path):\n", + " img = Image.open(img_path).convert('RGB')\n", + " img_array = np.array(img) / 255.0 # Normalize pixel values to [0, 1]\n", + " images.append(img_array)\n", + " ages.append(age)\n", + "\n", + "X = np.array(images)\n", + "y = np.array(ages)\n", + "\n", + "# Transpose image dimensions to match PyTorch format (N, C, H, W)\n", + "X = np.transpose(X, (0, 3, 1, 2))\n", + "\n", + "# Split Data\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n", + "\n", + "print(f\"X_train shape: {X_train.shape}\")\n", + "print(f\"X_test shape: {X_test.shape}\")\n", + "print(f\"y_train shape: {y_train.shape}\")\n", + "print(f\"y_test shape: {y_test.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 1. Convert Numpy arrays to PyTorch Tensors\n", + "import torch\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", + "\n", + "\n", + "\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 2. Create TensorDataset objects\n", + "train_dataset = TensorDataset(X_train, y_train)\n", + "test_dataset = TensorDataset(X_test, y_test)\n", + "\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 3. Create DataLoaders\n", + "\n", + "Create Dataloaders to train and test data in batches\n", + "train_loader = DataLoader(train_dataset, batch_size=32, shuffle=True)\n", + "test_loader = DataLoader(test_dataset, batch_size=32, shuffle=False)\n", + "\n", + "\n", + "\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}\")\n", + "\n", + "\n", + "# now Access a single sample from the dataset\n", + "\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": [ + "# 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].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", + "\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", + " 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", + " #thrid hidden layer\n", + " z3=self.layer3(a2)\n", + " a3=self.relu(z3)\n", + "\n", + "\n", + "\n", + " # Output layer (raw scores / logits)\n", + " output = self.layer4(a3)\n", + " return output" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your training loop here:\n", + "def train_one_epoch(model, optimizer, criterion, train_loader, 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", + "\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}\")\n", + "\n", + "\n", + "num_epochs = 20\n", + "learning_rate = 0.001\n", + "\n", + "# Define criterion (loss function) - using CrossEntropyLoss as model now outputs logits\n", + "criterion = nn.CrossEntropyLoss()\n", + "# Define optimizer\n", + "optimizer = Adam(model.parameters(), learning_rate)\n" + ], + "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/150/Q3.ipynb b/submissions_extracted/150/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..d48f55e91a9ff3c8b7f828aba1158a785f60762e --- /dev/null +++ b/submissions_extracted/150/Q3.ipynb @@ -0,0 +1,305 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "\n", + "\n", + "# Download latest version\n", + "\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q3-exam-data\")\n", + "\n", + "\n", + "\n", + "print(\"Path to dataset files:\", path)\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "from IPython.display import clear_output\n", + "\n", + "%pip install catboost -q\n", + "\n", + "clear_output()" + ], + "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 os\n", + "\n", + "q3 = os.path.join(path, 'Q3_data.csv')\n", + "df = pd.read_csv(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", + "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", + "\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", + "print(\"Checking for duplicate rows...\")\n", + "duplicate_rows = df.duplicated().sum()\n", + "if duplicate_rows > 0:\n", + " print(f\"Found {duplicate_rows} duplicate rows. Removing them...\")\n", + " df.drop_duplicates(inplace=True)\n", + " print(\"Duplicate rows removed.\")\n", + "else:\n", + " print(\"No duplicate rows found.\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "categorical_cols = df.select_dtypes(include=[\"object\"]).columns\n", + "\n", + "print(\"Categorical Columns:\", list(categorical_cols))\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "from sklearn.preprocessing import StandardScaler\n", + "\n", + "features = df.columns.drop(\"Target\") # DON'T SCALE THE TARGET\n", + "\n", + "scaler = StandardScaler()\n", + "df[features] = scaler.fit_transform(df[features])\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "import seaborn as sns\n", + "def check_target_imbalance(df, target_column):\n", + " print(\"Target Distribution:\")\n", + " print(df[target_column].value_counts(normalize=True))\n", + " sns.countplot(x=df[target_column])\n", + " plt.title(\"Target Distribution\")\n", + " plt.show()\n", + "\n", + "check_target_imbalance(df, \"Target\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "# Define features (X) and target (y)\n", + "\n", + "X = df.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", + "import numpy as np\n", + "from catboost import CatBoostClassifier\n", + "from sklearn.model_selection import StratifiedKFold\n", + "from sklearn.metrics import accuracy_score, f1_score\n", + "\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", + "from sklearn.model_selection import StratifiedKFold\n", + "\n", + "# Use previously generated random classification data\n", + "X, y = X.copy(), y.copy()\n", + "\n", + "# Show full dataset class distribution\n", + "full_ratio = (y.value_counts(normalize=True) * 100).sort_index()\n", + "print(\"Full Dataset Class Distribution\")\n", + "print(\" y class percentages:\", {k: f\"{v:.2f}%\" for k, v in full_ratio.items()})\n", + "print(\"-\" * 40)\n", + "\n", + "# Define Stratified K-Fold\n", + "skf = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)\n", + "\n", + "print(\"Stratified K-Fold Cross Validation\\n\" + \"-\"*40)\n", + "\n", + "for fold, (train_idx, test_idx) in enumerate(skf.split(X, y), start=1):\n", + " # indexing for each fold\n", + " X_train, X_test = X.iloc[train_idx], X.iloc[test_idx]\n", + " y_train, y_test = y.iloc[train_idx], y.iloc[test_idx]\n", + "\n", + " print(f\"Fold {fold}\")\n", + " print(\" X_train shape:\", X_train.shape)\n", + " print(\" X_test shape :\", X_test.shape)\n", + " print(\" y_train shape:\", y_train.shape)\n", + " print(\" y_test shape :\", y_test.shape)\n", + "\n", + " # showing class distribution\n", + " train_ratio = (y_train.value_counts(normalize=True) * 100).sort_index()\n", + " test_ratio = (y_test.value_counts(normalize=True) * 100).sort_index()\n", + "\n", + " print(\" y_train class percentages:\", {k: f\"{v:.2f}%\" for k, v in train_ratio.items()})\n", + " print(\" y_test class percentages :\", {k: f\"{v:.2f}%\" for k, v in test_ratio.items()})\n", + "\n", + " print(\"-\" * 40)\n", + "\n", + "model = CatBoostClassifier(verbose=0,\n", + " n_estimators=200,\n", + " max_depth=4) # instantiate\n", + "model.fit(X_train, y_train) # fit\n", + "y_pred = model.predict(X_test) # predict\n", + "\n", + "# Calculate metric\n", + "\n", + "accuracy = accuracy_score(y_test, y_pred)\n", + "f1 = f1_score(y_test, y_pred, average='macro')\n", + "\n", + "print(accuracy)\n", + "\n", + "print(f1)\n", + "\n", + "print(f\" Accuracy: {np.mean(accuracy):.4f}\")\n", + "print(f\" F1-Score: {np.mean(f1):.4f}\")\n", + "\n", + "\n", + "\n", + "\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_train ,\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" + ], + "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/151/Q1.ipynb b/submissions_extracted/151/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..5f8326685b7a7de182991865cad7dc2bccd1c76b --- /dev/null +++ b/submissions_extracted/151/Q1.ipynb @@ -0,0 +1,225 @@ +{ + "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", + "# 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", + "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\"Shape: {df_Q1.shape}\")\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.figure(figsize=(10, 5))\n", + "plt.hist(df_Q1['Delivery_Time'].dropna(), bins=50, edgecolor='black')\n", + "plt.title('Delivery Time Distribution')\n", + "plt.xlabel('Distance')\n", + "plt.ylabel('Prep time')\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "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", + "df_Q1['Order_ID'] = df_Q1['Order_ID'].fillna('none')\n", + "df_Q1['Distance_km'] = df_Q1['Distance_km'].fillna('none')\n", + "df_Q1['Vehicle_Type'] = df_Q1['Vehicle_Type'].fillna('none')\n", + "df_Q1['Preparation_Time_min'] = df_Q1['Preparation_Time_min'].fillna('none')" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "print(\"Checking for duplicates...\")\n", + "dups = df_Q1.duplicated().sum()\n", + "if dups > 0:\n", + " print(f\"Found {dups} duplicates. Removing them...\")\n", + " df_Q1.drop_duplicates(inplace=True)\n", + " print(\"Duplicates removed.\")\n", + "else:\n", + " print(\"No duplicates found.\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "categorical_cols = ['Weather', 'Time_of_Day', 'Vehicle_Type', 'Traffic_Level']\n", + "for col in categorical_cols:\n", + " le = LabelEncoder()\n", + " df_Q1[col] = le.fit_transform(df_Q1[col].astype(str))" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\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" + ], + "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/151/Q2.ipynb b/submissions_extracted/151/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..3b680fa68a6a19f95a7f9178b930e6000c9afada --- /dev/null +++ b/submissions_extracted/151/Q2.ipynb @@ -0,0 +1,386 @@ +{ + "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", + "from PIL import Image\n", + "from sklearn.model_selection import train_test_split\n", + "\n", + "import kagglehub\n", + "import pandas as pd\n", + "import numpy as np\n", + "import torch\n", + "import torch.nn as nn\n", + "from torch.optim import AdamW\n", + "import matplotlib.pyplot as plt\n", + "from torch.utils.data import DataLoader, TensorDataset\n", + "from sklearn.model_selection import train_test_split\n", + "from sklearn.preprocessing import StandardScaler, LabelEncoder\n", + "from sklearn.metrics import mean_absolute_error, mean_squared_error, r2_score\n", + "\n", + "# 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" + ], + "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", + "sample_image, sample_label = train_dataset[0]\n", + "print(f\"Image shape: {sample_image.shape}\")\n", + "print(f\"Label: {sample_label}\")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 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", + "\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", + "\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, hidden_dim)\n", + "\n", + "\n", + "\n", + " self.relu = nn.ReLU()\n", + "\n", + "\n", + " def forward(self, x):\n", + "\n", + " z1 = self.layer1(x)\n", + " a1 = self.relu(z1)\n", + "\n", + "\n", + " z2 = self.layer2(a1)\n", + " a2 = self.relu(z2)\n", + "\n", + "\n", + " z3 = self.layer3(a2)\n", + " a3 = self.relu(z3)\n", + "\n", + "\n", + " z4 = self.layer4(a3)\n", + "\n", + "\n", + " return z4" + ], + "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", + "\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", + "\n", + " outputs = model(X_batch)\n", + "\n", + " loss = criterion(outputs, y_batch)\n", + "\n", + "\n", + " optimizer.zero_grad()\n", + " loss.backward()\n", + " optimizer.step()\n", + "\n", + " running_loss += loss.item()\n", + "\n", + " avg_loss = running_loss / len(train_loader)\n", + "\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", + "\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", + "\n", + " loss = criterion(outputs, y_batch)\n", + " running_loss += loss.item()\n", + "\n", + "\n", + " probabilities = F.softmax(outputs, dim=1)\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", + "\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 * 36 * 36 #3 * 32 * 32\n", + "\n", + "\n", + "hidden_dim = 64\n", + "\n", + "\n", + "output_dim = 10\n", + "\n", + "\n", + "model = NN4Layer(input_dim, hidden_dim, output_dim).to(device)\n", + "\n", + "\n", + "print(\"Model Architecture:\\n\")\n", + "print(model)\n", + "\n", + "\n", + "total_params = sum(p.numel() for p in model.parameters() if p.requires_grad)\n", + "print(f\"\\nTotal trainable parameters: {total_params}\")\n", + "\n", + "\n", + "learning_rate = 0.001\n", + "\n", + "\n", + "criterion = nn.CrossEntropyLoss()\n", + "\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", + "num_epochs = 20\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!')\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/151/Q3.ipynb b/submissions_extracted/151/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..ee8b9d9f19721aaded13eba96f7413c87946cdf5 --- /dev/null +++ b/submissions_extracted/151/Q3.ipynb @@ -0,0 +1,199 @@ +{ + "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", + "import kagglehub\n", + "\n", + "from sklearn.model_selection import train_test_split, StratifiedKFold, cross_val_score\n", + "from sklearn.preprocessing import StandardScaler, LabelEncoder\n", + "from sklearn.ensemble import RandomForestClassifier\n", + "from sklearn.metrics import classification_report, confusion_matrix, accuracy_score\n", + "\n", + "import warnings\n", + "warnings.filterwarnings('ignore')\n", + "\n", + "\n", + "# Download latest version\n", + "\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q3-exam-data\")\n", + "\n", + "\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "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", + "print(f\"Shape: {df_Q3.shape}\")\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())\n", + "\n", + "df_Q3['D_39'] = df_Q3['D_39'].fillna('none')\n", + "df_Q3['B_1'] = df_Q3['B_1'].fillna('none')\n", + "df_Q3['R_1'] = df_Q3['R_1'].fillna('none')\n", + "df_Q3['Target'] = df_Q3['Target'].fillna('none')" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "print(\"Checking for duplicates...\")\n", + "dups = df_Q3.duplicated().sum()\n", + "if dups > 0:\n", + " print(f\"Found {dups} duplicates. Removing them...\")\n", + " df_Q3.drop_duplicates(inplace=True)\n", + " print(\"Duplicates removed.\")\n", + "else:\n", + " print(\"No duplicates found.\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "categorical_cols = ['', '', '', '']\n", + "for col in categorical_cols:\n", + " le = LabelEncoder()\n", + " df_Q3[col] = le.fit_transform(df_Q3[col].astype(str))" + ], + "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/152/Q1.ipynb b/submissions_extracted/152/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..4d3d77460b2445b778d97822e05a239dbda5ddae --- /dev/null +++ b/submissions_extracted/152/Q1.ipynb @@ -0,0 +1,316 @@ +{ + "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" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q1-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "#Read the dataset Q1_data.csv using read_csv()\n", + "\n", + "lap_path = os.path.join(path, 'Q1_data.csv')\n", + "df_food = pd.read_csv(lap_path)\n", + "\n", + "print(f\"Dataset shape: {df_food.shape}\")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "#Inspect the first few rows using head()\n", + "df_food.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "#Display dataset information using info()\n", + "df_food.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "#Show statistical description using describe()\n", + "df_food.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "#Plot the target distribution (delivery_time)\n", + "plt.figure(figsize=(10, 5))\n", + "plt.hist(df_food['Delivery_Time'].dropna(), bins=50, edgecolor='black')\n", + "plt.title('target 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", + "#Drop the 'Order_ID' column from the data\n", + "df_food.drop(columns=['Order_ID'])\n", + "df_food.columns" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "#Handle missing values appropriately\n", + "# Fill categorical columns with 'unknown' - missing likely means \"not specified\"\n", + "for col in ['Weather', 'Traffic_Level', 'Time_of_Day']:\n", + " df_food[col] = df_food[col].fillna('unknown')\n", + "\n", + "# Fill cylinders with mode - discrete feature, mode is most representative\n", + "df_food['Courier_Experience_yrs'] = df_food['Courier_Experience_yrs'].fillna(df_food['Courier_Experience_yrs'].mode()[0])\n", + "#handle whith missing in label\n", + "df_food['Delivery_Time']=df_food['Delivery_Time'].fillna(df_food['Delivery_Time'].mode()[0])\n", + "print(\"Missing values remaining:\", df_food.isnull().sum().sum())" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "#Check and remove duplicates\n", + "# . Do we have duplicate samples?\n", + "def check_duplicates(df_food):\n", + " duplicates = df_food().duplicated().sum()\n", + " print(f\"Number of Duplicate Samples: {duplicates}\")\n", + " if duplicates > 0:\n", + " print(\"Dropping Duplicates...\")\n", + " df_food.drop_duplicates(inplace=True)\n", + " print(\"Duplicates Dropped.\")\n", + " else:\n", + " print(\"No Duplicate Samples Found.\")\n", + "\n", + "check_duplicates(df_food)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "#Encode categorical variables\n", + "categorical_cols = df_food.select_dtypes(include=[\"object\"]).columns\n", + "\n", + "print(\"Categorical Columns:\", list(categorical_cols))\n", + "\n", + "label_encoders = {}\n", + "for col in categorical_cols:\n", + " le = LabelEncoder()\n", + " df_food[col] = le.fit_transform(df_food[col])\n", + " label_encoders[col] = le\n", + "df_food" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "#Apply feature scaling for all features\n", + "from sklearn.preprocessing import StandardScaler #import StandardScaler\n", + "num_cols = df_food.select_dtypes(include=[\"int64\", \"float64\"]).columns.drop(\"Delivery_Time\")# DON'T SCALE THE TARGET\n", + "\n", + "scaler = StandardScaler()\n", + "num_cols_scaled = scaler.fit_transform(df_food[num_cols])\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\n", + "# Is the target imbalanced?\n", + "#it is regression so not eather balance or not\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "# Train-test split (80% train, 20% test)\n", + "X = df_food.drop(\"Delivery_Time\", axis=1)\n", + "y = df_food['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", + "df_food.head()\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:\n", + "\n", + "from sklearn.model_selection import train_test_split, KFold\n", + "from sklearn.ensemble import RandomForestRegressor\n", + "#random forest model\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", + "# Predictions\n", + "y_pred = model.predict(X_test)\n", + "\n", + "#k-fold\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", + "\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}\")\n", + "\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": [ + "# Task 1: Write your code here:\n", + "# Feature importance\n", + "feature_cols=df_food[ 'Distance_km', 'Weather', 'Traffic_Level', 'Time_of_Day',\n", + " 'Vehicle_Type', 'Preparation_Time_min', 'Courier_Experience_yrs']\n", + "importance = pd.DataFrame({\n", + " 'feature': feature_cols,\n", + " 'importance': model.feature_importances_\n", + "}).sort_values('importance', ascending=False)\n", + "\n", + "plt.figure(figsize=(10, 6))\n", + "plt.barh(importance['feature'], importance['importance'], color='purple')\n", + "plt.xlabel('Importance')\n", + "plt.title('Feature Importance')\n", + "plt.gca().invert_yaxis()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/152/Q2.ipynb b/submissions_extracted/152/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..32f542a40b86fd090f358976da948b518bde9e1a --- /dev/null +++ b/submissions_extracted/152/Q2.ipynb @@ -0,0 +1,380 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "import pandas as pd\n", + "import torch\n", + "import torch.nn as nn\n", + "from torch.optim import AdamW\n", + "import matplotlib.pyplot as plt\n", + "import torch.nn.functional as F\n", + "from torch.utils.data import DataLoader, TensorDataset\n", + "from sklearn.model_selection import train_test_split\n", + "from sklearn.preprocessing import StandardScaler, LabelEncoder" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q2-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import os\n", + "import pandas as pd\n", + "import numpy as np\n", + "from PIL import Image\n", + "from sklearn.model_selection import train_test_split\n", + "\n", + "# Load Labels\n", + "labels_df = pd.read_csv(os.path.join(path, \"labels.csv\"))\n", + "img_dir = os.path.join(path, \"images\")\n", + "\n", + "images = []\n", + "ages = []\n", + "\n", + "# Load Images and Resize\n", + "print(\"Loading images...\")\n", + "for index, row in labels_df.iterrows():\n", + " img_name = row.iloc[0]\n", + " age = row.iloc[1]\n", + " img_path = os.path.join(img_dir, img_name)\n", + "\n", + " if os.path.exists(img_path):\n", + " img = Image.open(img_path).convert('RGB')\n", + " img_array = np.array(img) / 255.0 # Normalize pixel values to [0, 1]\n", + " images.append(img_array)\n", + " ages.append(age)\n", + "\n", + "X = np.array(images)\n", + "y = np.array(ages)\n", + "\n", + "# Transpose image dimensions to match PyTorch format (N, C, H, W)\n", + "X = np.transpose(X, (0, 3, 1, 2))\n", + "\n", + "# Split Data\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n", + "\n", + "print(f\"X_train shape: {X_train.shape}\")\n", + "print(f\"X_test shape: {X_test.shape}\")\n", + "print(f\"y_train shape: {y_train.shape}\")\n", + "print(f\"y_test shape: {y_test.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 1. Convert Numpy arrays to PyTorch Tensors\n", + "import torch\n", + "# transform to 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" + ], + "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", + "# 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", + "print(\"Train dataset:\", len(train_dataset))\n", + "print(\"Test dataset:\", len(test_dataset))\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].squeeze(), cmap='gray')\n", + " plt.title(f\"Label: {labels[i].item()}\")\n", + " plt.axis('off')\n", + "\n", + "plt.tight_layout()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your model class here:\n", + "class 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 = 1 # only age\n", + "\n", + "# Instantiate model\n", + "model = NN4Layer(input_dim, hidden_dim, output_dim).to(device)\n", + "\n", + "# Print the model architecture\n", + "print(\"Model Architecture:\\n\")\n", + "print(model)\n", + "\n", + "# 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.MSELoss()\n", + "# Define optimizer\n", + "optimizer = AdamW(model.parameters(), learning_rate)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "# 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_losses = 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_losses)\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_losses:.4f}, '\n", + " f'Val Loss: {val_loss:.4f}'\n", + " )\n", + "\n", + "print('Training Complete!')\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/152/Q3.ipynb b/submissions_extracted/152/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..1b9e9660ab5ae5ae0585e93e6f68da671bbc6153 --- /dev/null +++ b/submissions_extracted/152/Q3.ipynb @@ -0,0 +1,260 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import numpy as np\n", + "import pandas as pd\n", + "import matplotlib.pyplot as plt\n", + "import os\n", + "import kagglehub\n", + "\n", + "from sklearn.model_selection import train_test_split, KFold\n", + "from sklearn.preprocessing import StandardScaler, LabelEncoder\n", + "from sklearn.ensemble import RandomForestRegressor\n", + "from sklearn.metrics import mean_absolute_error, mean_squared_error\n", + "\n", + "import warnings\n", + "warnings.filterwarnings('ignore')" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "\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", + "lap_path = os.path.join(path, 'Q3_data.csv')\n", + "df = pd.read_csv(lap_path)\n", + "\n", + "print(f\"Dataset shape: {df.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "df.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "df.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "def check_missing_values(df):\n", + " missing_values = df.isnull().sum()\n", + " print(\"Missing Values per Column:\")\n", + " print(missing_values[missing_values > 0])\n", + " if missing_values.any():\n", + " print(\"\\nHandle Missing Values as needed.\")\n", + " else:\n", + " print(\"\\nNo Missing Values Found.\")\n", + "\n", + "check_missing_values(df)\n", + "\n", + "df[col] = df[col].fillna(df[col].mode()[0])" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "def check_duplicates(df):\n", + " duplicates = df.duplicated().sum()\n", + " print(f\"Number of Duplicate Samples: {duplicates}\")\n", + " if duplicates > 0:\n", + " print(\"Dropping Duplicates...\")\n", + " df.drop_duplicates(inplace=True)\n", + " print(\"Duplicates Dropped.\")\n", + " else:\n", + " print(\"No Duplicate Samples Found.\")\n", + "\n", + "check_duplicates(df)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "# 2. Do we have missing values?no\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", + "#Apply feature scaling for all features\n", + "from sklearn.preprocessing import StandardScaler #import StandardScaler\n", + "num_cols = df.select_dtypes(include=[\"int64\", \"float64\"]).columns.drop(\"Target\")# DON'T SCALE THE TARGET\n", + "\n", + "scaler = StandardScaler()\n", + "num_cols_scaled = scaler.fit_transform(df[num_cols])" + ], + "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)\n", + "y = df['Target']\n", + "\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n", + "print(f\"Train: {X_train.shape}, Test: {X_test.shape}\")" + ], + "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(\n", + " verbose=0,\n", + " n_estimators=320,\n", + " max_depth=4)\n", + "n_splits = 5 # K\n", + "r_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:" + ], + "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/153/Q1.ipynb b/submissions_extracted/153/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..4feef722a138e1b0d2f048f23fe78db6a07d1d2d --- /dev/null +++ b/submissions_extracted/153/Q1.ipynb @@ -0,0 +1,353 @@ +{ + "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", + "\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/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 = pd.read_csv(path + \"/Q1_data.csv\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "Q1_data.head(20)" + ], + "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", + "plt.figure(figsize=(10, 5))\n", + "plt.hist(Q1_data['Delivery_Time'].dropna(), bins=50, edgecolor='black')\n", + "plt.title('Delivery Time Distribution')\n", + "plt.xlabel('Delivery Time')\n", + "plt.ylabel('Frequency')\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "Q1_data = Q1_data.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(Q1_data.isnull().sum())\n", + "\n", + "missing_percentage = (Q1_data.isnull().sum() / len(Q1_data)) * 100\n", + "missing_data = pd.DataFrame({\n", + " 'Column': missing_percentage.index,\n", + " 'Missing_Percentage': missing_percentage.values\n", + "})\n", + "missing_data = missing_data[missing_data['Missing_Percentage'] > 0].sort_values('Missing_Percentage', ascending=False)\n", + "\n", + "print(\"Missing Data Analysis:\")\n", + "missing_data.head(10)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "\n", + "Q1_data = Q1_data.fillna({'Weather': 'Unknown', 'Traffic_Level': 'Unknown', 'Time_of_Day': 'Unknown'})\n", + "print(\"\\n2. Fill with constant:\")\n", + "print(Q1_data)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "Q1_data = Q1_data.dropna()\n", + "print(\"\\n1. After dropna():\", len(Q1_data), \"rows\")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "print(\"Missing values:\")\n", + "print(Q1_data.isnull().sum())" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "Q1_data.info()\n", + "#success :)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "print(\"Checking for duplicate rows...\")\n", + "duplicate_rows = Q1_data.duplicated().sum()\n", + "if duplicate_rows > 0:\n", + " print(f\"Found {duplicate_rows} duplicate rows. Removing them...\")\n", + " Q1_data.drop_duplicates(inplace=True)\n", + " print(\"Duplicate rows removed.\")\n", + "else:\n", + " print(\"No duplicate rows found.\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "from sklearn.preprocessing import LabelEncoder\n", + "categorical_cols = ['Weather', 'Traffic_Level','Time_of_Day', 'Vehicle_Type']\n", + "for col in categorical_cols:\n", + " le = LabelEncoder()\n", + " Q1_data[col] = le.fit_transform(Q1_data[col].astype(str))\n", + "\n", + "Q1_data.head()\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "\n", + "from sklearn.preprocessing import StandardScaler #import StandardScaler\n", + "\n", + "print('data before scaling:\\n', Q1_data) #show before scaling\n", + "standard_scaler = StandardScaler() # Instantiate StandardScaler\n", + "data_standard_scaled = standard_scaler.fit_transform(Q1_data) # Apply fit_transform\n", + "\n", + "print('\\nData after scaling:\\n', data_standard_scaled) #show after scaling" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 6: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "target_column = \"Delivery_Time\"\n", + "X = Q1_data.drop(target_column, axis=1)\n", + "y = Q1_data[target_column]\n", + "\n", + "print(\"\\nDataset Shapes\")\n", + "print(\"X:\", X.shape)\n", + "print(\"y:\", y.shape)" + ], + "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, r2_score\n", + "X_scaled = standard_scaler.fit_transform(X)\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", + "model = RandomForestRegressor(n_estimators=100,\n", + "random_state=42)\n", + "model.fit(X_train, y_train)\n", + "y_pred = model.predict(X_test)\n", + "mae = mean_absolute_error(y_test, y_pred)\n", + "r2 = r2_score(y_test, y_pred)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Print Evaluation Metrics\n", + "print(\"\\nModel Evaluation Metrics (K-Fold)\\n\" + \"-\"*5)\n", + "print(f\"MAE : {np.mean(mae):.2f}\")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "feature_importance = pd.DataFrame({\n", + "'feature': X_train.columns,\n", + "'importance': model.feature_importances_\n", + "}).sort_values('importance', ascending=False)\n", + "plt.figure(figsize=(12, 8))\n", + "plt.barh(feature_importance['feature'][:15],\n", + "feature_importance['importance'][:15])\n", + "plt.gca().invert_yaxis()\n", + "plt.title('Top 15 Feature Importances')\n", + "plt.xlabel('Importance Score')\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=(12, 5))\n", + "# Subplot 1: Actual vs Predicted scatter\n", + "plt.subplot(1, 2, 1)\n", + "plt.scatter(y_valid, y_pred, alpha=0.5, s=10)\n", + "plt.plot([y_valid.min(), y_valid.max()], [y_valid.min(),\n", + "y_valid.max()], 'r--', lw=2)\n", + "plt.xlabel('Actual Emissions')\n", + "plt.ylabel('Predicted Emissions')\n", + "plt.title('Actual vs Predicted Emissions')\n", + "plt.grid(True, alpha=0.3)\n", + "# Subplot 2: Histogram of predictions\n", + "plt.subplot(1, 2, 2)\n", + "plt.hist(y_pred, bins=50, alpha=0.7, label='Predicted',\n", + "color='orange', edgecolor='black')\n", + "plt.hist(y_valid, bins=50, alpha=0.5, label='Actual',\n", + "color='blue', edgecolor='black')\n", + "plt.xlabel('Emission Value')\n", + "plt.ylabel('Frequency')\n", + "plt.title('Distribution: Actual vs Predicted')\n", + "plt.legend()\n", + "plt.grid(True, alpha=0.3)\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/153/Q2.ipynb b/submissions_extracted/153/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..a3b935606b40e30607b48ac34eb0adb606edb6c3 --- /dev/null +++ b/submissions_extracted/153/Q2.ipynb @@ -0,0 +1,360 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import torch\n", + "import torch.nn as nn\n", + "from torch.optim import Adam" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import matplotlib.pyplot as plt\n", + "from torch.utils.data import DataLoader, TensorDataset\n", + "from sklearn.model_selection import train_test_split\n", + "from sklearn.preprocessing import StandardScaler, LabelEncoder\n", + "from sklearn.metrics import mean_absolute_error, mean_squared_error, r2_score\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q2-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import os\n", + "import pandas as pd\n", + "import numpy as np\n", + "from PIL import Image\n", + "from sklearn.model_selection import train_test_split\n", + "\n", + "# Load Labels\n", + "labels_df = pd.read_csv(os.path.join(path, \"labels.csv\"))\n", + "img_dir = os.path.join(path, \"images\")\n", + "\n", + "images = []\n", + "ages = []\n", + "\n", + "# Load Images and Resize\n", + "print(\"Loading images...\")\n", + "for index, row in labels_df.iterrows():\n", + " img_name = row.iloc[0]\n", + " age = row.iloc[1]\n", + " img_path = os.path.join(img_dir, img_name)\n", + "\n", + " if os.path.exists(img_path):\n", + " img = Image.open(img_path).convert('RGB')\n", + " img_array = np.array(img) / 255.0 # Normalize pixel values to [0, 1]\n", + " images.append(img_array)\n", + " ages.append(age)\n", + "\n", + "X = np.array(images)\n", + "y = np.array(ages)\n", + "\n", + "# Transpose image dimensions to match PyTorch format (N, C, H, W)\n", + "X = np.transpose(X, (0, 3, 1, 2))\n", + "\n", + "# Split Data\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n", + "\n", + "print(f\"X_train shape: {X_train.shape}\")\n", + "print(f\"X_test shape: {X_test.shape}\")\n", + "print(f\"y_train shape: {y_train.shape}\")\n", + "print(f\"y_test shape: {y_test.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 1. Convert Numpy arrays to PyTorch Tensors\n", + "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", + "\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 3. Create DataLoaders\n", + "train_loader = DataLoader(train_dataset, batch_size=32, shuffle=True)\n", + "test_loader = DataLoader(test_dataset, batch_size=32, shuffle=False)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 4. Print shape of one batch\n", + "X_batch, y_batch = next(iter(train_loader))\n", + "print(f\"Training batch input shape: {X_batch.shape}\")\n", + "print(f\"Training batch labels shape: {y_batch.shape}\")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 5. Display sample images\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your model class here:\n", + "class NN3Layer(nn.Module):\n", + "\n", + " def __init__(self, input_dim, hidden_dim, output_dim):\n", + " super(NN3Layer, self).__init__()\n", + "\n", + " # First linear layer: input features -> hidden layer\n", + " self.layer1 = nn.Linear(input_dim, hidden_dim)\n", + "\n", + " # Second linear layer: hidden layer -> hidden layer\n", + " self.layer2 = nn.Linear(hidden_dim, hidden_dim)\n", + "\n", + " # 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" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your training loop here:\n", + "def train_one_epoch(model, optimizer, criterion, train_loader, device):\n", + " # Set the model to training mode\n", + " model.train()\n", + "\n", + " running_loss = 0.0\n", + "\n", + " for X_batch, y_batch in train_loader:\n", + " # Move batch to the selected device\n", + " X_batch = X_batch.view(X_batch.size(0), -1).to(device)\n", + " y_batch = y_batch.to(device)\n", + "\n", + " # Forward pass\n", + " outputs = model(X_batch) # shape: (batch_size, 10)\n", + " loss = criterion(outputs, y_batch)\n", + "\n", + " # Backward pass & optimization\n", + " optimizer.zero_grad() # Clear previous gradients\n", + " loss.backward() # Compute gradients\n", + " optimizer.step() # Update model parameters\n", + "\n", + " running_loss += loss.item()\n", + "\n", + " # Average loss over all batches\n", + " avg_loss = running_loss / len(train_loader)\n", + "\n", + " return avg_loss" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your validation loop here:\n", + "def validate(model, criterion, test_loader, device):\n", + " # Set the model to evaluation mode\n", + " model.eval()\n", + "\n", + " running_loss = 0.0\n", + " correct = 0\n", + " total = 0\n", + "\n", + " with torch.no_grad():\n", + " for X_batch, y_batch in test_loader:\n", + " # Move data to device\n", + " X_batch = X_batch.view(X_batch.size(0), -1).to(device)\n", + " y_batch = y_batch.to(device)\n", + "\n", + " # Forward pass\n", + " outputs = model(X_batch) # shape: (batch_size, 10)\n", + " loss = criterion(outputs, y_batch)\n", + " running_loss += loss.item()\n", + "\n", + " # Apply Softmax to get probabilities\n", + " probabilities = F.softmax(outputs, dim=1)\n", + "\n", + " # Multiclass predictions\n", + " predicted = torch.argmax(probabilities, dim=1)\n", + "\n", + " # Accuracy calculation\n", + " correct += (predicted == y_batch).sum().item()\n", + " total += y_batch.size(0)\n", + "\n", + " avg_loss = running_loss / len(test_loader)\n", + " accuracy = correct / total\n", + "\n", + " return avg_loss, accuracy" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Define device, model, loss, optimizer:\n", + "device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n", + "\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", + "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", + "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/153/Q3.ipynb b/submissions_extracted/153/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..93912be30993e07258bafed239e5338373a1b453 --- /dev/null +++ b/submissions_extracted/153/Q3.ipynb @@ -0,0 +1,237 @@ +{ + "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", + "\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": [ + "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_data = pd.read_csv(path + \"/Q3_data.csv\")" + ], + "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", + "print(\"\\nMissing values before handling:\")\n", + "print(Q3_data.isnull().sum())\n", + "\n", + "missing_percentage = (Q3_data.isnull().sum() / len(Q3_data)) * 100\n", + "missing_data = pd.DataFrame({\n", + " 'Column': missing_percentage.index,\n", + " 'Missing_Percentage': missing_percentage.values\n", + "})\n", + "missing_data = missing_data[missing_data['Missing_Percentage'] > 0].sort_values('Missing_Percentage', ascending=False)\n", + "\n", + "print(\"Missing Data Analysis:\")\n", + "missing_data.head(10)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "\n", + "# Strategy 2: Fill with constant\n", + "Q3_data = Q3_data.fillna('0')\n", + "print(\"\\n2. Fill:\")\n", + "print(Q3_data)\n", + "\n", + "# When to use each:\n", + "# dropna(): <5% missing, random pattern\n", + "# fillna('Unknown'): Categorical, 'missing' has meaning\n", + "# fillna(mean/median): Numerical, <20% missing\n", + "# fillna(mode): Categorical, <30% missing\n", + "# Imputation (advanced): >30% missing, pattern exists" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "print(\"Checking for duplicate rows...\")\n", + "duplicate_rows = Q3_data.duplicated().sum()\n", + "if duplicate_rows > 0:\n", + " print(f\"Found {duplicate_rows} duplicate rows. Removing them...\")\n", + " Q3_data.drop_duplicates(inplace=True)\n", + " print(\"Duplicate rows removed.\")\n", + "else:\n", + " print(\"No duplicate rows found.\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "#no need" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "from sklearn.preprocessing import StandardScaler #import StandardScaler\n", + "\n", + "print('data before scaling:\\n', Q3_data) #show before scaling\n", + "standard_scaler = StandardScaler() # Instantiate StandardScaler\n", + "data_standard_scaled = standard_scaler.fit_transform(Q3_data) # Apply fit_transform\n", + "\n", + "print('\\nData after scaling:\\n', data_standard_scaled) #show after scaling" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:" + ], + "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", + "from sklearn.model_selection import KFold\n", + "kf = KFold(n_splits=5, shuffle=True, random_state=42)\n", + "df['category_target_encoded'] = 0\n", + "\n", + "for train_idx, val_idx in kf.split(df):\n", + " train_df = df.iloc[train_idx]\n", + " val_df = df.iloc[val_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/154/Q1.ipynb b/submissions_extracted/154/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..992f2c40c449e1f3126d0963a16fadbdbe8ed3c7 --- /dev/null +++ b/submissions_extracted/154/Q1.ipynb @@ -0,0 +1,314 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# @title\n", + "#Implementing all the necessary libraries\n", + "import numpy as np\n", + "import pandas as pd\n", + "import matplotlib.pyplot as plt\n", + "import kagglehub\n", + "from sklearn.preprocessing import StandardScaler, LabelEncoder\n", + "from sklearn.model_selection import KFold\n", + "from sklearn.linear_model import LinearRegression\n", + "from sklearn.metrics import mean_squared_error, mean_absolute_error\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# @title\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)\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# @title\n", + "# Task 1:\n", + "df = pd.read_csv(f\"{path}/Q1_data.csv\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# @title\n", + "# Task 2:\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3:\n", + "df.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4:\n", + "df.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5:\n", + "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('Frequency')\n", + "plt.show()\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1:\n", + "df.drop(columns=['Order_ID'], inplace=True)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2:\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", + "print(missing_data)\n", + "\n", + "# Dropping rows with missing values if they are few\n", + "df.dropna(inplace=True)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3:\n", + "df.drop_duplicates(inplace=True)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4:\n", + "from sklearn.preprocessing import StandardScaler, LabelEncoder\n", + "# Identify categorical columns\n", + "categorical_cols = df.select_dtypes(include=['object']).columns.tolist()\n", + "for col in categorical_cols:\n", + " le = LabelEncoder()\n", + " df[col] = le.fit_transform(df[col].astype(str))\n", + "\n", + "df" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5:\n", + "scaler = StandardScaler()\n", + "df[df.columns] = scaler.fit_transform(df)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 6: Write your code here:\n", + "import seaborn as sns\n", + "# Checking for target imbalance\n", + "delivery_time_counts = df['Delivery_Time'].value_counts()\n", + "plt.figure(figsize=(10, 5))\n", + "sns.histplot(delivery_time_counts, bins=30)\n", + "plt.title('Target Variable Distribution')\n", + "plt.xlabel('Delivery Time (minutes)')\n", + "plt.ylabel('Frequency')\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1:\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:\n", + "from sklearn.model_selection import KFold\n", + "from sklearn.ensemble import RandomForestRegressor\n", + "from sklearn.metrics import mean_absolute_error\n", + "\n", + "kf = KFold(n_splits=5, shuffle=True, random_state=42)\n", + "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", + " model = RandomForestRegressor(random_state=42)\n", + " model.fit(X_train, y_train)\n", + " predictions = model.predict(X_test)\n", + "\n", + " mae = mean_absolute_error(y_test, predictions)\n", + " mae_scores.append(mae)\n", + "\n", + "average_mae = np.mean(mae_scores)\n", + "print(f'Average MAE across folds: {average_mae}')\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1:\n", + "#Average feature importance across folds\n", + "importances = model.feature_importances_\n", + "features = X.columns\n", + "indices = np.argsort(importances)[::-1]\n", + "\n", + "plt.figure(figsize=(12, 6))\n", + "plt.title('Feature Importances')\n", + "plt.bar(range(X.shape[1]), importances[indices], align='center')\n", + "plt.xticks(range(X.shape[1]), features[indices], rotation=90)\n", + "plt.xlim([-1, X.shape[1]])\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2:\n", + "predictions = model.predict(X)\n", + "plt.figure(figsize=(10, 5))\n", + "plt.hist(predictions, bins=50, edgecolor='black')\n", + "plt.title('Predicted Delivery Time Distribution')\n", + "plt.xlabel('Predicted Time (minutes)')\n", + "plt.ylabel('Frequency')\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", + "from catboost import CatBoostRegressor\n", + "\n", + "kf = KFold(n_splits=5, shuffle=True, random_state=42)\n", + "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", + " rf_model = RandomForestRegressor(random_state=42)\n", + " cb_model = CatBoostRegressor(verbose=0)\n", + "\n", + " rf_model.fit(X_train, y_train) #Training RandomForest Model\n", + " cb_model.fit(X_train, y_train) #Training CatBoost Model\n", + "\n", + " rf_predictions = rf_model.predict(X_test)\n", + " cb_predictions = cb_model.predict(X_test)\n", + "\n", + " # Average predictions\n", + " avg_predictions = (rf_predictions + cb_predictions) / 2\n", + "\n", + " mae = mean_absolute_error(y_test, avg_predictions)\n", + " mae_scores.append(mae)\n", + "\n", + "average_mae = np.mean(mae_scores)\n", + "print(f'Average MAE across folds with ensemble: {average_mae}')\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/154/Q2.ipynb b/submissions_extracted/154/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..a5baf53ed30df46f559ce6697a166838c8b7bdf4 --- /dev/null +++ b/submissions_extracted/154/Q2.ipynb @@ -0,0 +1,301 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/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 torch.utils.data import TensorDataset, DataLoader\n", + "\n", + "# 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", + "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", + "batch_size =32\n", + "train_loader = DataLoader(train_dataset, batch_size=batch_size , shuffle=True)\n", + "test_loader = DataLoader(test_dataset, batch_size=batch_size, shuffle=False)" + ], + "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", + "\n", + "# Function to display a few images\n", + "def show_sample_images(images):\n", + " fig, axes = plt.subplots(1, 5, figsize=(15, 5))\n", + " for i in range(5):\n", + " axes[i].imshow(images[i].permute(1, 2, 0).numpy())\n", + " axes[i].axis('off')\n", + " plt.show()\n", + "\n", + "# Display sample images\n", + "show_sample_images(X_train_tensor[:5])\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 AgePredictionModel(nn.Module):\n", + " def __init__(self):\n", + " super(AgePredictionModel, self).__init__()\n", + " self.flatten = nn.Flatten()\n", + " self.fc1 = nn.Linear(3888, 512) # no first dim seems to work but 3888 , to be able to mat multiply even though it gives ridiculous outputs\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 = self.flatten(x)\n", + " x = nn.ReLU()(self.fc1(x))\n", + " x = nn.ReLU()(self.fc2(x))\n", + " x = nn.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_model(model, train_loader, optimizer, criterion, epochs):\n", + " model.train()\n", + " for epoch in range(epochs):\n", + " for imgs, ages in train_loader:\n", + " optimizer.zero_grad()\n", + " outputs = model(imgs)\n", + " loss = criterion(outputs.squeeze(), ages)\n", + " loss.backward()\n", + " optimizer.step()\n", + " print(f'Epoch [{epoch+1}/{epochs}], Loss: {loss.item():.4f}')\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your validation loop here:\n", + "def validate_model(model, test_loader, criterion):\n", + " model.eval()\n", + " val_loss = 0\n", + " with torch.no_grad():\n", + " for imgs, ages in test_loader:\n", + " outputs = model(imgs)\n", + " loss = criterion(outputs.squeeze(), ages)\n", + " val_loss += loss.item()\n", + " return val_loss / len(test_loader)\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 = AgePredictionModel().to(device)\n", + "criterion = nn.MSELoss()\n", + "optimizer = torch.optim.Adam(model.parameters(), lr=0.001)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Start training for 20 epochs:\n", + "epochs = 20\n", + "for epoch in range(epochs):\n", + " train_model(model, train_loader, optimizer, criterion, epochs=1)\n", + " val_loss = validate_model(model, test_loader, criterion)\n", + " print(f'Validation Loss after Epoch {epoch + 1}: {val_loss:.4f}')\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "# Create lists to store losses\n", + "train_losses = []\n", + "val_losses = []\n", + "\n", + "# Modify training loop to store losses\n", + "for epoch in range(epochs):\n", + " train_model(model, train_loader, optimizer, criterion, epochs=1)\n", + " val_loss = validate_model(model, test_loader, criterion)\n", + " val_losses.append(val_loss)\n", + " print(f'Validation Loss after Epoch {epoch + 1}: {val_loss:.4f}')\n", + "\n", + "# Plotting training and validation loss\n", + "plt.plot(range(1, epochs + 1), val_losses, label='Validation Loss')\n", + "plt.xlabel('Epochs')\n", + "plt.ylabel('Loss')\n", + "plt.title('Training and Validation Loss')\n", + "plt.legend()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2 (Bonus): Write your code here:\n", + "def plot_predictions(model, test_loader, num_images=5):\n", + " model.eval()\n", + " with torch.no_grad():\n", + " imgs, ages = next(iter(test_loader))\n", + " outputs = model(imgs)\n", + "\n", + " fig, axes = plt.subplots(1, num_images, figsize=(15, 5))\n", + " for i in range(num_images):\n", + " axes[i].imshow(imgs[i].permute(1, 2, 0).numpy())\n", + " axes[i].set_title(f'Predicted Age: {outputs[i].item():.2f}\\nActual Age: {ages[i].item()}')\n", + " axes[i].axis('off')\n", + " plt.show()\n", + "\n", + "# Plot predictions\n", + "plot_predictions(model, test_loader)\n", + "\n", + "# I really tried :'(" + ], + "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/154/Q3.ipynb b/submissions_extracted/154/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..7908c4a5a870e00b6b91e33ef02b8ba7db5808a1 --- /dev/null +++ b/submissions_extracted/154/Q3.ipynb @@ -0,0 +1,249 @@ +{ + "cells": [ + { + "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", + "import pandas as pd\n", + "\n", + "data = pd.read_csv(f\"{path}/Q3_data.csv\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "data.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "data.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "data.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "print(data.isnull().sum())\n", + "data.fillna(data.median(), inplace=True) # filled null data with median" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "duplicates = data.duplicated().sum()\n", + "print(f'Duplicates: {duplicates}')\n", + "data.drop_duplicates(inplace=True)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "from sklearn.preprocessing import StandardScaler, LabelEncoder\n", + "# Identify categorical columns\n", + "categorical_cols = data.select_dtypes(include=['object']).columns.tolist()\n", + "for col in categorical_cols:\n", + " le = LabelEncoder()\n", + " data[col] = le.fit_transform(data[col].astype(str))\n", + "\n", + "data" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "scaler = StandardScaler()\n", + "numerical_cols = data.select_dtypes(include=['int64', 'float64']).columns.drop(\"Target\").tolist()\n", + "data[numerical_cols] = scaler.fit_transform(data[numerical_cols])" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "target_counts = data['Target'].value_counts()\n", + "print(target_counts)\n", + "print('Is the target imbalanced?', target_counts.min() / target_counts.max() < 0.1)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "%pip install catboost" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "from sklearn.model_selection import StratifiedKFold\n", + "from catboost import CatBoostClassifier\n", + "from sklearn.metrics import f1_score\n", + "\n", + "X = data.drop('Target', axis=1)\n", + "y = data['Target']\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:\n", + "kfold = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)\n", + "f1_scores = []\n", + "\n", + "# Task 3 and 4: Train CatBoostClassifier and evaluate\n", + "for train_index, test_index in kfold.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=100, learning_rate=0.1, depth=6, silent=True)\n", + " model.fit(X_train, y_train)\n", + "\n", + " y_pred = model.predict(X_test)\n", + "\n", + " # Task 4: Evaluate using F1 Score\n", + " f1_scores.append(f1_score(y_test, y_pred))\n", + "\n", + "# Task 5: Print the averaged F1 score across all folds\n", + "print('Average F1 Score:', sum(f1_scores) / len(f1_scores))\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "import matplotlib.pyplot as plt\n", + "\n", + "# Task 1: Plot feature importance from your trained model\n", + "feature_importances = model.get_feature_importance()\n", + "features = X.columns\n", + "\n", + "# Create a DataFrame for visualization\n", + "importance_df = pd.DataFrame({'Feature': features, 'Importance': feature_importances})\n", + "importance_df = importance_df.sort_values(by='Importance', ascending=False)\n", + "\n", + "# Plot\n", + "plt.figure(figsize=(12, 6))\n", + "plt.barh(importance_df['Feature'], importance_df['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", + "golden_feature = importance_df.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", + "\n", + "#Run the same KFold loop with this single feature\n", + "f1_scores_golden = []\n", + "\n", + "for train_index, test_index in kfold.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=100, learning_rate=0.1, depth=6, silent=True)\n", + " model_golden.fit(X_train, y_train)\n", + "\n", + " y_pred = model_golden.predict(X_test)\n", + " f1_scores_golden.append(f1_score(y_test, y_pred))\n", + "\n", + "#Print and compare the accuracy with the full model\n", + "print('Average F1 Score with Golden Feature:', sum(f1_scores_golden) / len(f1_scores_golden))\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/155/Q1.ipynb b/submissions_extracted/155/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..f89997ac9c2080ca42474bbb43771604a99b1c10 --- /dev/null +++ b/submissions_extracted/155/Q1.ipynb @@ -0,0 +1,173 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q1-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 6: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/155/Q2.ipynb b/submissions_extracted/155/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..8a75d3557503a60f51ae30f971694972343fa896 --- /dev/null +++ b/submissions_extracted/155/Q2.ipynb @@ -0,0 +1,320 @@ +{ + "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", + "# Create tensors\n", + "x = torch.tensor([1.0, 2.0, 3.0])\n", + "y = torch.randn(3)\n", + "print(\"x:\", x)\n", + "print(\"y:\", y)\n", + "\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 2. Create TensorDataset objects\n", + "a = torch.tensor([1.0, 2.0, 3.0])\n", + "b = torch.tensor([4.0, 5.0, 6.0])\n", + "\n", + "# Element-wise operations\n", + "print(\"Addition:\", a + b)\n", + "print(\"Multiplication:\", a * b)\n", + "\n", + "# Matrix multiplication\n", + "A = torch.randn(2, 3)\n", + "B = torch.randn(3, 2)\n", + "C = A @ B\n", + "\n", + "print(\"ANON_OWNER/q2-exam-data:\", C.shape)\n", + "\n", + "\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", + "test_loader = DataLoader(\n", + " test_dataset,\n", + " batch_size=32,\n", + " shuffle=False,\n", + " num_workers=2\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", + "\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 4. Print shape of one batch\n", + "print(\"Shape of x:\", x.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", + "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 2: Write your training loop here:\n", + "optimizer = torch.optim.Adam(model.parameters(), lr=0.001)\n", + "criterion = nn.CrossEntropyLoss()\n", + "\n", + "# Loop\n", + "for epoch in range(10):\n", + " train_loss = train_step(model, train_loader, criterion, optimizer)\n", + " val_loss = validate_step(model, test_loader, criterion)\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": [ + "# Task 3: Write your validation loop here:\n", + "# Loop\n", + "for epoch in range(10):\n", + " train_loss = train_step(model, train_loader, criterion, optimizer)\n", + " val_loss = validate_step(model, test_loader, criterion)\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": [ + "# Task 4: Define device, model, loss, optimizer:\n", + "class SimpleNN(nn.Module):\n", + " def __init__(self, input_dim, output_dim):\n", + " super(SimpleNN, self).__init__()\n", + " self.layer1 = nn.Linear(input_dim, 64)\n", + " self.output = nn.Linear(64, output_dim)\n", + " self.relu = nn.ReLU()\n", + "\n", + " def forward(self, x):\n", + " x = self.relu(self.layer1(x))\n", + " x = self.output(x)\n", + " return x" + ], + "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", + "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", + "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", + " X_batch = X_batch.to(device)\n", + " y_batch = y_batch.view(-1, 1).to(device)\n", + "\n", + "\n", + " outputs = model(X_batch)\n", + " loss = criterion(outputs, y_batch)\n", + " running_loss += loss.item()\n", + "\n", + " predicted = (outputs > 0.5).float()\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": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/155/Q3.ipynb b/submissions_extracted/155/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..c97832709061629f03a86d1f40306ca8a3e2a744 --- /dev/null +++ b/submissions_extracted/155/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/156/Q1.ipynb b/submissions_extracted/156/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..df505353430d2acc2276fe2529adc10a44565823 --- /dev/null +++ b/submissions_extracted/156/Q1.ipynb @@ -0,0 +1,235 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q1-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import pandas as pd\n", + "import numpy as np\n", + "import os\n", + "import matplotlib.pyplot as plt" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "p = os.path.join(path, 'Q1_data.csv')\n", + "df = pd.read_csv(p)" + ], + "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().T" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "# Task 5: Write your code here:\n", + "plt.hist(df['Delivery_Time'].dropna(),bins=50, edgecolor='black', color='green')\n", + "plt.title('Delivery time distribution')\n", + "plt.xlabel('Delivery time')\n", + "plt.ylabel('Frequency')" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "from sklearn.preprocessing import OneHotEncoder, StandardScaler" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "df_c = df.drop(['Order_ID'], axis = 1)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "# Task 2: Write your code here:\n", + "print(\"Missing values:\")\n", + "print(df_c.isnull().sum())" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "na_fl = ['Courier_Experience_yrs', 'Delivery_Time']\n", + "na_obj = ['Weather','Traffic_Level','Time_of_Day']\n", + "\n", + "df_c['Courier_Experience_yrs'] = df_c['Courier_Experience_yrs'].fillna(df_c['Courier_Experience_yrs'].mean)\n", + "df_c['Delivery_Time'] = df_c['Delivery_Time'].fillna(df_c['Delivery_Time'].mean)\n", + "\n", + "df_c = df_c.dropna(subset=na_obj)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "print(df_c.isnull().sum())" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "df_c = df_c.drop_duplicates()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "obj = [col for col in df.columns()]\n", + "oh = OneHotEncoder()" + ], + "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/156/Q2.ipynb b/submissions_extracted/156/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..443908ac14c5859531cb99498412f0688308c301 --- /dev/null +++ b/submissions_extracted/156/Q2.ipynb @@ -0,0 +1,339 @@ +{ + "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 AdamW\n", + "import matplotlib.pyplot as plt\n", + "from torch.utils.data import DataLoader, TensorDataset\n", + "from sklearn.model_selection import train_test_split" + ], + "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(\n", + " train_dataset,\n", + " batch_size=32,\n", + " shuffle=True\n", + ")\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", + "X_batch, y_batch = next(iter(train_loader))\n", + "print(X_batch.shape)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 5. Display sample images\n", + "\n", + "images, labels = next(iter(train_loader))\n", + "\n", + "# Display the first 6 images in the batch\n", + "plt.figure(figsize=(8, 4))\n", + "\n", + "for i in range(6):\n", + " plt.subplot(3, 3, i + 1)\n", + " plt.imshow(images[i].squeeze(), cmap='gray')\n", + " plt.title(f\"Label: {labels[i].item()}\")\n", + " plt.axis('off')\n", + "\n", + "plt.tight_layout()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your model class here:\n", + "class NN4Layer(nn.Module):\n", + " def __init__(self, input_dim, hidden_dimm, 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", + " z1 = self.layer1(x)\n", + " a1 = self.relu(z1)\n", + "\n", + " z2 = self.layer1(a1)\n", + " a2 = self.relu(z2)\n", + "\n", + " z3 = self.layer1(a2)\n", + " a3 = self.relu(z3)\n", + "\n", + " output = self.layer3(a3)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your training loop here:\n", + "def train_one_epoch(model, optimizer, criterion, train_loader, device):\n", + " # Set the model to training mode\n", + " model.train()\n", + "\n", + " running_loss = 0.0\n", + "\n", + " for X_batch, y_batch in train_loader:\n", + " # Move batch to the selected device\n", + " X_batch = X_batch.view(X_batch.size(0), -1).to(device)\n", + " y_batch = y_batch.to(device)\n", + "\n", + " # Forward pass\n", + " outputs = model(X_batch) # shape: (batch_size, 10)\n", + " loss = criterion(outputs, y_batch)\n", + "\n", + " # Backward pass & optimization\n", + " optimizer.zero_grad() # Clear previous gradients\n", + " loss.backward() # Compute gradients\n", + " optimizer.step() # Update model parameters\n", + "\n", + " running_loss += loss.item()\n", + "\n", + " # Average loss over all batches\n", + " avg_loss = running_loss / len(train_loader)\n", + "\n", + " return avg_loss" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your validation loop here:\n", + "def validate(model, criterion, test_loader, device):\n", + " # Set the model to evaluation mode\n", + " model.eval()\n", + "\n", + " running_loss = 0.0\n", + " correct = 0\n", + " total = 0\n", + "\n", + " with torch.no_grad():\n", + " for X_batch, y_batch in test_loader:\n", + " # Move data to device\n", + " X_batch = X_batch.view(X_batch.size(0), -1).to(device)\n", + " y_batch = y_batch.to(device)\n", + "\n", + " # Forward pass\n", + " outputs = model(X_batch) # shape: (batch_size, 10)\n", + " loss = criterion(outputs, y_batch)\n", + " running_loss += loss.item()\n", + "\n", + " # Apply Softmax to get probabilities\n", + " probabilities = F.softmax(outputs, dim=1)\n", + "\n", + " # Multiclass predictions\n", + " predicted = torch.argmax(probabilities, dim=1)\n", + "\n", + " # Accuracy calculation\n", + " correct += (predicted == y_batch).sum().item()\n", + " total += y_batch.size(0)\n", + "\n", + " avg_loss = running_loss / len(test_loader)\n", + " accuracy = correct / total\n", + "\n", + " return avg_loss, accuracy" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Define device, model, loss, optimizer:\n", + "device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n", + "\n", + "input_dim = 32*36*36\n", + "hidden_dim = 32\n", + "output_dim = 1\n", + "\n", + "learning_rate = 1e-3\n", + "criterion = nn.MSELoss()\n", + "model = NN4Layer(input_dim, hidden_dim, output_dim).to(device)\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", + "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/156/Q3.ipynb b/submissions_extracted/156/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..b85c8bc02541140585b3b5de6881b158739de04e --- /dev/null +++ b/submissions_extracted/156/Q3.ipynb @@ -0,0 +1,185 @@ +{ + "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 os\n", + "import matplotlib.pyplot as plt" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "p = os.path.join(path, 'Q3_data.csv')\n", + "df = pd.read_csv(p)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "df.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "df.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "df = df.dropna()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "df = df.drop_duplicates()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "from sklearn.preprocessing import OneHotEncoder,LabelEncoder,StandardScaler\n", + "\n", + "le = LabelEncoder()\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "s = StandardScaler()\n", + "\n", + "df = s.fit_transform(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:" + ], + "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/157/Q1.ipynb b/submissions_extracted/157/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..b1e3b87d5551ea0c6c670f371921cf348c730cab --- /dev/null +++ b/submissions_extracted/157/Q1.ipynb @@ -0,0 +1,380 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# --- 1. CORE LIBRARIES ---\n", + "import numpy as np\n", + "import pandas as pd\n", + "import matplotlib.pyplot as plt\n", + "import seaborn as sns\n", + "\n", + "# --- 2. SKLEARN: PREPROCESSING & SPLITTING ---\n", + "from sklearn.model_selection import train_test_split, StratifiedKFold, KFold, cross_val_score\n", + "from sklearn.preprocessing import StandardScaler, MinMaxScaler, OneHotEncoder, LabelEncoder, OrdinalEncoder\n", + "from sklearn.impute import SimpleImputer\n", + "from sklearn.compose import ColumnTransformer\n", + "from sklearn.pipeline import Pipeline\n", + "\n", + "# --- 3. SKLEARN: MODELS (Covers Regression & Classification) ---\n", + "from sklearn.linear_model import LinearRegression, LogisticRegression\n", + "from sklearn.ensemble import RandomForestRegressor, RandomForestClassifier\n", + "from sklearn.tree import DecisionTreeRegressor, DecisionTreeClassifier\n", + "from sklearn.dummy import DummyRegressor, DummyClassifier\n", + "\n", + "# --- 4. SKLEARN: METRICS ---\n", + "from sklearn.metrics import (mean_absolute_error, mean_squared_error, r2_score,\n", + " accuracy_score, precision_score, recall_score, f1_score,\n", + " classification_report, confusion_matrix)\n", + "\n", + "\n", + "\n", + "\n", + "# Configuration for cleaner output\n", + "import warnings\n", + "warnings.filterwarnings('ignore')\n", + "pd.set_option('display.max_columns', None) # Show all columns\n", + "print(\"Libraries Imported Successfully\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q1-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "#task 1\n", + "path = os.path.join(path,'/kaggle/input/q1-exam-data/Q1_data.csv')\n", + "df = pd.read_csv(path)\n", + "\n", + "print(f\"Dataset shape: {df.shape}\")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2:\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3:\n", + "df.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4:\n", + "df.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5:\n", + "# 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.show()\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1:\n", + "df.drop(columns=['Order_ID']) # id - names rows can misslead the model and they are not usefull for training" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2:\n", + "\n", + "df = df.dropna(subset=['Delivery_Time']) #droping missing values in the target coulmn\n", + "\n", + "#how many data are missing from each coulmn\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", + "# Define Columns by Type\n", + "# We need to treat numbers and text differently\n", + "num_cols = df.select_dtypes(include=['number']).columns\n", + "cat_cols = df.select_dtypes(include=['object', 'category']).columns\n", + "\n", + "# Create Imputers\n", + "# Strategy: 'median' for numbers (robust to outliers), 'most_frequent' for text\n", + "num_imputer = SimpleImputer(strategy='median')\n", + "cat_imputer = SimpleImputer(strategy='most_frequent')\n", + "\n", + "# --- 3. Apply Imputation ---\n", + "# We use .copy() to keep original df safe\n", + "df_clean = df.copy()\n", + "\n", + "# Fill Missing Values\n", + "df_clean[num_cols] = num_imputer.fit_transform(df[num_cols])\n", + "df_clean[cat_cols] = cat_imputer.fit_transform(df[cat_cols])\n", + "\n", + "# Verify Cleaning\n", + "print(f\"Missing values after cleaning: {df_clean.isnull().sum().sum()}\")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3:\n", + "def check_duplicates(df):\n", + " duplicates = df_clean.duplicated().sum() #sum the number of duplicate # checks the row (data sample )\n", + " print(f\"Number of Duplicate Samples: {duplicates}\")\n", + " if duplicates > 0:\n", + " print(\"Dropping Duplicates...\")\n", + " df_clean.drop_duplicates(inplace=True) #delete them\n", + " print(\"Duplicates Dropped.\")\n", + " else:\n", + " print(\"No Duplicate Samples Found.\")\n", + "\n", + "check_duplicates(df)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4:\n", + "# --- 1. Separate Features (X) and Target (y) ---\n", + "X = df_clean.drop(columns=['Delivery_Time'])\n", + "y = df_clean['Delivery_Time']\n", + "\n", + "# --- 2. Split Data ---\n", + "# Logic: If Classification -> Use Stratify. If Regression -> No Stratify.\n", + "is_classification = (y.dtype == 'object') or (y.nunique() < 20)\n", + "\n", + "if is_classification:\n", + " print(\"Detected Classification Task -> Using Stratified Split\")\n", + " X_train, X_test, y_train, y_test = train_test_split(\n", + " X, y, test_size=0.2, random_state=42, stratify=y\n", + " )\n", + "else:\n", + " print(\"Detected Regression Task -> Using Random Split\")\n", + " X_train, X_test, y_train, y_test = train_test_split(\n", + " X, y, test_size=0.2, random_state=42\n", + " )\n", + "\n", + "print(f\"Train Shape: {X_train.shape}\")\n", + "print(f\"Test Shape: {X_test.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5:\n", + "# --- 1. Update Column Lists (In case Features Changed) ---\n", + "num_features = X_train.select_dtypes(include=['number']).columns\n", + "cat_features = X_train.select_dtypes(include=['object', 'category']).columns\n", + "\n", + "# --- 2. Define Transformers ---\n", + "# Numerical: Standardize (Z-score)\n", + "scaler = StandardScaler()\n", + "\n", + "# Categorical: One-Hot Encode (handle_unknown='ignore' prevents errors on new categories)\n", + "encoder = OneHotEncoder(handle_unknown='ignore', sparse_output=False)\n", + "\n", + "# --- 3. Build Preprocessor ---\n", + "preprocessor = ColumnTransformer(\n", + " transformers=[\n", + " ('num', scaler, num_features),\n", + " ('cat', encoder, cat_features)\n", + " ],\n", + " verbose_feature_names_out=False # Keeps column names clean\n", + ")\n", + "\n", + "# --- 4. Apply Transformations ---\n", + "# Fit ONLY on Train, Transform on both\n", + "X_train_processed = preprocessor.fit_transform(X_train)\n", + "X_test_processed = preprocessor.transform(X_test)\n", + "\n", + "# Convert back to DataFrame for readability (Optional, but helpful for debugging)\n", + "feature_names = preprocessor.get_feature_names_out()\n", + "X_train_df = pd.DataFrame(X_train_processed, columns=feature_names)\n", + "X_test_df = pd.DataFrame(X_test_processed, columns=feature_names)\n", + "\n", + "print(\"Data Processed & Ready for Modeling\")\n", + "display(X_train_df.head(3))" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 6: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1:\n", + "\n", + "X = df_clean.drop(columns=['Delivery_Time'])\n", + "y = df_clean['Delivery_Time']\n", + "\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:\n", + "from sklearn.model_selection import train_test_split, KFold\n", + "\n", + "fkfold = 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", + " # 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", + " # 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": [ + "# --- Extract Feature Importance (Random Forest Only) ---\n", + "\n", + "# 1. Get the model from the pipeline\n", + "# (Assuming your pipeline step is named 'model')\n", + "rf_model = my_pipeline.named_steps['model']\n", + "\n", + "# 2. Get importance scores\n", + "importances = rf_model.feature_importances_\n", + "\n", + "# 3. Get feature names\n", + "# (If you used OneHotEncoder, this is tricky. This is a simplified safe version)\n", + "# We will use the numerical columns + generic names for categorical to avoid errors\n", + "feature_names = num_cols.tolist() + [f\"Cat_{i}\" for i in range(len(importances) - len(num_cols))]\n", + "\n", + "# 4. Create a DataFrame\n", + "feature_imp_df = pd.DataFrame({'Feature': feature_names, 'Importance': importances})\n", + "feature_imp_df = feature_imp_df.sort_values(by='Importance', ascending=False).head(10) # Top 10\n", + "\n", + "# 5. Plot\n", + "plt.figure(figsize=(10, 6))\n", + "sns.barplot(x='Importance', y='Feature', data=feature_imp_df, palette='magma')\n", + "plt.title(\"Top 10 Most Important Features\")\n", + "plt.show()\n", + "\n", + "print(\"💡 Analysis: The top feature is the biggest driver of the decision.\")" + ], + "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/157/Q2.ipynb b/submissions_extracted/157/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..3861458c415b8de6d95625e8a5a57dfa4e1af517 --- /dev/null +++ b/submissions_extracted/157/Q2.ipynb @@ -0,0 +1,238 @@ +{ + "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 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()}\")\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, dtype=torch.float32)\n", + "X_test = torch.tensor(X_test.shape, dtype=torch.float32)\n", + "y_train = torch.tensor(y_train.shape, dtype=torch.float32)\n", + "y_test = torch.tensor(y_test.shape, 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", + "# Create Dataloaders to train and test data in batches\n", + "train_loader = DataLoader(train_dataset, batch_size=32, shuffle=True)\n", + "test_loader = DataLoader(test_dataset, batch_size=32, shuffle=False)\n", + "\n", + "# Print dataset sizes\n", + "print(\"Train dataset:\", len(train_dataset))\n", + "print(\"Test dataset:\", len(test_dataset))\n", + "\n", + "# Get the first batch from the training DataLoader\n", + "X_batch, y_batch = next(iter(train_loader))\n", + "print(f\"Training batch input shape: {X_batch.shape}\")\n", + "print(f\"Training batch labels shape: {y_batch.shape}\")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 3. Create DataLoaders\n", + "\n", + "\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": [ + "# 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" + ], + "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/157/Q3.ipynb b/submissions_extracted/157/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..36f43d4f91ae69a7e89eefcf4aff33da0862ba59 --- /dev/null +++ b/submissions_extracted/157/Q3.ipynb @@ -0,0 +1,201 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "import numpy as np\n", + "import pandas as pd\n", + "import matplotlib.pyplot as plt\n", + "import seaborn as sns\n", + "\n", + "# --- 2. SKLEARN: PREPROCESSING & SPLITTING ---\n", + "from sklearn.model_selection import train_test_split, StratifiedKFold, KFold, cross_val_score\n", + "from sklearn.preprocessing import StandardScaler, MinMaxScaler, OneHotEncoder, LabelEncoder, OrdinalEncoder\n", + "from sklearn.impute import SimpleImputer\n", + "from sklearn.compose import ColumnTransformer\n", + "from sklearn.pipeline import Pipeline\n", + "\n", + "# --- 3. SKLEARN: MODELS (Covers Regression & Classification) ---\n", + "from sklearn.linear_model import LinearRegression, LogisticRegression\n", + "from sklearn.ensemble import RandomForestRegressor, RandomForestClassifier\n", + "from sklearn.tree import DecisionTreeRegressor, DecisionTreeClassifier\n", + "from sklearn.dummy import DummyRegressor, DummyClassifier\n", + "\n", + "# --- 4. SKLEARN: METRICS ---\n", + "from sklearn.metrics import (mean_absolute_error, mean_squared_error, r2_score,\n", + " accuracy_score, precision_score, recall_score, f1_score,\n", + " classification_report, confusion_matrix)\n", + "\n", + "\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", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1:\n", + "Qpath = os.path.join(path, '/kaggle/input/q3-exam-data/Q3_data.csv')\n", + "df = pd.read_csv(Qpath)\n", + "\n", + "print(f\"Dataset shape: {df.shape}\")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2:\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3:\n", + "df.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4:\n", + "df.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Do we have missing values?\n", + "df.isnull().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() #sum the number of duplicate # checks the row (data sample )\n", + " print(f\"Number of Duplicate Samples: {duplicates}\")\n", + " if duplicates > 0:\n", + " print(\"Dropping Duplicates...\")\n", + " df.drop_duplicates(inplace=True) #delete them\n", + " print(\"Duplicates Dropped.\")\n", + " else:\n", + " print(\"No Duplicate Samples Found.\")\n", + "\n", + "check_duplicates(df)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/158/Q1.ipynb b/submissions_extracted/158/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..1669a48fd5d591865f431f43b111439d80696afe --- /dev/null +++ b/submissions_extracted/158/Q1.ipynb @@ -0,0 +1,179 @@ +{ + "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: pd.read_csv(csv_path)\n", + "\n", + " pd.read_csv(csv_path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: df.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: df.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: df.columns.drop(\"Delivery_time\")" + ], + "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: #there is no missing values" + ], + "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: np.array(y)\n", + " m = len(y)" + ], + "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: KFold(n_splits=n_splits, shuffle=True, random_state=42)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: 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/158/Q2.ipynb b/submissions_extracted/158/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..b781052b8ce677413ea723f8d09271ab2f5f4f25 --- /dev/null +++ b/submissions_extracted/158/Q2.ipynb @@ -0,0 +1,206 @@ +{ + "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", + "numpy arrays (X_test.to(device)).cpu().numpy()\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 2. Create TensorDataset objects\n", + "x = torch.tensor([1.0, 2.0, 3.0])\n", + "y = torch.randn(3)\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 3. Create DataLoaders\n", + "\n", + "torch.tensor(X_train, dtype=torch.float32)\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: # First linear layer: input features -> hidden layer\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" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: model.train()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: model.eval()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Define device, model, loss, optimizer:\n", + "\n", + " #we can do it like def __init__(self, input_dim, hidden_dim, output_dim):\n", + " super(NN4Layer, self).__init__() but i didn't work for me" + ], + "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: Wplt.figure(figsize=(7, 5))" + ], + "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/158/Q3.ipynb b/submissions_extracted/158/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..a57b3d72d984ee43b578d83452790a5e551b227e --- /dev/null +++ b/submissions_extracted/158/Q3.ipynb @@ -0,0 +1,171 @@ +{ + "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: pd.read_csv(csv_path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: df.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: df.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: check_missing_values(df)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: df.isnull().sum()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: df.isnull().sum()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: scaler.fit_transform(df[numerical_cols])" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5:" + ], + "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: KFold(n_splits=n_splits, shuffle=True, random_state=42)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: 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/159/Q1.ipynb b/submissions_extracted/159/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..a40f66d66c02e8650c8093093311cf91dfedba76 --- /dev/null +++ b/submissions_extracted/159/Q1.ipynb @@ -0,0 +1,336 @@ +{ + "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", + "from tqdm import tqdm\n", + "import os\n", + "import kagglehub\n", + "%matplotlib inline\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q1-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "Q1_data_path = os.path.join(path,'Q1_data.csv')\n", + "df_Q1_data_path = pd.read_csv(Q1_data_path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "df_Q1_data_path.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "df_Q1_data_path.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "df_Q1_data_path.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "def check_target_distribution(df_Q1_data_path, Delivery_Time):\n", + " df_Q1_data_path[Delivery_Time].hist(bins=30, edgecolor='black')\n", + "\n", + " plt.title(f\"Target Distribution ({Delivery_Time})\")\n", + " plt.xlabel(Delivery_Time)\n", + " plt.ylabel(\"..\")\n", + " plt.grid(False)\n", + "\n", + " plt.show()\n", + "\n", + "check_target_distribution(df_Q1_data_path, \"Delivery_Time\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "df_clean=df_Q1_data_path.drop(columns='Order_ID', axis=1)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "df_clean.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "def check_missing_values(df_clean):\n", + " missing_values = df_clean.isnull().sum()\n", + " print(\"Missing Values per Column:\")\n", + " print(missing_values[missing_values > 0])\n", + " if missing_values.any():\n", + " print(\"\\nHandle Missing Values as needed.\")\n", + " else:\n", + " print(\"\\nNo Missing Values Found.\")\n", + "\n", + "check_missing_values(df_clean)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "def check_missing_values(df_clean):\n", + " missing_values = df_clean.isnull().sum()\n", + " print(\"Missing Values per Column:\")\n", + " print(missing_values[missing_values > 0])\n", + " if missing_values.any():\n", + " print(\"\\nHandle Missing Values as needed.\")\n", + " else:\n", + " print(\"\\nNo Missing Values Found.\")\n", + "\n", + "check_missing_values(df_clean)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "categorical_cols = df_clean.select_dtypes(include=[\"object\"]).columns\n", + "\n", + "print(\"Categorical Columns:\", list(categorical_cols))" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "def check_duplicates(df_clean):\n", + " duplicates = df_clean.duplicated().sum()\n", + " print(f\"Number of Duplicate Samples: {duplicates}\")\n", + " if duplicates > 0:\n", + " print(\"Dropping Duplicates...\")\n", + " df_clean.drop_duplicates(inplace=True)\n", + " print(\"Duplicates Dropped.\")\n", + " else:\n", + " print(\"No Duplicate Samples Found.\")\n", + "\n", + "check_duplicates(df_clean)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "from sklearn.preprocessing import LabelEncoder\n", + "\n", + "label_encoders = {}\n", + "for col in categorical_cols:\n", + " le = LabelEncoder()\n", + " df_clean[col] = le.fit_transform(df_clean[col])\n", + " label_encoders[col] = le\n", + "\n", + "df_clean" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "# Apply feature scaling for all features (Use StandardScaler)\n", + "from sklearn.preprocessing import StandardScaler\n", + "\n", + "numerical_cols = df_clean.select_dtypes(include=[\"int64\", \"float64\"]).columns.drop(\"Delivery_Time\")\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", + "# Check for target imbalance and state if it is imbalanced or not\n", + "import seaborn as sns\n", + "def check_target_imbalance(df_clean, target_column):\n", + " print(\"Target Distribution:\")\n", + " print(df_clean[target_column].value_counts(normalize=True))\n", + " sns.countplot(x=df_clean[target_column])\n", + " plt.title(\"Target Distribution\")\n", + " plt.show()\n", + "\n", + "check_target_imbalance(df_clean, \"Delivery_Time\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "X = df_clean.drop(\"Delivery_Time\", axis=1).astype(float)\n", + "y = df_clean['Delivery_Time'].astype(float)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 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 as sklearn_mae, r2_score\n", + "n_splits = 5\n", + "kf = KFold(n_splits=n_splits, shuffle=True, random_state=42)\n", + "lr_losses = []\n", + "lr_mae = []\n", + "lr_r2 = []\n", + "def gradient_descent(X, y, learning_rate, n_iters=500):\n", + " m, n = X.shape # m rows, n columns (dimensions)\n", + " theta = np.zeros(n) # initialize a zeros weight vector with n dimensions\n", + " losses = []\n", + " for _ in tqdm(range(n_iters), desc=\"Training 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", + " return theta, losses\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", + " r2 = r2_score(y_test, y_pred)\n", + "\n", + " # Store results\n", + " lr_losses.append(losses)\n", + "\n", + " lr_r2.append(r2)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "model.eval()\n", + "with torch.no_grad():\n", + "\n", + " predictions = model(X_test.to(device)).cpu().numpy()\n", + "mae = mean_absolute_error(y_test.numpy(), predictions)\n", + "\n", + "print(\"Model Evaluation\")\n", + "print(f\" MAE: ${mae:.2f}\")\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/159/Q2.ipynb b/submissions_extracted/159/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..f0683251655b2c141c578286461ff19d928afd55 --- /dev/null +++ b/submissions_extracted/159/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", + "import numpy as np\n", + "from PIL import Image\n", + "from sklearn.model_selection import train_test_split\n", + "import torch.nn.functional as F\n", + "import kagglehub\n", + "import pandas as pd\n", + "import torch\n", + "import torch.nn as nn\n", + "from torch.optim import AdamW\n", + "import matplotlib.pyplot as plt\n", + "import torch.nn.functional as F\n", + "from torch.utils.data import DataLoader, TensorDataset\n", + "from sklearn.model_selection import train_test_split\n", + "from sklearn.preprocessing import StandardScaler, LabelEncoder\n", + "\n", + "\n", + "# Load Labels\n", + "labels_df = pd.read_csv(os.path.join(path, \"labels.csv\"))\n", + "img_dir = os.path.join(path, \"images\")\n", + "\n", + "images = []\n", + "ages = []\n", + "\n", + "# Load Images and Resize\n", + "print(\"Loading images...\")\n", + "for index, row in labels_df.iterrows():\n", + " img_name = row.iloc[0]\n", + " age = row.iloc[1]\n", + " img_path = os.path.join(img_dir, img_name)\n", + "\n", + " if os.path.exists(img_path):\n", + " img = Image.open(img_path).convert('RGB')\n", + " img_array = np.array(img) / 255.0 # Normalize pixel values to [0, 1]\n", + " images.append(img_array)\n", + " ages.append(age)\n", + "\n", + "X = np.array(images)\n", + "y = np.array(ages)\n", + "\n", + "# Transpose image dimensions to match PyTorch format (N, C, H, W)\n", + "X = np.transpose(X, (0, 3, 1, 2))\n", + "\n", + "# Split Data\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n", + "\n", + "print(f\"X_train shape: {X_train.shape}\")\n", + "print(f\"X_test shape: {X_test.shape}\")\n", + "print(f\"y_train shape: {y_train.shape}\")\n", + "print(f\"y_test shape: {y_test.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 1. Convert Numpy arrays to PyTorch Tensors\n", + "import torch\n", + "from torch.utils.data import DataLoader, TensorDataset\n", + "import torch.nn as nn\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\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" + ], + "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", + "# Get the first batch from the training DataLoader\n", + "X_batch, y_batch = next(iter(train_loader))\n", + "print(f\"Training batch input shape: {X_batch.shape}\")\n", + "print(f\"Training batch labels shape: {y_batch.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 5. Display sample images\n", + "# Get one batch of images and labels, copy pastable\n", + "import matplotlib.pyplot as plt\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", + "\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", + " 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 = 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.view(X_batch.size(0), -1).to(device) #very important step, it flatten the pic , u can use flatten here instead\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, zero it out\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) # loss / num of batchs\n", + "\n", + " return avg_loss\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your validation loop here,\n", + "#Task 4: Define device, model, loss, optimizer\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) # dim 1 is do prob based on classes\n", + "\n", + " # Multiclass predictions\n", + " predicted = torch.argmax(probabilities, dim=1) #maximim prob (indexes thats why argmax)\n", + "\n", + " # Accuracy calculation\n", + " correct += (predicted == y_batch).sum().item()\n", + " total += y_batch.size(0) # num of samples\n", + "\n", + "\n", + "\n", + " avg_loss = running_loss / len(test_loader)\n", + " accuracy = correct / total\n", + "\n", + " return avg_loss, accuracy\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Define device, model, loss, optimizer:\n", + "# in the cell above with validation" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Start training for 20 epochs:\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 (vector)\n", + "hidden_dim = 14 # Design choice\n", + "output_dim = 10 # Digits 0–9 has to be number of dp\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", + "total_params = sum(p.numel() for p in model.parameters() if p.requires_grad)\n", + "print(f\"\\nTotal trainable parameters: {total_params}\")\n", + "num_epochs = 20\n", + "learning_rate = 0.001\n", + "\n", + "# Define criterion (loss function) - using CrossEntropyLoss as model now outputs logits\n", + "criterion = nn.CrossEntropyLoss()\n", + "# Define optimizer\n", + "optimizer = AdamW(model.parameters(), learning_rate)" + ], + "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/159/Q3.ipynb b/submissions_extracted/159/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..00d8c3f60d0b3b3346ac6a64b05c8dee2fb20474 --- /dev/null +++ b/submissions_extracted/159/Q3.ipynb @@ -0,0 +1,348 @@ +{ + "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", + "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_data_path = pd.read_csv(Q3_path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "df_Q3_data_path.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "df_Q3_data_path.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "df_Q3_data_path.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "def check_missing_values(df_Q3_data_path):\n", + " missing_values = df_Q3_data_path.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_path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "def check_duplicates(df_Q3_data_path):\n", + " duplicates = df_Q3_data_path.duplicated().sum()\n", + " print(f\"Number of Duplicate Samples: {duplicates}\")\n", + " if duplicates > 0:\n", + " print(\"Dropping Duplicates...\")\n", + " df_Q3_data_path.drop_duplicates(inplace=True)\n", + " print(\"Duplicates Dropped.\")\n", + " else:\n", + " print(\"No Duplicate Samples Found.\")\n", + "\n", + "check_duplicates(df_Q3_data_path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "categorical_cols = df_Q3_data_path.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_Q3_data_path.select_dtypes(include=[\"int64\", \"float64\"]).columns.drop(\"Target\")\n", + "\n", + "scaler = StandardScaler()\n", + "df_Q3_data_path[numerical_cols] = scaler.fit_transform(df_Q3_data_path[numerical_cols])\n", + "df_Q3_data_path.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "import seaborn as sns\n", + "def check_target_imbalance(df_Q3_data_path, Target):\n", + " print(\"Target Distribution:\")\n", + " print(df_Q3_data_path[Target].value_counts(normalize=True))\n", + " sns.countplot(x=df_Q3_data_path[Target])\n", + " plt.title(\"Target Distribution\")\n", + " plt.show()\n", + "\n", + "check_target_imbalance(df_Q3_data_path, \"Target\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "X = df_Q3_data_path.drop(\"Target\", axis=1).astype(float)\n", + "y = df_Q3_data_path['Target'].astype(float)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "def one_hot_encode(y, num_classes): # from scratch , usually we wont do it from scratch\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)) #rows m, col 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, put 1 in a specific index\n", + " one_hot[i, class_label] = 1\n", + "\n", + " return one_hot" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "def softmax(z): # (m,k) samples, classes\n", + " z_shifted = z\n", + " exp_z = np.exp(z_shifted)\n", + " return exp_z / np.sum(exp_z, axis=1, keepdims=True) #op shape (m,k) -> og diminsions" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Categorical cross entropy loss function using NumPy\n", + "def categorical_cross_entropy(y, y_hat):\n", + " epsilon = 1e-15\n", + " y_hat = np.clip(y_hat, epsilon, 1 - epsilon)\n", + "\n", + " loss = -np.mean(np.sum(y * np.log(y_hat), axis=1))\n", + " return loss" + ], + "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 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 tqdm import tqdm\n", + "from CatBoost import CatBoostClassifier\n", + "\n", + "def gradient_descent(X, y, num_classes, lr, n_iters=1000):\n", + " # Get the number of samples (m) and number of features (n)\n", + " m, n = X.shape\n", + "\n", + " # Initialize weight matrix with shape (n, num_classes)\n", + " theta = np.zeros((n, num_classes)) # shape is dofferent here\n", + "\n", + " # One-hot encode the labels\n", + " y_onehot = one_hot_encode(y, num_classes)\n", + "\n", + " losses = []\n", + "\n", + " for _ in tqdm(range(n_iters), desc=\"Training Multiclass Logistic Regression\"):\n", + " # Calculate the logits z\n", + " z = np.dot(X, theta)\n", + "\n", + " # Get class probabilities using softmax instead of sigmoid\n", + " y_pred = softmax(z)\n", + "\n", + " # Compute the gradient of Categorical Cross-Entropy with Softmax\n", + " # ∂J/∂θ = (1/m) * X^T * (y_pred - y_onehot)\n", + " gradient = np.dot(X.T, (y_pred - y_onehot)) / m\n", + "\n", + " # Update weights\n", + " theta -= lr * gradient\n", + "\n", + " # Track loss\n", + " loss = categorical_cross_entropy(y_onehot, y_pred)\n", + " losses.append(loss)\n", + "\n", + " return theta, losses\n", + "n_splits = 3\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)\n", + "print(\"Performance:\")\n", + "\n", + "print(f\" Accuracy: {np.mean(sr_results['acc']):.4f}\")\n", + "print(f\" F1-Score: {np.mean(sr_results['f1']):.4f}\")\n", + "\n", + "models = {\n", + " \"CatBoost\": CatBoostClassifier(\n", + " verbose=0,\n", + " n_estimators=200,\n", + " max_depth=4\n", + " )\n", + "}\n", + "for model_name in results:\n", + " print(f\"\\n{model_name}:\")\n", + " # Print the average of each evaluation metric across folds\n", + " print(f\" Accuracy: {np.mean(results[model_name]['accuracy']):.4f}\")\n", + " print(f\" F1-Score: {np.mean(results[model_name]['f1']):.4f}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/16/Q1.ipynb b/submissions_extracted/16/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..e6d8727a30f9106f2059d193b45f66d1db5600f7 --- /dev/null +++ b/submissions_extracted/16/Q1.ipynb @@ -0,0 +1,484 @@ +{ + "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", + "ANON_OWNER_path = os.path.join(path, 'Q1_data.csv')\n", + "df_ANON_OWNER = pd.read_csv(ANON_OWNER_path)\n", + "print(f\"Dataset shape: {df_ANON_OWNER.shape}\")\n", + "df_ANON_OWNER.head()\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "csv_path = os.path.join(path, \"Q1_data.csv\")\n", + "df = pd.read_csv(csv_path)\n", + "df = df.drop(columns=\"Unnamed: 0\", axis=1)\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "df_ANON_OWNER.info()" + ], + "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", + "plt.title(f\"Target Distribution ({target_column})\")\n", + "plt.xlabel(target_column)\n", + "plt.ylabel(\"Frequency\")\n", + "plt.grid(False)\n", + "plt.show()\n", + "check_target_distribution(df, \"Sales\")\n" + ], + "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", + "plt.title(f\"Target Distribution ({target_column})\")\n", + "plt.xlabel(target_column)\n", + "plt.ylabel(\"Frequency\")\n", + "plt.grid(False)\n", + "plt.show()\n", + "check_target_distribution(df, \"Sales\")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "df_ANON_OWNER.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "missing_percentage = (df_ANON_OWNER.isnull().sum() / len(df_ANON_OWNER)) * 100\n", + "missing_data = pd.DataFrame({\n", + "'Column': missing_percentage.index,\n", + "'Missing_Percentage': missing_percentage.values\n", + "})\n", + "missing_data = missing_data[missing_data['Missing_Percentage'] > 0].sort_values('Missing_Percentage', ascending=False)\n", + "print(\"Missing Data Analysis:\")\n", + "missing_data.head(10)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\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 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", + "# 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\n", + "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", + "# Initialize weight matrix with shape (n, num_classes)\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 Multiclass Logistic Regression\"):\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": [ + "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", + "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", + "for fold_idx, (train_index, test_index) in enumerate(skf.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=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", + "accuracy = accuracy_score(y_test, y_pred)\n", + "f1 = f1_score(y_test, y_pred, average='macro')\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 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", + "n_splits = 5 # K\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": [ + "n_splits = 5 # K=5 Folds\n", + "# 5-Fold Cross-Validation, shuffled\n", + "kf = KFold(n_splits=n_splits, shuffle=True, random_state=42)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "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", + "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", + "theta, losses = gradient_descent(X_train.values, y_train.values, learning_rate=0.1, n_iters=500)\n", + "# Validate\n", + "y_pred = np.dot(X_test.values, theta)\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", + "# 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 2,3,4,5: Write your code here:\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:\n", + "{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": [ + "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\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", + "\"CatBoost\": CatBoostRegressor(verbose=0)\n", + "}\n", + "# Storage for results\n", + "all_results = {}\n", + "for name in models:\n", + "all_results[name] = {'mse': [], 'rmse': [], 'r2': []}\n", + "kf = KFold(n_splits=5, shuffle=True, random_state=42)\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", + "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", + "# Calculate metrics\n", + "mse = sklearn_mse(y_test, y_pred)\n", + "rmse = np.sqrt(mse)\n", + "r2 = r2_score(y_test, y_pred)\n", + "# Store results\n", + "all_results[model_name][\"mse\"].append(mse)\n", + "all_results[model_name][\"rmse\"].append(rmse)\n", + "all_results[model_name][\"r2\"].append(r2)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "# Calculate the majority class baseline\n", + "majority_class = y.value_counts().idxmax()\n", + "baseline_pred = [majority_class] * len(y)\n", + "# Evaluate the baseline\n", + "baseline_accuracy = accuracy_score(y, baseline_pred)\n", + "baseline_precision = precision_score(y, baseline_pred, average='weighted', zero\n", + "baseline_recall = recall_score(y, baseline_pred, average='weighted', zero_divis\n", + "baseline_f1 = f1_score(y, baseline_pred, average='weighted', zero_division=0)\n", + "print(f\"Baseline Accuracy (majority class): {baseline_accuracy:.4f}\")\n", + "print(f\"Baseline Precision: {baseline_precision:.4f}\")\n", + "print(f\"Baseline Recall: {baseline_recall:.4f}\")\n", + "print(f\"Baseline F1-Score: {baseline_f1:.4f}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: 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 catboost import CatBoostRegressor\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", + "\"CatBoost\": CatBoostRegressor(verbose=0)\n", + "}\n", + "# Storage for results\n", + "all_results = {}\n", + "for name in models:\n", + "all_results[name] = {'mse': [], 'rmse': [], 'r2': []}\n", + "kf = KFold(n_splits=5, shuffle=True, random_state=42)\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", + "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", + "# Calculate metrics\n", + "mse = sklearn_mse(y_test, y_pred)\n", + "rmse = np.sqrt(mse)\n", + "r2 = r2_score(y_test, y_pred)\n", + "# Store results\n", + "all_results[model_name][\"mse\"].append(mse)\n", + "all_results[model_name][\"rmse\"].append(rmse)\n", + "all_results[model_name][\"r2\"].append(r2)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: 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 catboost import CatBoostRegressor\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", + "\"CatBoost\": CatBoostRegressor(verbose=0)\n", + "}\n", + "# Storage for results\n", + "all_results = {}\n", + "for name in models:\n", + "all_results[name] = {'mse': [], 'rmse': [], 'r2': []}\n", + "kf = KFold(n_splits=5, shuffle=True, random_state=42)\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", + "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", + "# Calculate metrics\n", + "mse = sklearn_mse(y_test, y_pred)\n", + "rmse = np.sqrt(mse)\n", + "r2 = r2_score(y_test, y_pred)\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": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/16/Q2.ipynb b/submissions_extracted/16/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..cf3bf8da80e6498433fb1de1803d4c8ef62cac2f --- /dev/null +++ b/submissions_extracted/16/Q2.ipynb @@ -0,0 +1,418 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q2-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import os\n", + "import pandas as pd\n", + "import numpy as np\n", + "from PIL import Image\n", + "from sklearn.model_selection import train_test_split\n", + "\n", + "# Load Labels\n", + "labels_df = pd.read_csv(os.path.join(path, \"labels.csv\"))\n", + "img_dir = os.path.join(path, \"images\")\n", + "\n", + "images = []\n", + "ages = []\n", + "\n", + "# Load Images and Resize\n", + "print(\"Loading images...\")\n", + "for index, row in labels_df.iterrows():\n", + " img_name = row.iloc[0]\n", + " age = row.iloc[1]\n", + " img_path = os.path.join(img_dir, img_name)\n", + "\n", + " if os.path.exists(img_path):\n", + " img = Image.open(img_path).convert('RGB')\n", + " img_array = np.array(img) / 255.0 # Normalize pixel values to [0, 1]\n", + " images.append(img_array)\n", + " ages.append(age)\n", + "\n", + "X = np.array(images)\n", + "y = np.array(ages)\n", + "\n", + "# Transpose image dimensions to match PyTorch format (N, C, H, W)\n", + "X = np.transpose(X, (0, 3, 1, 2))\n", + "\n", + "# Split Data\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n", + "\n", + "print(f\"X_train shape: {X_train.shape}\")\n", + "print(f\"X_test shape: {X_test.shape}\")\n", + "print(f\"y_train shape: {y_train.shape}\")\n", + "print(f\"y_test shape: {y_test.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 1. Convert Numpy arrays to PyTorch Tensors\n", + "a = torch.tensor([1.0, 2.0, 3.0])\n", + "b = torch.tensor([4.0, 5.0, 6.0])\n", + "# Element-wise operations\n", + "print(\"Addition:\", a + b)\n", + "print(\"Multiplication:\", a * b)\n", + "# Matrix multiplication\n", + "A = torch.randn(2, 3)\n", + "B = torch.randn(3, 2)\n", + "C = A @ B\n", + "print(\"Matrix multiplication result shape:\", C.shape)\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 2. Create TensorDataset objects\n", + "\n", + "import torch\n", + "#\n", + "1️⃣\n", + " Flatten - Convert any shape to (batch_size, features)\n", + "x = torch.randn(32, 3, 28, 28)\n", + "x_flat = x.flatten(start_dim=1)\n", + "print(\"Flatten:\", x_flat.shape) # (32, 2352)\n", + "#\n", + "2️⃣\n", + " Squeeze - Remove dimensions with size 1\n", + "x = torch.randn(1, 3, 28, 28)\n", + "x_sq = x.squeeze()\n", + "print(\"Squeeze:\", x_sq.shape) # (3, 28, 28)\n", + "#\n", + "3️⃣\n", + " Unsqueeze - Add a new dimension of size 1\n", + "x = torch.randn(3, 28, 28)\n", + "x_unsq = x.unsqueeze(0)\n", + "print(\"Unsqueeze:\", x_unsq.shape) # (1, 3, 28, 28)\n", + "#\n", + "4️⃣\n", + " View - Reshape freely while keeping same number of elements\n", + "x = torch.randn(32, 28, 28, 3)\n", + "x_view = x.view(32, -1) # Flatten all except batch\n", + "print(\"View:\", x_view.shape) # (32, 28*28*3)\n", + "Flatten: torch.Size([32, 2352])\n", + "Squeeze: torch.Size([3, 28, 28])\n", + "Unsqueeze: torch.Size([1, 3, 28, 28])\n", + "View: torch.Size([32, 2352])\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 3. Create DataLoaders\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", + "# 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", + "# Print dataset sizes\n", + "print(\"Train dataset:\", len(train_dataset))\n", + "print(\"Test dataset:\", len(test_dataset))\n", + "# Get the first batch from the training DataLoader\n", + "X_batch, y_batch = next(iter(train_loader))\n", + "print(f\"Training batch input shape: {X_batch.shape}\")\n", + "print(f\"Training batch labels shape: {y_batch.shape}\")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 4. Print shape of one batch\n", + "\n", + "class NN4Layer(nn.Module):\n", + " def __init__(self, input_dim, hidden_dim, output_dim):\n", + " super(NN4Layer, self).__init__()\n", + " # First linear layer: input features -> hidden layer\n", + " self.layer1 = nn.Linear(input_dim, hidden_dim)\n", + " # Second linear layer: hidden layer -> hidden layer\n", + " self.layer2 = nn.Linear(hidden_dim, hidden_dim)\n", + " # Third linear layer: hidden layer -> hidden layer\n", + " self.layer3 = nn.Linear(hidden_dim, hidden_dim)\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", + " # Defines how input data flows through the network\n", + " def forward(self, x):\n", + " # First hidden layer\n", + " a1 = self.relu(self.layer1(x))\n", + " # Second hidden layer\n", + " a2 = self.relu(self.layer2(a1))\n", + " # Third hidden layer\n", + " a3 = self.relu(self.layer3(a2))\n", + " # Output layer (raw scores / logits)\n", + " output = self.layer4(a3) # we said we'll use softmax, where is it? ¯\\(ツ)/¯\n", + " return outpu" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 5. Display sample images\n", + "\n", + "from torchvision.datasets import MNIST\n", + "from torchvision.transforms.functional import to_tensor\n", + "# Training dataset\n", + "train_dataset = MNIST(\n", + "root='./datasets',\n", + "train=True,\n", + "transform=to_tensor,\n", + "download=True\n", + ")\n", + "# Testing dataset\n", + "test_dataset = MNIST(\n", + "root='./datasets',\n", + "train=False,\n", + "transform=to_tensor,\n", + "download=True\n", + "# Dataset storage path\n", + "# Use training data\n", + "# Convert images to tensors\n", + "# Download if not available\n", + "# Dataset storage path\n", + "# Use test data\n", + "# Convert images to tensors\n", + "# Download if not available\n", + ")\n", + "# print one sample from the dataset\n", + "# Each sample consists of an image tensor and its label\n", + "sample_image, sample_label = train_dataset[0]\n", + "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": [ + "# Task 1: Write your model class here:\n", + "def train_one_epoch(model, optimizer, criterion, train_loader, device):\n", + " # Set the model to training mode\n", + " model.train()\n", + " running_loss = 0.0\n", + " for X_batch, y_batch in train_loader:\n", + " # Move batch to the selected device\n", + " X_batch = X_batch.to(device) # shape: (batch_size, num_features)\n", + " y_batch = y_batch.to(device) # shape: (batch_size,)\n", + " # Forward pass (outputs are logits)\n", + " outputs = model(X_batch) # shape: (batch_size, num_classes)\n", + " loss = criterion(outputs, y_batch)\n", + " # Backward pass & optimization\n", + " optimizer.zero_grad() # Clear previous gradients\n", + " loss.backward() # Compute gradients\n", + " optimizer.step() # Update model parameters\n", + " running_loss += loss.item()\n", + " # Average loss over all batches\n", + " avg_loss = running_loss / len(train_loader)\n", + " return avg_loss" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your training loop here:\n", + "def validate(model, criterion, test_loader, device):\n", + " # Set the model to evaluation mode\n", + " model.eval()\n", + " running_loss = 0.0\n", + " correct = 0\n", + " total = 0\n", + " with torch.no_grad():\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", + " # Forward pass\n", + " outputs = model(X_batch) # shape: (batch_size, num_classes)\n", + " loss = criterion(outputs, y_batch)\n", + " running_loss += loss.item()\n", + " # Apply Softmax to get probabilities\n", + " probabilities = F.softmax(outputs, dim=1)\n", + " # Pick the classes with highest probabilities\n", + " predicted = torch.argmax(probabilities, dim=1)\n", + " # Accuracy calculation\n", + " correct += (predicted == y_batch).sum().item()\n", + " total += y_batch.size(0)\n", + " avg_loss = running_loss / len(test_loader)\n", + " accuracy = correct / total\n", + " return avg_loss, accuracy" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your validation loop here:\n", + "device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n", + "# Model parameters\n", + "input_dim = X_train.shape[1] # Number of tabular features\n", + "hidden_dim = 14 # Design choice\n", + "output_dim = 4 # Weather classes: Rainy, Sunny, Cloudy, Snowy\n", + "# Instantiate model\n", + "model = NN4Layer(input_dim, hidden_dim, output_dim).to(device)\n", + "# Print the model architecture\n", + "print(\"Model Architecture:\\n\")\n", + "print(model)\n", + "# Calculate the total number of trainable parameters\n", + "total_params = sum(p.numel() for p in model.parameters() if p.requires_grad)\n", + "print(f\"\\nTotal trainable parameters: {total_params}\")\n", + "Model Architecture:\n", + "NN4Layer(\n", + " (layer1): Linear(in_features=10, out_features=14, bias=True)\n", + " (layer2): Linear(in_features=14, out_features=14, bias=True)\n", + " (layer3): Linear(in_features=14, out_features=14, bias=True)\n", + " (layer4): Linear(in_features=14, out_features=4, bias=True)\n", + " (relu): ReLU()\n", + ")\n", + "Total trainable parameters: 634" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Define device, model, loss, optimizer:\n", + "num_epochs = 20\n", + "learning_rate = 0.001\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", + "# Run Training\n", + "train_losses = []\n", + "val_losses = []\n", + "val_accuracies = []\n", + "print('Starting Training...')\n", + "for epoch in range(num_epochs):\n", + "# Train one epoch\n", + "train_loss = train_one_epoch(model, optimizer, criterion, train_loader, device)\n", + "# Validate\n", + "val_loss, val_accuracy = validate(model, criterion, test_loader, device)\n", + "train_losses.append(train_loss)\n", + "val_losses.append(val_loss)\n", + "val_accuracies.append(val_accuracy)\n", + "print(f'Epoch [{epoch+1}/{num_epochs}], Train Loss: {train_loss:.4f}, Val Loss: {val_loss:.4f}, Val Accuracy: {val_accuracy\n", + "print('Training Complete!')" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Start training for 20 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.title('Loss over Epochs')\n", + "plt.xlabel('Epoch')\n", + "plt.ylabel('Loss')\n", + "plt.legend()\n", + "plt.tight_layout()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "import torch\n", + "import torch.nn as nn\n", + "# Create a linear layer: 3 input features -> 1 output\n", + "linear = nn.Linear(in_features=3, out_features=1)\n", + "# Example input: batch of 4 samples, each with 3 features\n", + "x = torch.randn(4, 3)\n", + "# Forward through the layer\n", + "y = linear(x)\n", + "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": [ + "# Task 2 (Bonus): Write your code here:\n", + "class NN2Layer(nn.Module):\n", + "def __init__(self, input_dim, hidden_dim):\n", + "super(NN2Layer, self).__init__()\n", + "# input_dim = num of features, hidden_dim = num of neurons\n", + "self.layer1 = nn.Linear(input_dim, hidden_dim)\n", + "# hidden_dim = num of neurons, Output for binary classification is 1\n", + "self.layer2 = nn.Linear(hidden_dim, 1)\n", + "# non-linearity activation function\n", + "self.relu = nn.ReLU()\n", + "# output activation function\n", + "self.sigmoid = nn.Sigmoid()\n", + "# forward pass\n", + "def forward(self, x):\n", + "z1 = self.layer1(x)\n", + "a1 = self.relu(z1)\n", + "z2 = self.layer2(a1)\n", + "a2 = self.sigmoid(z2)\n", + "return a2" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/160/Q1.ipynb b/submissions_extracted/160/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..508983f74777fc11cdd020382bffe12fc024ee10 --- /dev/null +++ b/submissions_extracted/160/Q1.ipynb @@ -0,0 +1,365 @@ +{ + "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": [ + "csv_path = os.path.join(path, \"Q1_data.csv\")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\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", + "X = df.drop(\"Order_ID\", axis=1)\n", + "X\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": [ + "\n", + "df_clean = df.dropna(subset=['Delivery_Time'])\n", + "df_clean" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "df_filled = df_clean['Delivery_Time'].fillna(\"unknown\")\n", + "df_filled" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "missing_values = df_filled.isnull().sum()\n", + "print(\"Missing Values per Column:\")\n", + "print(missing_values[missing_values > 0])" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "def check_duplicates(df):\n", + " duplicates = df.duplicated().sum()\n", + " 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))" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "from sklearn.preprocessing import LabelEncoder\n", + "\n", + "label_encoders = {}\n", + "for col in categorical_cols:\n", + " le = LabelEncoder()\n", + " df[col] = le.fit_transform(df[col])\n", + " label_encoders[col] = le\n", + "df\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()\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 6: Write your code here:\n", + "def check_target_imbalance(df, target_column):\n", + " print(\"Target Distribution:\")\n", + " 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.model_selection import StratifiedKFold\n", + "from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score\n", + "from sklearn.ensemble import RandomForestRegressor\n", + "from sklearn.model_selection import train_test_split, KFold\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "target_column = \"Delivery_Time\"\n", + "X = df.drop(target_column, axis=1)\n", + "y = df[target_column]" + ], + "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", + "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", + "\n", + "scaler = StandardScaler()\n", + "X_scaled = scaler.fit_transform(X)\n", + "\n", + "kf = KFold(n_splits=5, shuffle=True, random_state=42)\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 RandomForestClassifier\n", + "model = RandomForestRegressor()\n", + "\n", + "\n", + "model.fit(X_train, y_train)\n", + "\n", + "print(\"Model trained!\")\n", + "\n", + "print(f\"MAE : {np.mean(mae_scores):.2f}\")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "# Feature importance\n", + "feature_importance = pd.DataFrame({\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/160/Q2.ipynb b/submissions_extracted/160/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..519fcd4d6537d29c379659f7f22622286aac3f3e --- /dev/null +++ b/submissions_extracted/160/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": [ + "import torch\n", + "import torch.nn as nn\n", + "from torchvision.datasets import MNIST\n", + "from torch.utils.data import DataLoader\n", + "from torch.optim import Adam\n", + "from torchvision.transforms.functional import to_tensor\n", + "import torch.nn.functional as F\n", + "import matplotlib.pyplot as plt" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 1. Convert Numpy arrays to PyTorch Tensors\n", + "# 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", + ")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 2. Create TensorDataset objects\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": [ + "# 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", + "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", + "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", + "class NN3Layer(nn.Module):\n", + "\n", + " def __init__(self, input_dim, hidden_dim, output_dim):\n", + " super(NN3Layer, self).__init__()\n", + "\n", + " # First layer = input\n", + " self.layer1 = nn.Linear(input_dim, hidden_dim)\n", + "\n", + " # Second layer = hidden\n", + " self.layer2 = nn.Linear(hidden_dim, hidden_dim)\n", + "\n", + " # Third layer which is also hidden\n", + " self.layer3 = nn.Linear(hidden_dim, output_dim)\n", + "\n", + " # Output layer\n", + " self.layer4 = nn.Linear(hidden_dim, output_dim)\n", + "\n", + " # ReLU activation\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\n", + " output = self.layer4(a2)\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()\n", + " loss.backward()\n", + " optimizer.step()\n", + "\n", + " running_loss += loss.item()\n", + "\n", + " # Average loss over all batches\n", + " avg_loss = running_loss / len(train_loader)\n", + "\n", + " return avg_loss" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your validation loop here:\n", + "def validate(model, criterion, test_loader, device):\n", + " # Set the model to evaluation mode\n", + " model.eval()\n", + "\n", + " running_loss = 0.0\n", + " correct = 0\n", + " total = 0\n", + "\n", + " with torch.no_grad():\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", + "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": [ + "# 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='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/160/Q3.ipynb b/submissions_extracted/160/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..2f438c4dd84be60e3770795e599e039ce83b7168 --- /dev/null +++ b/submissions_extracted/160/Q3.ipynb @@ -0,0 +1,269 @@ +{ + "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" + ], + "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": [ + "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": [ + "# Drop rows with missing stat values\n", + "df_clean = df.dropna().copy()" + ], + "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": [ + "df.describe()" + ], + "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))" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "from sklearn.preprocessing import LabelEncoder\n", + "\n", + "label_encoders = {}\n", + "for col in categorical_cols:\n", + " le = LabelEncoder()\n", + " df[col] = le.fit_transform(df[col])\n", + " label_encoders[col] = le\n", + "df\n" + ], + "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", + "standard_scaler = StandardScaler() # Instantiate StandardScaler\n", + "data_standard_scaled = standard_scaler.fit_transform(df) # Apply fit_transform\n", + "\n", + "print('\\nData after scaling:\\n', data_standard_scaled) #show after scaling" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "# 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).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,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" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "# Feature importance\n", + "feature_importance = pd.DataFrame({\n", + " 'feature': feature_cols,\n", + " 'importance': model.feature_importances_\n", + "}).sort_values('importance', ascending=False)\n", + "\n", + "plt.figure(figsize=(10, 6))\n", + "plt.barh(feature_importance['feature'], feature_importance['importance'])\n", + "plt.xlabel('Importance')\n", + "plt.title('Feature Importance')\n", + "plt.gca().invert_yaxis()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/161/Q1.ipynb b/submissions_extracted/161/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..3e3dcc376ffa87ff26041012078fd5816581191e --- /dev/null +++ b/submissions_extracted/161/Q1.ipynb @@ -0,0 +1,275 @@ +{ + "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", + "# 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_path = os.path.join(path, 'Q1_data.csv')\n", + "df_Q1_data = pd.read_csv(Q1_data_path_path)\n", + "\n", + "print(f\"Shape: {df_Q1_data.shape}\")\n", + "df_Q1_data.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "df_Q1_data.head" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "df_Q1_data.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "df_Q1_data.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "plt.figure(figsize=(10, 5))\n", + "plt.hist(df_Q1_data['Delivery_Time'].dropna(), bins=50, edgecolor='black')\n", + "plt.title('Delivery_Time Distribution')\n", + "plt.xlabel('Delivery_Time')\n", + "plt.ylabel('Frequency')\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "df_Q1_data.drop(columns=['Order_ID'])\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "df_Q1_data.dropna()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "def check_duplicates(df_Q1_data):\n", + "\n", + " #TODO: get duplicated data using pandas\n", + " duplicates = df_Q1_data.duplicated().sum()\n", + "\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", + "from sklearn.preprocessing import LabelEncoder\n", + "\n", + "labels = [' Weather ', 'Traffic_Level', 'Time_of_Day ', 'Vehicle_Type ']\n", + "encoder = LabelEncoder()\n", + "encoded = encoder.fit_transform(labels)\n", + "print(\"Labels:\", labels)\n", + "print(\"Encoded:\", encoded) # [1, 2, 1, 0, 2]\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "from sklearn.preprocessing import StandardScaler\n", + "import numpy as np\n", + "\n", + "data = np.array([[1, 100, 50],\n", + " [2, 200, 60],\n", + " [3, 300, 70],\n", + " [4, 400, 80],\n", + " [5, 500, 90]])\n", + "\n", + "scaler = StandardScaler()\n", + "scaled = scaler.fit_transform(data)\n", + "\n", + "print(\"Original:\\n\", data)\n", + "print(\"\\nScaled (mean≈0, std≈1):\\n\", scaled)\n", + "print(\"\\nMeans:\", scaled.mean(axis=0))\n", + "print(\"Stds:\", scaled.std(axis=0))\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "from sklearn.preprocessing import StandardScaler\n", + "\n", + "# Pick only the numerical columns, NOT the target\n", + "numerical_cols = df_Q1_data.select_dtypes(include=[\"number\"]).columns.drop(\"Order_ID\")\n", + "\n", + "scaler = StandardScaler()\n", + "\n", + "df_Q1_data[numerical_cols] = scaler.fit_transform(df_Q1_data[numerical_cols])\n", + "\n", + "df_Q1_data.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 6: Write your code here:\n", + "def check_target_imbalance(df_Q1_data, target_column):\n", + " print(\"Target Distribution:\")\n", + "\n", + " df_Q1_data[target_column].hist()\n", + " plt.show()\n", + "\n", + "check_target_imbalance(df_Q1_data, \"Delivery_Time\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "feature_cols = ['Order_ID', 'Distance_km ', 'Courier_Experience_yrs', 'Preparation_Time_min' , 'Vehicle_Type ']\n", + "target = 'Delivery_Time'\n", + "X = df_Q1_data\n", + "y = df_Q1_data\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)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "plt.figure(figsize=(10, 5))\n", + "plt.hist(df_Q1_data['Delivery_Time'].dropna(), bins=50, edgecolor='black')\n", + "plt.title('Delivery_Time Distribution')\n", + "plt.xlabel('Delivery_Time')\n", + "plt.ylabel('Frequency')\n", + "plt.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=50, edgecolor='black')\n", + "plt.title('Delivery_Time Distribution')\n", + "plt.xlabel('Delivery_Time')\n", + "plt.ylabel('Frequency')\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/161/Q2.ipynb b/submissions_extracted/161/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..f8f83ed562b8f2babcbaaf0ee4b4a195c01a1926 --- /dev/null +++ b/submissions_extracted/161/Q2.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/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", + "import torch.nn as nn\n", + "from torch.optim import Adam\n", + "import matplotlib.pyplot as plt\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", + "X_train = torch.tensor(X_train, dtype=torch.float32)\n", + "X_test = torch.tensor(X_test, dtype=torch.float32)\n", + "y_train = torch.tensor(y_train, dtype=torch.float32)\n", + "y_test = torch.tensor(y_test, dtype=torch.float32)\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 2. Create TensorDataset objects\n", + "\n", + "train_dataset = TensorDataset(X_train, y_train)\n", + "test_dataset = TensorDataset(X_test, y_test)\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 3. Create DataLoaders\n", + "\n", + "train_loader = DataLoader(train_dataset, batch_size=32, shuffle=True)\n", + "test_loader = DataLoader(test_dataset, batch_size=32, shuffle=False)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 4. Print shape of one batch\n", + "\n", + "print(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": [ + "# 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 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", + "\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", + "\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" + ], + "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", + "device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n", + "optimizer = AdamW(model.parameters(), learning_rate)\n", + "criterion = nn.CrossEntropyLoss()\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 = 15\n", + "model.train()\n", + "\n", + "learning_rate = 0.001\n", + "\n", + "\n", + "criterion = nn.CrossEntropyLoss()\n", + "\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" + ], + "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/161/Q3.ipynb b/submissions_extracted/161/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..e4821ee4bbbb8b8e6c3fad428b671b84942911de --- /dev/null +++ b/submissions_extracted/161/Q3.ipynb @@ -0,0 +1,255 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "import os\n", + "import pandas as pd\n", + "\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", + "# 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_path = os.path.join(path, 'Q3_data.csv')\n", + "df_Q3_data = pd.read_csv(Q3_data_path_path)\n", + "\n", + "print(f\"Shape: {df_Q3_data.shape}\")\n", + "df_Q3_data.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "df_Q3_data.head" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "df_Q3_data.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "df_Q3_data.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "df_Q3_data.isnull().sum()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "def check_duplicates(df_Q3_data):\n", + "\n", + " #TODO: get duplicated data using pandas\n", + " duplicates = df_Q3_data.duplicated().sum()\n", + "\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 need\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "#no need\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "import matplotlib.pyplot as plt\n", + "def check_target_imbalance(df_Q3_data, target_column):\n", + " print(\"Target Distribution:\")\n", + "\n", + " df_Q3_data[target_column].hist()\n", + " plt.show()\n", + "\n", + "check_target_imbalance(df_Q3_data, \"Target\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\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}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code 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 1: Write your code here:\n", + "train_losses = []\n", + "val_losses = []\n", + "val_accuracies = []\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:" + ], + "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/162/Q1.ipynb b/submissions_extracted/162/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..d7514fbc4d167a50b8e9eadeb0ad8a842e1485c0 --- /dev/null +++ b/submissions_extracted/162/Q1.ipynb @@ -0,0 +1,338 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q1-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "\n", + "import seaborn as sns\n", + "import matplotlib.pyplot as plt\n", + "import os\n", + "\n", + "# 1. Read the dataset Q1_data.csv\n", + "# Assuming the file is named Q1_data.csv inside the downloaded path\n", + "file_path = os.path.join(path, \"Q1_data.csv\")\n", + "df = pd.read_csv(file_path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "\n", + "print(\"--- First 5 Rows ---\")\n", + "print(df.head())" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "# 3. Display dataset information\n", + "print(\"\\n--- Dataset Info ---\")\n", + "df.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "# 4. Show statistical description\n", + "print(\"\\n--- Statistical Description ---\")\n", + "print(df.describe())" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "# 5. Plot the target distribution (delivery_time)\n", + "plt.figure(figsize=(10, 6))\n", + "sns.histplot(df['delivery_time'], kde=True, color='skyblue')\n", + "plt.title('Distribution of Delivery Time')\n", + "plt.xlabel('Delivery Time')\n", + "plt.ylabel('Frequency')\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "df.drop(\"Order_ID\",axis=1)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "df.isna().sum()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "df = df.dropna(subset=['Weather', 'Traffic_Level', 'Time_of_Day','Courier_Experience_yrs','Delivery_Time'])" + ], + "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", + "df.drop_duplicates()" + ], + "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", + "\n", + "# Using pandas get_dummies for One-Hot Encoding\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", + "from sklearn.preprocessing import StandardScaler\n", + "\n", + "scaler = StandardScaler()\n", + "\n", + "# We scale only the features, not the target (delivery_time)\n", + "features = df.drop(columns=['Delivery_Time'])\n", + "target = df['Delivery_Time']\n", + "\n", + "scaled_features = scaler.fit_transform(features)\n", + "df_scaled = pd.DataFrame(scaled_features, columns=features.columns)" + ], + "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.ensemble import RandomForestRegressor\n", + "from sklearn.model_selection import KFold, cross_val_score\n", + "import numpy as np\n", + "\n", + "# Splitting features and target\n", + "X = df_scaled # Scaled features from Part 2\n", + "y = target # delivery_time" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:\n", + "# Initialize the model\n", + "rf_model = RandomForestRegressor(n_estimators=100, random_state=42)\n", + "\n", + "# Define KFold cross-validation\n", + "# n_splits=5 is a standard choice for a balance between bias and variance\n", + "kf = KFold(n_splits=5, shuffle=True, random_state=42)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Calculate MAE across folds\n", + "# Note: scikit-learn uses negative MAE for its scoring API\n", + "mae_scores = cross_val_score(\n", + " rf_model, X, y,\n", + " scoring='neg_mean_absolute_error',\n", + " cv=kf\n", + ")\n", + "\n", + "# Convert negative scores back to positive\n", + "mae_scores = -mae_scores\n", + "\n", + "# 4. Print the averaged score\n", + "print(f\"--- Model Evaluation ---\")\n", + "print(f\"MAE per fold: {mae_scores}\")\n", + "print(f\"Average MAE across all folds: {mae_scores.mean():.2f} minutes\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "import matplotlib.pyplot as plt\n", + "import pandas as pd\n", + "\n", + "# Assuming 'model' is your trained estimator and 'X_train' is your features DataFrame\n", + "def plot_feature_importance(model, X_train):\n", + " # Create a Series with feature importances and index as feature names\n", + " importances = pd.Series(model.feature_importances_, index=X_train.columns)\n", + "\n", + " # Sort importances in descending order\n", + " importances = importances.sort_values(ascending=True)\n", + "\n", + " plt.figure(figsize=(10, 6))\n", + " importances.plot(kind='barh', color='skyblue')\n", + " plt.title('Feature Importance')\n", + " plt.xlabel('Importance Score')\n", + " plt.ylabel('Features')\n", + " plt.grid(axis='x', linestyle='--', alpha=0.7)\n", + " plt.tight_layout()\n", + " plt.show()\n", + "\n", + "# Call the function\n", + "plot_feature_importance(model, X_train)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "import seaborn as sns\n", + "\n", + "def plot_prediction_distribution(y_pred):\n", + " plt.figure(figsize=(10, 6))\n", + "\n", + " # Using Seaborn for a smoother distribution curve (KDE)\n", + " sns.histplot(y_pred, kde=True, bins=30, color='salmon')\n", + "\n", + " plt.title('Distribution of Predicted Delivery Times')\n", + " plt.xlabel('Predicted Delivery Time (minutes)')\n", + " plt.ylabel('Frequency')\n", + " plt.grid(axis='y', linestyle='--', alpha=0.5)\n", + " plt.show()\n", + "\n", + "# Assuming 'y_pred' contains your model's predictions\n", + "plot_prediction_distribution(y_pred)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:\n", + "import numpy as np\n", + "from sklearn.model_selection import KFold\n", + "from sklearn.ensemble import RandomForestRegressor\n", + "from catboost import CatBoostRegressor\n", + "from sklearn.metrics import mean_absolute_error\n", + "\n", + "# Initialize KFold\n", + "kf = KFold(n_splits=5, shuffle=True, random_state=42)\n", + "\n", + "mae_scores = []\n", + "\n", + "# Assuming X and y are your features and target\n", + "for train_index, val_index in kf.split(X):\n", + " X_train, X_val = X.iloc[train_index], X.iloc[val_index]\n", + " y_train, y_val = y.iloc[train_index], y.iloc[val_index]\n", + "\n", + " # 1. Initialize the models\n", + " rf_model = RandomForestRegressor(n_estimators=100, random_state=42)\n", + " cat_model = CatBoostRegressor(iterations=500, learning_rate=0.1, depth=6, verbose=0)\n", + "\n", + " # 2. Train both models\n", + " rf_model.fit(X_train, y_train)\n", + " cat_model.fit(X_train, y_train)\n", + "\n", + " # 3. Get predictions from both\n", + " rf_preds = rf_model.predict(X_val)\n", + " cat_preds = cat_model.predict(X_val)\n", + "\n", + " # 4. Average the predictions\n", + " ensemble_preds = (rf_preds + cat_preds) / 2\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/162/Q2.ipynb b/submissions_extracted/162/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..ae7117ac6cabffbb3d703777f09f84ca5074dbdb --- /dev/null +++ b/submissions_extracted/162/Q2.ipynb @@ -0,0 +1,512 @@ +{ + "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", + "# Loading\n", + "df_laeb = pd.read_csv(os.path.join(path, \"labels.csv\"))\n", + "\n", + "\n", + "imgeing_directory = os.path.join(path, \"images\")\n", + "\n", + "images = []\n", + "ages = []\n", + "\n", + "# Load Images and Resize\n", + "print(\"Loading images...\")\n", + "\n", + "\n", + "for index, row in df_laeb.iterrows():\n", + "\n", + "\n", + " img_name = row.iloc[0]\n", + "\n", + "\n", + " age = row.iloc[1]\n", + "\n", + "\n", + " img_path = os.path.join(imgeing_directory, img_name)\n", + "\n", + "\n", + "\n", + " if os.path.exists(img_path):\n", + "\n", + "\n", + " img = Image.open(img_path).convert('RGB')\n", + "\n", + "\n", + " imgening_array = np.array(img) / 255.0 # Normalize [0, 1]\n", + "\n", + "\n", + " images.append(imgening_array)\n", + "\n", + "\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", + "\n", + "# 1. Convert to Tensors\n", + "# useing float32 for features (X) and float32 for regression targets (y)\n", + "\n", + "\n", + "X_train_t = torch.tensor(X_train, dtype=torch.float32)\n", + "\n", + "\n", + "\n", + "y_train_t = torch.tensor(y_train, dtype=torch.float32).view(-1, 1) # Reshape to (N, 1)\n", + "\n", + "\n", + "\n", + "\n", + "X_test_t = torch.tensor(X_test, dtype=torch.float32)\n", + "\n", + "\n", + "\n", + "\n", + "y_test_t = torch.tensor(y_test, dtype=torch.float32).view(-1, 1)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 2. Creating TensorDataset object\n", + "\n", + "# 2. Create Datasets\n", + "\n", + "\n", + "train_dataset = TensorDataset(X_train_t, y_train_t)\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\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", + "batch_size = 32\n", + "\n", + "\n", + "train_loader = DataLoader(train_dataset, batch_size=batch_size, shuffle=True)\n", + "\n", + "\n", + "test_loader = DataLoader(test_dataset, batch_size=batch_size, shuffle=False)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 4. Print shape of one batch\n", + "\n", + "data_iter = iter(train_loader)\n", + "\n", + "\n", + "images_batch, labels_batch = next(data_iter)\n", + "\n", + "\n", + "\n", + "print(f\"Batch Image shape: {images_batch.shape}\") # Expected: [32, 3, H, W]\n", + "\n", + "\n", + "print(f\"Batch Label shape: {labels_batch.shape}\") # Expected: [32, 1]\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 5. Display sample images\n", + "\n", + "# 5. Display a few images\n", + "def show_images(imgs, labels):\n", + " plt.figure(figsize=(12, 5))\n", + " for i in range(4):\n", + " plt.subplot(1, 4, i + 1)\n", + " # Transpose back from (C, H, W) to (H, W, C) for Matplotlib\n", + " img = imgs[i].numpy().transpose((1, 2, 0))\n", + " plt.imshow(img)\n", + " plt.title(f\"Age: {int(labels[i].item())}\")\n", + " plt.axis('off')\n", + " plt.show()\n", + "\n", + "show_images(images_batch, labels_batch)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your model class here:\n", + "import torch.nn as nn\n", + "import torch.optim as optim\n", + "\n", + "class AgeEstimationModel(nn.Module):\n", + " def __init__(self, input_shape):\n", + "\n", + "\n", + " super(AgeEstimationModel, self).__init__()\n", + "\n", + "\n", + " # Channels * Height * Width\n", + " self.input_dim = input_shape[0] * input_shape[1] * input_shape[2]\n", + "\n", + " self.network = nn.Sequential(\n", + " nn.Flatten(),\n", + "\n", + "\n", + " nn.Linear(self.input_dim, 512),\n", + "\n", + "\n", + " nn.ReLU(),\n", + "\n", + "\n", + " nn.Linear(512, 256),\n", + "\n", + "\n", + "\n", + " nn.ReLU(),\n", + "\n", + "\n", + " nn.Linear(256, 64),\n", + "\n", + " nn.ReLU(),\n", + "\n", + "\n", + " nn.Linear(64, 1) # Final output for regression\n", + " )\n", + "\n", + " def forward(self, x):\n", + " return self.network(x)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your training loop here:\n", + "\n", + "\n", + "def train_step(model, loader, criterion, optimizer, device):\n", + " model.train()\n", + " running_loss = 0.0\n", + "\n", + "\n", + " for images, labels in loader:\n", + "\n", + "\n", + " images, labels = images.to(device), labels.to(device)\n", + "\n", + " optimizer.zero_grad()\n", + "\n", + "\n", + " outputs = model(images)\n", + "\n", + "\n", + " loss = criterion(outputs, labels)\n", + "\n", + "\n", + " loss.backward()\n", + "\n", + "\n", + " optimizer.step()\n", + "\n", + " running_loss += loss.item()\n", + "\n", + "\n", + " return running_loss / len(loader)\n", + "\n", + "def val_step(model, loader, criterion, device):\n", + "\n", + "\n", + " model.eval()\n", + "\n", + " running_loss = 0.0\n", + "\n", + " with torch.no_grad():\n", + "\n", + "\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()\n", + " return running_loss / len(loader)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your validation loop here:\n", + "# Setup Device\n", + "device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n", + "\n", + "\n", + "# Initialize Model (using shape of first image in X_train)\n", + "\n", + "\n", + "input_shape = X_train.shape[1:]\n", + "\n", + "\n", + "model = AgeEstimationModel(input_shape).to(device)\n", + "\n", + "# Define Loss and Optimizer\n", + "\n", + "\n", + "criterion = nn.MSELoss()\n", + "\n", + "\n", + "optimizer = optim.Adam(model.parameters(), lr=0.001)\n", + "\n", + "# Training Loop\n", + "\n", + "\n", + "num_epochs = 20\n", + "history = {\"training_loss\": [], \"valdition_loss\": []}\n", + "\n", + "\n", + "\n", + "print(f\"Starting training on {device}...\")\n", + "for epoch in range(num_epochs):\n", + " train_loss = train_step(model, train_loader, criterion, optimizer, device)\n", + " val_loss = val_step(model, test_loader, criterion, device)\n", + "\n", + " history[\"trainining_loss\"].append(train_loss)\n", + " history[\"valadtion_loss\"].append(val_loss)\n", + "\n", + " print(f\"Epoch [{epoch+1}/{num_epochs}] - Training Loss: {train_loss:.4f}, Valdtion Loss: {val_loss:.4f}\")\n", + "\n", + "print(\"Training accoblish!\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Define device, model, loss, optimizer:\n", + "import torch.nn as nn\n", + "import torch.optim as optim\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", + "# We pass the shape of one image (C, H, W) to calculate the input dimension\n", + "input_shape = X_train.shape[1:]\n", + "model = AgeEstimationModel(input_shape).to(device)\n", + "\n", + "# 3. Define Loss Function (Regression)\n", + "criterion = nn.MSELoss()\n", + "\n", + "# 4. Define Optimizer\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", + "# Storage for metrics\n", + "history = {\"train_loss\": [], \"val_loss\": []}\n", + "num_epochs = 20\n", + "\n", + "print(\"Starting Training...\")\n", + "\n", + "for epoch in range(num_epochs):\n", + " # --- Training Phase ---\n", + " model.train()\n", + " train_running_loss = 0.0\n", + " for images, labels in train_loader:\n", + " images, labels = images.to(device), labels.to(device)\n", + "\n", + " # Zero the gradients\n", + " optimizer.zero_grad()\n", + "\n", + " # Forward pass\n", + " outputs = model(images)\n", + " loss = criterion(outputs, labels)\n", + "\n", + " # Backward pass and optimize\n", + " loss.backward()\n", + " optimizer.step()\n", + "\n", + " train_running_loss += loss.item() * images.size(0)\n", + "\n", + " epoch_train_loss = train_running_loss / len(train_loader.dataset)\n", + "\n", + " # --- Validation Phase ---\n", + " model.eval()\n", + " val_running_loss = 0.0\n", + " with torch.no_grad(): # No need to track gradients during val\n", + " for images, labels in test_loader:\n", + " images, labels = images.to(device), labels.to(device)\n", + " outputs = model(images)\n", + " loss = criterion(outputs, labels)\n", + " val_running_loss += loss.item() * images.size(0)\n", + "\n", + " epoch_val_loss = val_running_loss / len(test_loader.dataset)\n", + "\n", + " # Save history\n", + " history[\"train_loss\"].append(epoch_train_loss)\n", + " history[\"val_loss\"].append(epoch_val_loss)\n", + "\n", + " # Print progress\n", + " print(f\"Epoch [{epoch+1}/{num_epochs}] | Train Loss: {epoch_train_loss:.4f} | Val Loss: {epoch_val_loss:.4f}\")\n", + "\n", + "print(\"Training Done!\")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "import matplotlib.pyplot as plt\n", + "\n", + "def plot_loss(history):\n", + " plt.figure(figsize=(10, 6))\n", + " plt.plot(history['train_loss'], label='Training Loss', color='blue', lw=2)\n", + " plt.plot(history['val_loss'], label='Validation Loss', color='orange', lw=2)\n", + " plt.title('Training and Validation Loss Over Epochs', fontsize=14)\n", + " plt.xlabel('Epochs')\n", + " plt.ylabel('Mean Squared Error (MSE)')\n", + " plt.legend()\n", + " plt.grid(True, linestyle='--', alpha=0.6)\n", + " plt.show()\n", + "\n", + "plot_loss(history)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2 (Bonus): Write your code here:\n", + "def plot_predictions(model, loader, device, num_images=5):\n", + " model.eval()\n", + " images, labels = next(iter(loader))\n", + " images, labels = images.to(device), labels.to(device)\n", + "\n", + " with torch.no_grad():\n", + " outputs = model(images)\n", + "\n", + " # Move back to CPU for plotting\n", + " images = images.cpu()\n", + " labels = labels.cpu()\n", + " outputs = outputs.cpu()\n", + "\n", + " plt.figure(figsize=(15, 5))\n", + " for i in range(num_images):\n", + " plt.subplot(1, num_images, i + 1)\n", + "\n", + " # Reshape image: (C, H, W) -> (H, W, C)\n", + " img = images[i].permute(1, 2, 0).numpy()\n", + "\n", + " actual_age = labels[i].item()\n", + " pred_age = outputs[i].item()\n", + "\n", + " plt.imshow(img)\n", + " plt.title(f\"Actual: {actual_age:.1f}\\nPred: {pred_age:.1f}\",\n", + " color=(\"green\" if abs(actual_age - pred_age) < 5 else \"red\"))\n", + " plt.axis('off')\n", + " plt.tight_layout()\n", + " plt.show()\n", + "\n", + "# Run the visualization\n", + "plot_predictions(model, test_loader, device)" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/162/Q3.ipynb b/submissions_extracted/162/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..51d5668827d91a04b79f7169da7d5cbf55cef136 --- /dev/null +++ b/submissions_extracted/162/Q3.ipynb @@ -0,0 +1,392 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [], + "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", + "import pandas as pd\n", + "import os\n", + "\n", + "# Define the file path (joining the downloaded path with the filename)\n", + "\n", + "\n", + "file_path = os.path.join(path, \"Q3_data.csv\")\n", + "\n", + "# 1. Read the dataset\n", + "\n", + "\n", + "df = pd.read_csv(file_path)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "print(\"First 5 Rows \")\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 (Check for nulls and data types)\n", + "\n", + "\n", + "print(\"\\nDataset Information \")\n", + "df.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "# 4. Show statistical description\n", + "print(\"\\nStatistical Summary\")\n", + "display(df.describe())" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "from sklearn.preprocessing import StandardScaler, LabelEncoder\n", + "\n", + "# 1. Handle Missing Values\n", + "# For credit data, filling with median is often safer than mean to avoid outlier influence\n", + "df = df.fillna(df.median(numeric_only=True))\n", + "# For categorical columns, fill with \"Unknown\"\n", + "df = df.fillna(\"Na\")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "\n", + "# 2. Check and remove duplicates\n", + "duplicate_count = df.duplicated().sum()\n", + "\n", + "\n", + "\n", + "print(f\"duplicate rows: {duplicate_count}\")\n", + "\n", + "\n", + "if duplicate_count > 0:\n", + " df = df.drop_duplicates()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "# 3. Encode Categorical Variables\n", + "# Identify non-numeric columns (excluding the target 'target' if present)\n", + "\n", + "cat_cols = df.select_dtypes(include=['object']).columns\n", + "\n", + "\n", + "le = LabelEncoder()\n", + "\n", + "\n", + "for col in cat_cols:\n", + "\n", + "\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", + "# 4. Apply Feature Scaling (StandardScaler)\n", + "# We scale features to have mean=0 and variance=1\n", + "scaler = StandardScaler()\n", + "\n", + "features = df.drop(columns=['Target']) # Assuming 'target' is the label name\n", + "\n", + "\n", + "target = df['Target']\n", + "\n", + "scaled_features = scaler.fit_transform(features)\n", + "\n", + "\n", + "df_scaled = pd.DataFrame(scaled_features, columns=features.columns)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "# 5. Check for Target Imbalance\n", + "imbalance_ratio = target.value_counts(normalize=True) * 100\n", + "\n", + "\n", + "print(\"\\nTarget Distribution\")\n", + "\n", + "\n", + "print(imbalance_ratio)\n", + "\n", + "if imbalance_ratio.min() < 20:\n", + "\n", + " print(\"\\nResult: The dataset is IMBALANCED. We may need SMOTE or class weights later.\")\n", + "\n", + "\n", + "else:\n", + "\n", + "\n", + " print(\"\\nResult: The dataset balance.\")" + ], + "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", + "# 1. Split the dataset to features(X) and target(y)\n", + "X = df_scaled\n", + "\n", + "# Using the scaled features from Part 2\n", + "y = target # The target labels (0 or 1)\n" + ], + "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", + "\n", + "from sklearn.model_selection import StratifiedKFold\n", + "from sklearn.metrics import f1_score\n", + "import numpy as np\n", + "\n", + "# 2.StratifiedKFold\n", + "# 5 folds robust validation\n", + "\n", + "\n", + "skf = StratifiedKFold(n_splits=5,\n", + " shuffle=True, random_state=42)\n", + "\n", + "f1_scores = []\n", + "\n", + "\n", + "\n", + "print(\"Cross-Validation\")\n", + "\n", + "# 3. Train CatBoost and Evaluate'\n", + "\n", + "for fold, (train_index, test_index) in enumerate(skf.split(X, y)):\n", + " X_train, X_test = X.iloc[train_index],\n", + "\n", + " X.iloc[test_index]\n", + " y_train, y_test = y.iloc[train_index],\n", + "\n", + " y.iloc[test_index]\n", + "\n", + " # Initialize CatBoost\n", + " # We use silent=True to prevent the log from becoming too long\n", + "\n", + "\n", + " model = CatBoostClassifier(iterations=500, learning_rate=0.05, depth=6, silent=True)\n", + "\n", + " # Train the model\n", + "\n", + "\n", + " model.fit(X_train, y_train)\n", + "\n", + " # Predict\n", + " y_pred = model.predict(X_test)\n", + "\n", + "\n", + " # 4. Evaluate using F1-Score\n", + " score = f1_score(y_test, y_pred)\n", + "\n", + "\n", + " f1_scores.append(score)\n", + "\n", + "\n", + " print(f\"Fold {fold + 1} F1-Score: {score:.4f}\")\n", + "\n", + "# 5. Print the averaged score\n", + "\n", + "print(\"-\" * 30)\n", + "\n", + "print(f\"Average F1-Score: {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", + "import seaborn as sns\n", + "\n", + "# 1. Extract feature importance from the trained model\n", + "\n", + "\n", + "feature_importance = model.get_feature_importance()\n", + "\n", + "\n", + "\n", + "feature_names = X.columns\n", + "\n", + "# Create a DataFrame for easy sorting and plotting\n", + "\n", + "\n", + "data_df = pd.DataFrame({\n", + " 'Feature': feature_names,\n", + " 'Importance': feature_importance\n", + "}).sort_values(by='Importance', ascending=False)\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "# 2. Plot Feature Importance\n", + "plt.figure(figsize=(10, 8))\n", + "sns.barplot(x='Importance', y='Feature', data=data_df.head(15), palette='magma')\n", + "plt.title('Top 15 Predictive Features (The Search for the Golden Feature)')\n", + "plt.xlabel('Importance Score')\n", + "plt.ylabel('Anonymized Feature Name')\n", + "plt.show()\n", + "\n", + "# 3. Identify and print the 'Golden Feature'\n", + "golden_feature = data_df.iloc[0]['Feature']\n", + "golden_score = data_df.iloc[0]['Importance']\n", + "\n", + "print(f\"--- MISSION COMPLETE ---\")\n", + "print(f\"The Golden Feature is: {golden_feature}\")\n", + "print(f\"Importance Score: {golden_score:.2f}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:\n", + "# 1. Create new X with ONLY the golden feature\n", + "# (Assuming 'golden_feature' was identified as 'P_2' or similar in Part 4)\n", + "X_golden = df_scaled[[golden_feature]]\n", + "y = target\n", + "\n", + "# 2. Run the same KFold loop with this single feature\n", + "skf_solo = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)\n", + "solo_f1_scores = []\n", + "\n", + "print(f\"Retraining model using ONLY: {golden_feature}...\")\n", + "\n", + "for train_index, test_index in skf_solo.split(X_golden, y):\n", + " X_train_s, X_test_s = X_golden.iloc[train_index], X_golden.iloc[test_index]\n", + " y_train_s, y_test_s = y.iloc[train_index], y.iloc[test_index]\n", + "\n", + " # Using the same parameters as before\n", + " solo_model = CatBoostClassifier(iterations=500, learning_rate=0.05, depth=6, silent=True)\n", + " solo_model.fit(X_train_s, y_train_s)\n", + "\n", + " # Predict and evaluate\n", + " y_pred_s = solo_model.predict(X_test_s)\n", + " solo_f1_scores.append(f1_score(y_test_s, y_pred_s))\n", + "\n", + "# 3. Compare Results\n", + "avg_full_f1 = np.mean(f1_scores) # From Part 3\n", + "avg_solo_f1 = np.mean(solo_f1_scores)\n", + "\n", + "print(\"\\n\" + \"=\"*30)\n", + "print(f\"Full Model F1-Score: {avg_full_f1:.4f}\")\n", + "print(f\"Golden Feature Solo: {avg_solo_f1:.4f}\")\n", + "print(f\"Performance Retained: {(avg_solo_f1 / avg_full_f1) * 100:.2f}%\")\n", + "print(\"=\"*30)\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/163/Q1.ipynb b/submissions_extracted/163/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..45c32ec0973f02510065b5e8f0c68cbc704b1e8a --- /dev/null +++ b/submissions_extracted/163/Q1.ipynb @@ -0,0 +1,259 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q1-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "import os\n", + "import pandas as pd\n", + "Q1_path = os.path.join(path, 'Q1_data.csv')\n", + "df_Q1 = pd.read_csv(Q1_path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "df_Q1.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "df_Q1.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "df_Q1.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "import matplotlib.pyplot as plt\n", + "plt.figure(figsize=(10, 5))\n", + "plt.hist(df_Q1['Delivery_Time'].dropna(), bins=30, edgecolor='black')\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "df_Q1=df_Q1.drop('Order_ID',axis=1)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "# Drop rows with missing stat values\n", + "df_clean = df_Q1.dropna().copy()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "df_clean=df_clean.drop_duplicates()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "from sklearn.preprocessing import OneHotEncoder\n", + "df_clean = df_clean.drop(['Weather', 'Traffic_Level', 'Time_of_Day', 'Vehicle_Type'], axis=1).copy()\n", + "X = df_clean.drop(['Distance_km', 'Preparation_Time_min', 'Courier_Experience_yrs', 'Delivery_Time'], axis=1).copy()\n", + "print(\"Applying One-Hot Encoding to feature DataFrame 'X'...\")\n", + "onehot_encoder = OneHotEncoder(handle_unknown='ignore', sparse_output=False)\n", + "X_encoded = pd.DataFrame(onehot_encoder.fit_transform(X), columns=onehot_encoder.get_feature_names_out(X.columns))\n", + "display(X_encoded.head())\n", + "\n", + "\n", + "\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "from sklearn.preprocessing import StandardScaler\n", + "import numpy as np\n", + "scaler = StandardScaler()\n", + "df_scaled = scaler.fit_transform(df_clean)\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", + "target=df_clean['delivery_time']\n", + "X1=df_clean.drop(['delivery_time']).copy()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:\n", + "\n", + "from sklearn.linear_model import LogisticRegression\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", + "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 1: Write your code here:\n", + "import matplotlib.pyplot as plt\n", + "from sklearn.model_selection import train_test_split, KFold, cross_val_score\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.\")" + ], + "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/163/Q2.ipynb b/submissions_extracted/163/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..2a8f3b2bc5878b0a78b1d7a734dc9a668d51b297 --- /dev/null +++ b/submissions_extracted/163/Q2.ipynb @@ -0,0 +1,365 @@ +{ + "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": [ + "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" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 1. Convert Numpy arrays to PyTorch Tensorsy_train\n", + "X_train = torch.tensor(X_train, dtype=torch.float32)\n", + "X_test = torch.tensor(X_test, dtype=torch.float32)\n", + "y_train = torch.tensor(y_train, dtype=torch.float32)\n", + "y_test = torch.tensor(y_test, dtype=torch.float32)\n", + "\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 2. Create TensorDataset objects\n", + "\n", + "# Create TensorDatasets for training and testing\n", + "train_dataset = TensorDataset(X_train, y_train)\n", + "test_dataset = TensorDataset(X_test, y_test)\n", + "\n", + "\n" + ], + "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", + "# 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": [ + "# 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", + "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", + " # Output layer (regression output)\n", + " output = self.layer3(a2)\n", + "\n", + " return output" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your training loop here:\n", + "def train_one_epoch(model, optimizer, criterion, train_loader, device):\n", + " # Set the model to training mode\n", + " model.train()\n", + "\n", + " running_loss = 0.0\n", + "\n", + " for X_batch, y_batch in train_loader:\n", + " # Move batch to the selected device\n", + " X_batch = X_batch.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", + "# 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", + "# Hyperparameters (feel free to experiment!)\n", + "num_epochs = 20\n", + "learning_rate = 0.001\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", + "# Run Training\n", + "train_losses = []\n", + "val_losses = []\n", + "\n", + "print('Starting Training...')\n", + "for epoch in range(num_epochs):\n", + " # Train one epoch\n", + " train_loss = train_one_epoch(model, optimizer, criterion, train_loader, device)\n", + "\n", + " # Validate\n", + " val_loss = validate(model, criterion, test_loader, device)\n", + "\n", + " train_losses.append(train_loss)\n", + " val_losses.append(val_loss)\n", + "\n", + " if (epoch + 1) % 5 == 0:\n", + " print(\n", + " f'Epoch [{epoch+1}/{num_epochs}], '\n", + " f'Train Loss: {train_loss:.4f}, '\n", + " f'Val Loss: {val_loss:.4f}'\n", + " )\n", + "\n", + "print('Training Complete!')" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "plt.figure(figsize=(7, 5))\n", + "\n", + "plt.plot(train_losses, label='Train Loss')\n", + "plt.plot(val_losses, label='Validation Loss')\n", + "plt.title('Loss over Epochs')\n", + "plt.xlabel('Epoch')\n", + "plt.ylabel('Loss')\n", + "plt.legend()\n", + "\n", + "plt.tight_layout()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2 (Bonus): Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/163/Q3.ipynb b/submissions_extracted/163/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..7f27697746193099f3fe3a29462b9bd61123fb1d --- /dev/null +++ b/submissions_extracted/163/Q3.ipynb @@ -0,0 +1,228 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "\n", + "\n", + "# Download latest version\n", + "\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q3-exam-data\")\n", + "\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "import os\n", + "import pandas as pd\n", + "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", + "df_dropna = df_Q3.dropna(axis=1).copy()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "df_clean=df_dropna.drop_duplicates()\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "df_clean.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "from sklearn.preprocessing import OneHotEncoder\n", + "encoder = OneHotEncoder(sparse_output=False)\n", + "encoded = encoder.fit_transform(df_clean)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "from sklearn.preprocessing import StandardScaler\n", + "import numpy as np\n", + "scaler = StandardScaler()\n", + "scaled = scaler.fit_transform(df_clean)" + ], + "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", + "print(\"Plotting feature distributions...\")\n", + "\n", + "# Identify feature columns\n", + "feature_columns = df_clean[column]\n", + "\n", + "# Iterate through each feature and create a count plot\n", + "for feature in feature_columns:\n", + " plt.figure(figsize=(10, 6)) # Adjust figure size dynamically if needed\n", + " sns.countplot(data=df, x=feature, palette='viridis')\n", + " plt.title(f'Distribution of {feature}', fontsize=16)\n", + " plt.xlabel(feature.replace('-', ' ').title(), fontsize=12)\n", + " plt.ylabel('Count', fontsize=12)\n", + " plt.xticks(rotation=45, ha='right') # Rotate labels for better readability\n", + " plt.tight_layout() # Adjust layout to prevent labels from overlapping\n", + " plt.show()\n", + "\n", + "print(\"All feature distributions plotted successfully.\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "X=df_clean.drop(['Target']).cpoy\n", + "y=df_clean['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", + "import numpy as np\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\"Training set: {len(X_train)} samples\")\n", + "print(f\"Test set: {len(X_test)} samples\")\n", + "print(f\"\\nX_train:\\n{X_train}\")\n", + "print(f\"\\nX_test:\\n{X_test}\")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "# Plot feature importance\n", + "importance = pd.DataFrame({\n", + " 'feature': features,\n", + " 'importance': model.feature_importances_\n", + "})\n", + "importance = importance.sort_values('importance', ascending=True).tail(10)\n", + "\n", + "plt.figure(figsize=(10, 6))\n", + "plt.barh(importance['feature'], importance['importance'])\n", + "plt.title('Top 10 Feature Importance')\n", + "plt.xlabel('Importance')\n", + "plt.tight_layout()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/164/Q1.ipynb b/submissions_extracted/164/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..f798cb3ac038c4fc7eb75bf009cea59359321334 --- /dev/null +++ b/submissions_extracted/164/Q1.ipynb @@ -0,0 +1,268 @@ +{ + "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", + "from sklearn.model_selection import train_test_split, KFold\n", + "from sklearn.preprocessing import StandardScaler, LabelEncoder\n", + "from sklearn.preprocessing import OneHotEncoder\n", + "from sklearn.ensemble import RandomForestRegressor\n", + "from sklearn.metrics import mean_absolute_error, mean_squared_error\n", + "from sklearn.preprocessing import StandardScaler\n", + "\n", + "\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", + "# Load the dataset\n", + "ppath = os.path.join(path, '/kaggle/input/q1-exam-data/Q1_data.csv')\n", + "df = pd.read_csv(ppath)" + ], + "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", + "# Delivery_Time distribution\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 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", + "# Missing values\n", + "print(\"Missing values:\")\n", + "print(df.isnull().sum())\n", + "df['Delivery_Time'] = df['Delivery_Time'].fillna(df['Delivery_Time'].mode()[0])" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "def check_duplicates(df):\n", + " duplicates = df.duplicated().sum()\n", + " print(f\"Number of Duplicate Samples: {duplicates}\")\n", + " if duplicates > 0:\n", + " print(\"Dropping Duplicates...\")\n", + " df.drop_duplicates(inplace=True)\n", + " print(\"Duplicates Dropped.\")\n", + " else:\n", + " print(\"No Duplicate Samples Found.\")\n", + "\n", + "check_duplicates(df)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "cols = ['Weather', 'Traffic_Level', 'Time_of_Day', 'Vehicle_Type']\n", + "for col in cols:\n", + " le = LabelEncoder()\n", + " df[col] = le.fit_transform(df[col].astype(str))\n", + "\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "\n", + "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:\n", + "print(f\"{df['Delivery_Time'].sum()}\")\n", + "print(f\"{(df['Delivery_Time'] == 0).sum()}\")\n", + "\n", + "# ITS BALANCED!!" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "feature_cols = cols + ['Order_ID',\t'Distance_km', 'Preparation_Time_min', 'Courier_Experience_yrs'\t]\n", + "\n", + "X = df[feature_cols]\n", + "# y: The target variable we want to predict (the \"Answer Key\")\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", + "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\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", + "print(f\"MAE: ${mae:,.2f}\")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "# Feature importance\n", + "feature_importance = pd.DataFrame({\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", + "condition_counts = df['Delivery_Time'].value_counts()\n", + "plt.figure(figsize=(10, 5))\n", + "plt.bar(condition_counts.index, condition_counts.values, color='coral')\n", + "plt.title('Delivery_Time Distribution')\n", + "plt.xlabel('Delivery_Time')\n", + "plt.ylabel('Delivery_Time')\n", + "plt.xticks(rotation=45)\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/164/Q2.ipynb b/submissions_extracted/164/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..4b5fa96d49ecf2b0509c550d37a4798260623109 --- /dev/null +++ b/submissions_extracted/164/Q2.ipynb @@ -0,0 +1,354 @@ +{ + "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.preprocessing import StandardScaler\n", + "import torch\n", + "import torch.nn as nn\n", + "\n", + "\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", + "# 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", + "from torch.utils.data import TensorDataset\n", + "\n", + "train_dataset = TensorDataset(X_train, y_train)\n", + "test_dataset = TensorDataset(X_test, y_test)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 3. Create DataLoaders\n", + "\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)" + ], + "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" + ], + "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", + " z3 = self.layer3(a2)\n", + " a3 = self.relu(z3)\n", + "\n", + " # Output layer (raw scores / logits)\n", + " output = self.layer4(a3) # there is something missing here, remember? :)\n", + "\n", + " return output" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your training loop here:\n", + "def train_one_epoch(model, optimizer, criterion, train_loader, device):\n", + " # Set the model to training mode\n", + " model.train()\n", + "\n", + " running_loss = 0.0\n", + "\n", + " for X_batch, y_batch in train_loader:\n", + " # Move batch to the selected device\n", + " X_batch = X_batch.to(device)\n", + " y_batch = y_batch.view(-1, 1).to(device)\n", + "\n", + " # Forward pass\n", + " outputs = model(X_batch)\n", + " loss = criterion(outputs, y_batch)\n", + "\n", + " # Backward pass & optimization\n", + " optimizer.zero_grad() # Clear previous gradients\n", + " loss.backward() # Compute gradients\n", + " optimizer.step() # Update model parameters\n", + "\n", + " running_loss += loss.item()\n", + "\n", + " # Average loss over all batches\n", + " avg_loss = running_loss / len(train_loader)\n", + "\n", + " return avg_loss" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your validation loop here:\n", + "def validate(model, criterion, test_loader, device):\n", + " # Set the model to evaluation mode\n", + " model.eval()\n", + "\n", + " running_loss = 0.0\n", + " correct = 0\n", + " total = 0\n", + "\n", + " with torch.no_grad(): # Disable gradient computation\n", + " for X_batch, y_batch in test_loader:\n", + " # Move batch to the selected device\n", + " X_batch = X_batch.to(device)\n", + " y_batch = y_batch.view(-1, 1).to(device)\n", + "\n", + " # Forward pass\n", + " outputs = model(X_batch)\n", + " loss = criterion(outputs, y_batch)\n", + " running_loss += loss.item()\n", + "\n", + " # Binary predictions\n", + " predicted = (outputs > 0.5).float()\n", + "\n", + " # Accuracy calculation\n", + " correct += (predicted == y_batch).sum().item()\n", + " total += y_batch.size(0)\n", + "\n", + " avg_loss = running_loss / len(test_loader)\n", + " accuracy = correct / total\n", + "\n", + " return avg_loss, accuracy\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Define device, model, loss, optimizer:\n", + "device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n", + "\n", + "# Model parameters\n", + "input_dim = 3\n", + "hidden_dim = 4\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", + "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", + "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/164/Q3.ipynb b/submissions_extracted/164/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..9d474b5359285019f44d560109a0553b74decd93 --- /dev/null +++ b/submissions_extracted/164/Q3.ipynb @@ -0,0 +1,227 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "import numpy as np\n", + "import pandas as pd\n", + "import matplotlib.pyplot as plt\n", + "import os\n", + "from sklearn.preprocessing import StandardScaler, LabelEncoder\n", + "from sklearn.model_selection import train_test_split, KFold\n", + "\n", + "from sklearn.model_selection import train_test_split, KFold\n", + "from sklearn.preprocessing import StandardScaler, LabelEncoder\n", + "from sklearn.preprocessing import OneHotEncoder\n", + "from sklearn.ensemble import RandomForestRegressor\n", + "from sklearn.metrics import mean_absolute_error, mean_squared_error\n", + "from sklearn.preprocessing import StandardScaler\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", + "ppath = os.path.join(path, '/kaggle/input/q3-exam-data/Q3_data.csv')\n", + "df = pd.read_csv(ppath)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "df.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "df.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "# Missing values\n", + "print(\"Missing values:\")\n", + "print(df.isnull().sum())\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", + "# WE dont need to encode" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "\n", + "features = df.columns.drop(\"Target\") # DON'T SCALE THE TARGET\n", + "\n", + "\n", + "scaler = StandardScaler()\n", + "df[features] = scaler.fit_transform(df[features])\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "print(f\"{df['Target'].sum()}\")\n", + "print(f\"{(df['Target'] == 0).sum()}\")\n", + "\n", + "# its not balanced!" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "feature_cols = features\n", + "\n", + "X = df[feature_cols]\n", + "# y: The target variable we want to predict (the \"Answer Key\")\n", + "y = df['Target']" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\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", + "print(f\"MAE: ${mae:,.2f}\")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:# Feature importance\n", + "feature_importance = pd.DataFrame({\n", + " 'feature': feature_cols,\n", + " 'importance': model.feature_importances_\n", + "}).sort_values('importance', ascending=False)\n", + "\n", + "plt.figure(figsize=(10, 6))\n", + "plt.barh(feature_importance['feature'], feature_importance['importance'])\n", + "plt.xlabel('Importance')\n", + "plt.title('Feature Importance')\n", + "plt.gca().invert_yaxis()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/165/Q1.ipynb b/submissions_extracted/165/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..37c9acb4f061816cf8092c3db8b4fd2f582e237e --- /dev/null +++ b/submissions_extracted/165/Q1.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/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", + "import os\n", + "import pandas as pd\n", + "\n", + "path = os.path.join(path, 'Q1_data.csv')\n", + "df = pd.read_csv(path)\n", + "\n", + "print(f\"Shape: {df.shape}\") # the dataset shape\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "\n", + "df.head() # print firstt five samples" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "df.info() # to see the types of our features for encoding and missing values (later)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "df.describe() # for scaling (later)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "import matplotlib.pyplot as plt # import matplotlib for visualization\n", + "\n", + "plt.figure(figsize=(10, 5))\n", + "plt.hist(df['Delivery_Time'].dropna(), bins=30, edgecolor='black')\n", + "plt.title('Target Distribution')\n", + "plt.xlabel('Delivery_Time')\n", + "plt.ylabel('Frequency')\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "\n", + "d= df.drop(columns=['Order_ID'])\n", + "d" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "\n", + "# 1) lets see our missing values first and how many they are if not alot then we will not drop the features because they might be relevant or beneficial to the models predictions\n", + "\n", + "print(\"Missing values:\")\n", + "print(d .isnull().sum())\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 2) # hard coded each feature that had missing values and i thought filling it wiht the mode would be the best option sisnce feature include both catagorical and numrical data\n", + "\n", + "d['Weather'] = d['Weather'].fillna(d['Weather'].mode()[0])\n", + "\n", + "d['Traffic_Level'] = d['Traffic_Level'].fillna(d['Traffic_Level'].mode()[0])\n", + "\n", + "d['Courier_Experience_yrs'] = d['Courier_Experience_yrs'].fillna(d['Courier_Experience_yrs'].mode()[0])\n", + "d['Time_of_Day'] = d['Time_of_Day'].fillna(d['Time_of_Day'].mode()[0])\n", + "d['Delivery_Time'] = d['Delivery_Time'].fillna(d['Delivery_Time'].mode()[0])\n", + "\n", + "print(\"Missing values remaining:\", d.isnull().sum().sum())\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "\n", + "def check_duplicates(d):\n", + " duplicates = d.duplicated().sum()\n", + " print(f\"Number of Duplicate Samples: {duplicates}\")\n", + " if duplicates > 0:\n", + " print(\"Dropping Duplicates...\")\n", + " d.drop_duplicates(inplace=True)\n", + " print(\"Duplicates Dropped.\")\n", + " else:\n", + " print(\"No Duplicate Samples Found.\")\n", + "\n", + "check_duplicates(d)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "\n", + "from sklearn.preprocessing import OneHotEncoder #import OneHotEncoder\n", + "from sklearn.preprocessing import StandardScaler, LabelEncoder\n", + "\n", + "# Labeleencoder used\n", + "\n", + "cols = ['Weather','Traffic_Level','Time_of_Day','Vehicle_Type']\n", + "\n", + "\n", + "for col in cols:\n", + " le = LabelEncoder()\n", + " d[col] = le.fit_transform(d[col].astype(str))\n", + "\n", + "d.head()\n", + "\n", + "# ONE HOT ENCODER CODE\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": [ + "numerical_cols = df.select_dtypes(include=[\"int64\", \"float64\"]).columns.drop(\"Delivery_Time\") # DON'T SCALE THE TARGET # IMP\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", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 6: Write your code here:\n", + "\n", + " # i believe its imbalance from this line of code and the distribution perfomed earlier\n", + "\n", + "target_column =d[\"Delivery_Time\"]\n", + "\n", + "def check_target_imbalance(d, 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", + "\n", + "#\n", + "X = df.drop(\"Delivery_Time\", axis=1).astype(float)\n", + "y = df['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", + "\n", + "\n", + "# 2) i will use k fold since the dataset is small and no need to use stratified since there is no imbalance\n", + "\n", + "\n", + "from sklearn.model_selection import KFold\n", + "\n", + "kf = KFold(n_splits=5, shuffle=True, random_state=42)\n", + "\n", + "# Iterate through folds\n", + "for fold, (train_idx, test_idx) in enumerate(kf.split(X), start=1): # we only take the indices of x because y is corresponding with it\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) # import need libraries for ou model and evaluation\n", + "\n", + "from sklearn.ensemble import RandomForestClassifier\n", + "from sklearn.metrics import classification_report, confusion_matrix, accuracy_score\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", + "# 4)\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", + "# 5)\n", + "\n", + "kfold = KFold(n_splits=5, shuffle=True, random_state=42)\n", + "\n", + "mae_scores = []\n", + "rmse_scores = []\n", + "\n", + "for train_idx, val_idx in kfold.split(X_train_scaled):\n", + " X_fold_train, X_fold_val = X_train_scaled[train_idx], X_train_scaled[val_idx]\n", + " y_fold_train, y_fold_val = y_train.iloc[train_idx], y_train.iloc[val_idx]\n", + "\n", + " # Train and predict\n", + " model.fit(X_fold_train, y_fold_train)\n", + " y_fold_pred = model.predict(X_fold_val)\n", + "\n", + " # Calculate metrics\n", + " mae_scores.append(mean_absolute_error(y_fold_val, y_fold_pred))\n", + "\n", + "\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", + "\n", + "\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" + ], + "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/165/Q2.ipynb b/submissions_extracted/165/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..59a80cdcbf0310f71896f4cfed7c792dad4fe83e --- /dev/null +++ b/submissions_extracted/165/Q2.ipynb @@ -0,0 +1,424 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q2-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import os\n", + "import pandas as pd\n", + "import numpy as np\n", + "from PIL import Image\n", + "from sklearn.model_selection import train_test_split\n", + "\n", + "# Load Labels\n", + "labels_df = pd.read_csv(os.path.join(path, \"labels.csv\"))\n", + "img_dir = os.path.join(path, \"images\")\n", + "\n", + "images = []\n", + "ages = []\n", + "\n", + "# Load Images and Resize\n", + "print(\"Loading images...\")\n", + "for index, row in labels_df.iterrows():\n", + " img_name = row.iloc[0]\n", + " age = row.iloc[1]\n", + " img_path = os.path.join(img_dir, img_name)\n", + "\n", + " if os.path.exists(img_path):\n", + " img = Image.open(img_path).convert('RGB')\n", + " img_array = np.array(img) / 255.0 # Normalize pixel values to [0, 1]\n", + " images.append(img_array)\n", + " ages.append(age)\n", + "\n", + "X = np.array(images)\n", + "y = np.array(ages)\n", + "\n", + "# Transpose image dimensions to match PyTorch format (N, C, H, W)\n", + "X = np.transpose(X, (0, 3, 1, 2))\n", + "\n", + "# Split Data\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n", + "\n", + "print(f\"X_train shape: {X_train.shape}\")\n", + "print(f\"X_test shape: {X_test.shape}\")\n", + "print(f\"y_train shape: {y_train.shape}\")\n", + "print(f\"y_test shape: {y_test.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# import needed libraries\n", + "import torch\n", + "import torch.nn as nn\n", + "from torch.optim import AdamW\n", + "import matplotlib.pyplot as plt\n", + "from torch.utils.data import DataLoader, TensorDataset\n", + "from sklearn.model_selection import train_test_split\n", + "from sklearn.preprocessing import StandardScaler, LabelEncoder\n", + "from sklearn.metrics import mean_absolute_error, mean_squared_error, r2_score" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 1. Convert Numpy arrays to PyTorch Tensors\n", + "\n", + "\n", + "# TODO: Transform to PyTorch tensors with dtype=torch.float32\n", + "X_train = torch.tensor(X_train.values, dtype=torch.float32)\n", + "X_test = torch.tensor(X_test.values, dtype=torch.float32)\n", + "y_train = torch.tensor(y_train.values, dtype=torch.float32)\n", + "y_test = torch.tensor(y_test.values, dtype=torch.float32)\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", + "\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": [ + "# 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", + "\n", + " self.layer1 = nn.Linear(input_dim, hidden_dim)\n", + "\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) # a single neuron in the output layer becasue this is a regression task\n", + "\n", + " # ReLU activation for non-linearity in hidden layers\n", + " self.relu = nn.ReLU()\n", + "\n", + "\n", + " # Defines how input data flows through the network\n", + " def forward(self, x):\n", + "\n", + " a1 = self.relu(self.layer1(x))\n", + "\n", + "\n", + " a2 = self.relu(self.layer2(a1))\n", + "\n", + " a3 = self.relu(self.layer3(a2))\n", + "\n", + "\n", + "\n", + " # Output layer (regression output)\n", + " output = self.layer3(a3)\n", + "\n", + "\n", + " # TODO: are we missing output activation function? (hint: Loss Function)\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", + " # TODO: make predictions\n", + " outputs = # \n", + " # TODO: compute loss\n", + " loss = # \n", + "\n", + " # Backward pass & optimization\n", + " optimizer.zero_grad() # Clear previous gradients\n", + " loss.backward() # Compute gradients\n", + " optimizer.step() # Update model parameters\n", + "\n", + " running_loss += loss.item()\n", + "\n", + " # Average loss over all batches\n", + " avg_loss = running_loss / len(train_loader)\n", + "\n", + " return avg_loss" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your validation loop here: # NO BACK PROPOGATION only forward pass becasue we are validating our model not training it so no need for gradient function\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", + "\n", + "\n", + " avg_loss = running_loss / len(test_loader)\n", + "\n", + "\n", + " return avg_loss" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Define device, model, loss, optimizer:\n", + "\n", + "from torch.optim import AdamW\n", + "\n", + "learning_rate = 0.001\n", + "\n", + "# 1)\n", + "device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n", + "\n", + "# 2)\n", + "# Model parameters\n", + "input_dim = 28 * 28 # image size\n", + "hidden_dim = 14 # Design choice\n", + "output_dim = 1 # age\n", + "\n", + "# Instantiate model\n", + "model = NN4Layer(input_dim, hidden_dim, output_dim).to(device)\n", + "\n", + "# Print the model architecture\n", + "print(\"Model Architecture:\\n\")\n", + "print(model)\n", + "\n", + "# Calculate the total number of trainable parameters (added as optional)\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", + "# 3)\n", + "criterion = nn.CrossEntropyLoss()\n", + "\n", + "# 4)\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", + "num_epochs = 20\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", + "\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()\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/165/Q3.ipynb b/submissions_extracted/165/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..00de952979ed06a022b15227fb78c337d0c5bd13 --- /dev/null +++ b/submissions_extracted/165/Q3.ipynb @@ -0,0 +1,340 @@ +{ + "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 os\n", + "import pandas as pd\n", + "\n", + "path = os.path.join(path, 'Q3_data.csv')\n", + "df = pd.read_csv(path)\n", + "\n", + "print(f\"Shape: {df.shape}\") # the dataset 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", + "\n", + "df.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "\n", + "df.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "\n", + "print(\"Missing values:\")\n", + "print(df.isnull().sum())" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "\n", + "# i will drop it because it contains the most missing values\n", + "d= df.drop(columns=['D_142'])\n", + "\n", + "\n", + "for col in ['D_143', 'D_144', 'D_145', 'P_2']: # i wanted to to fill the missing values since im not sure these features are relevant to the code or not\n", + " d[col] = d[col].fillna('unknown')\n", + "\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "print(\"Missing values remaining:\", d.isnull().sum().sum())" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "d.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "\n", + "def check_duplicates(d):\n", + " duplicates = d.duplicated().sum()\n", + " print(f\"Number of Duplicate Samples: {duplicates}\")\n", + " if duplicates > 0:\n", + " print(\"Dropping Duplicates...\")\n", + " d.drop_duplicates(inplace=True)\n", + " print(\"Duplicates Dropped.\")\n", + " else:\n", + " print(\"No Duplicate Samples Found.\")\n", + "\n", + "check_duplicates(d)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "\n", + "# NOT NEEDED since what we got from .info() are only numbers no objects/strings" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "from sklearn.model_selection import train_test_split, KFold\n", + "from sklearn.preprocessing import StandardScaler\n", + "\n", + "\n", + "numerical_cols = df.select_dtypes(include=[\"int64\", \"float64\"]).columns.drop(\"Target\") # DON'T SCALE THE TARGET # IMP\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: # YES i didnt run the code but what i read from the data (the tearget column) it appears to have more 0 values than one indicating its imbalance\n", + "\n", + "import seaborn as sns\n", + "import matplotlib.pyplot as plt\n", + "\n", + "target_column =d[\"Target\"]\n", + "\n", + "def check_target_imbalance(d, 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": [ + "\n", + "#task 1\n", + "\n", + "X = df.drop(\"Target\", axis=1).astype(float)\n", + "y = df['Target'].astype(float)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "from IPython.display import clear_output\n", + "\n", + "%pip install kagglehub catboost xgboost tqdm -q\n", + "\n", + "clear_output()\n", + "\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" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:\n", + "\n", + "# because its considered imbalance i will use stratifiedKfold\n", + "\n", + "\n", + "\n", + "\n", + "sklearn_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 sklearn_models:\n", + " all_results[name] = {'accuracy': [], 'precision': [], 'recall': [], 'f1': []}\n", + "\n", + "\n", + "n_splits = 5\n", + "\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", + "\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", + " for model_name, model in sklearn_models.items():\n", + " print(f\"Training {model_name}...\")\n", + " model.fit(X_train, y_train)\n", + " y_pred = model.predict(X_test)\n", + "\n", + "\n", + " accuracy = accuracy_score(y_test, y_pred)\n", + "\n", + " f1 = f1_score(y_test, y_pred, zero_division=0)\n", + "\n", + " all_results[model_name]['accuracy'].append(accuracy)\n", + "\n", + " all_results[model_name]['f1'].append(f1)\n", + "\n", + " avg_loss = np.mean(all_results, axis=0) # PRINT AVERAGE ACROSS ALL FOLDS" + ], + "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", + "i\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()\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/166/Q1.ipynb b/submissions_extracted/166/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..647705b0068da27d335ba1890d231c221da1365a --- /dev/null +++ b/submissions_extracted/166/Q1.ipynb @@ -0,0 +1,263 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import pandas as pd\n", + "import numpy as np\n", + "import matplotlib.pyplot as plt\n", + "import seaborn as sns\n", + "import kagglehub\n", + "import os\n", + "from tqdm import tqdm" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q1-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "\n", + "csv_path = os.path.join(path, \"Q1_data.csv\")\n", + "\n", + "df = pd.read_csv(csv_path)\n", + "\n", + "print(f\"CSV file loaded from: {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\", axis=1)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "print(\"\\nMissing Values (df.isnull().sum()):\")\n", + "print(df.isnull().sum())" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "duplicate_rows = df.duplicated().sum()\n", + "if duplicate_rows > 0:\n", + " print(f\"Found {duplicate_rows} duplicate rows. Removing them...\")\n", + " df.drop_duplicates(inplace=True)\n", + " print(\"Duplicate rows removed.\")\n", + "else:\n", + " print(\"No duplicate rows found.\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "from sklearn.preprocessing import 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\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "from sklearn.preprocessing import StandardScaler\n", + "\n", + "print('data before scaling:\\n', df) #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:\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "plt.figure(figsize=(10, 5))\n", + "plt.title('delivery time Distribution')\n", + "plt.xlabel(\"delivery time\")\n", + "plt.ylabel(\"Traffic_Level\")\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42, stratify=y)\n", + "print(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", + "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", + "y_pred = model.predict(X_test_scaled)\n", + "\n", + "mae = mean_absolute_error(y_test, y_pred)\n", + "\n", + "print(f\"MAE: ${mae:,.2f}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\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/166/Q2.ipynb b/submissions_extracted/166/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..f2afdcb06f27da9b6f9e10b992d6c0127143bd4b --- /dev/null +++ b/submissions_extracted/166/Q2.ipynb @@ -0,0 +1,338 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q2-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import os\n", + "import pandas as pd\n", + "import numpy as np\n", + "from PIL import Image\n", + "from sklearn.model_selection import train_test_split\n", + "from torch.utils.data import DataLoader, TensorDataset\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)" + ], + "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)\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": [ + "# 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", + "import torch.nn as nn\n", + "\n", + "class NN3Layer(nn.Module):\n", + " def __init__(self, input_dim, hidden_dim):\n", + " super(NN3Layer, self).__init__()\n", + "\n", + " # First linear layer: input features -> hidden layer\n", + " self.layer1 = nn.Linear(input_dim, hidden_dim)\n", + "\n", + " # Second linear layer: hidden layer -> hidden layer\n", + " self.layer2 = nn.Linear(hidden_dim, hidden_dim)\n", + "\n", + " # Output layer: hidden layer\n", + " self.layer3 = nn.Linear(hidden_dim, hidden_dim)\n", + "\n", + " self.layer4 = nn.Linear(hidden_dim, 1)\n", + "\n", + " # ReLU activation for non-linearity in hidden layers\n", + " self.relu = nn.ReLU()\n", + "\n", + " # Defines how input data flows through the network\n", + " def forward(self, x):\n", + " # First hidden layer\n", + " a1 = self.relu(self.layer1(x))\n", + "\n", + " # Second hidden layer\n", + " a2 = self.relu(self.layer2(a1))\n", + "\n", + " a3 = self.relu(self.layer2(a2))\n", + "\n", + " # Output layer (regression output)\n", + " output = self.layer3(a3)\n", + "\n", + " return output" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your training loop here:\n", + "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": [ + "# Device configuration\n", + "from torch.optim import Adam\n", + "\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" + ], + "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", + " 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", + "import matplotlib.pyplot as plt\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/166/Q3.ipynb b/submissions_extracted/166/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..e23e8892e93c38257c45f4831b3a91e6e9472629 --- /dev/null +++ b/submissions_extracted/166/Q3.ipynb @@ -0,0 +1,227 @@ +{ + "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", + "csv_path = os.path.join(path, \"Q3_data.csv\")\n", + "\n", + "df = pd.read_csv(csv_path)\n", + "\n", + "print(f\"CSV file loaded from: {csv_path}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "df.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "df.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "def check_missing_values(df):\n", + " missing_values = df.isnull().sum()\n", + " print(\"Missing Values per Column:\")\n", + " print(missing_values[missing_values > 0])\n", + " if missing_values.any():\n", + " print(\"\\nHandle Missing Values as needed.\")\n", + " else:\n", + " print(\"\\nNo Missing Values Found.\")\n", + "\n", + "check_missing_values(df)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "def check_duplicates(df):\n", + " duplicates = df.duplicated().sum()\n", + " print(f\"Number of Duplicate Samples: {duplicates}\")\n", + " if duplicates > 0:\n", + " print(\"Dropping Duplicates...\")\n", + " df.drop_duplicates(inplace=True)\n", + " print(\"Duplicates Dropped.\")\n", + " else:\n", + " print(\"No Duplicate Samples Found.\")\n", + "\n", + "check_duplicates(df)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:" + ], + "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", + "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, \"status\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "plt.figure(figsize=(10, 5))\n", + "plt.title('...')\n", + "plt.xlabel(\"x\")\n", + "plt.ylabel(\"y\")\n", + "plt.show()" + ], + "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", + "\"CatBoost\": CatBoostClassifier(\n", + " verbose=0,\n", + " n_estimators=320,\n", + " max_depth=4\n", + " )\n", + "print(\"Model trained!\")" + ], + "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/167/Q1.ipynb b/submissions_extracted/167/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..170aaf4a97692efa206a58346ee91798c4072800 --- /dev/null +++ b/submissions_extracted/167/Q1.ipynb @@ -0,0 +1,312 @@ +{ + "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 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", + "from sklearn.preprocessing import OneHotEncoder # for one-hot encoding the categorical variables\n", + "from sklearn.model_selection import StratifiedKFold\n", + "from sklearn.metrics import accuracy_score\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q1-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1 (read the dataset): Write your code here:\n", + "delivery_path = os.path.join(path, 'Q1_data.csv')\n", + "df = pd.read_csv(delivery_path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2 (inspect the first few rows): Write your code here:\n", + "print(df.head())" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3 (Display Information): 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", + "# Delivery time 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 Distribution')\n", + "plt.xlabel('Delivery')\n", + "plt.ylabel('Frequency')\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1 (Drop the 'Order_ID' column): Write your code here:\n", + "df.drop(columns=['Order_ID'])" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "df.info()" + ], + "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 2 (Handle missing values): 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.isnull().sum()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "df.dropna()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3 (Check and remove duplicates): Write your code here:\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": [ + "# Check whether there's categorical columns\n", + "categorical_cols = df.select_dtypes(include=[\"object\"]).columns\n", + "print(\"Categorical Columns:\", list(categorical_cols))" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4 (Encode categorical variables): Write your code here:\n", + "# use onehotencoder for bonus\n", + "\n", + "pd.get_dummies(df, columns=['Weather','Traffic_Level','Time_of_Day','Vehicle_Type'], drop_first=True)\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5 (Apply Feature Scaling for all features): Write your code here:\n", + "# Use StandardScaler\n", + "scaler = StandardScaler()\n", + "numerical_columns = ['Distance_km', 'Preparation_Time_min', 'Courier_Experience_yrs','Delivery_Time']\n", + "df[numerical_columns] = scaler.fit_transform(df[numerical_columns])\n", + "print(df.head())\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 6: Write your code here:\n", + "# Check for target imbalance\n", + "# and state if it is imbalanced or not\n", + "\n", + "df['Delivery_Time'].hist()\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1 (Split dataset into features(X) and target(y):\n", + "# Write your code here:\n", + "# Define features (X) and target (y)\n", + "feature_cols = ['Traffic_Level', 'Preparation_Time_min','Courier_Experience_yrs',\n", + " 'Time_of_Day','Weather']\n", + "X = df[feature_cols]\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", + "# Use the correct split: Kfold or stratifiedkfold\n", + "n_splits = 5\n", + "skf = StratifiedKFold(n_splits=n_splits, shuffle=True, random_state=42)\n", + "for fold_idx, (train_index, test_index) in enumerate(skf.split(X, y)):\n", + " print(f\"\\nFold {fold_idx + 1}/{n_splits}\")\n", + "\n", + " 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 = RandomForestRegressor(n_estimators=100, max_depth=20, random_state=42, n_jobs=-1)\n", + "model.fit(X_train_scaled, y_train)\n", + "print(\"Model trained!\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n" + ], + "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/167/Q2.ipynb b/submissions_extracted/167/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..d4538e0dd86b128a4c5285f6d47397f5e9c106a8 --- /dev/null +++ b/submissions_extracted/167/Q2.ipynb @@ -0,0 +1,390 @@ +{ + "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\n", + "import numpy as np\n", + "\n", + "from torchvision.datasets import MNIST\n", + "from torch.optim import Adam\n", + "from torchvision.transforms.functional import to_tensor\n", + "import torch.nn.functional as F\n", + "import matplotlib.pyplot as plt\n", + "\n", + "\n", + "# 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.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", + "\n", + "print(f'{X.shape=}')\n", + "print(f'{y.shape=}')\n", + "print('-'*10)\n", + "print(f'{X_train.shape=}')\n", + "print(f'{X_test.shape=}')\n", + "print('-'*10)\n", + "print(f'{y_train.shape=}')\n", + "print(f'{y_test.shape=}')" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 2. Create TensorDataset objects\n", + "# Create TensorDatasets for training and testing\n", + "train_dataset = TensorDataset(X_train, y_train)\n", + "test_dataset = TensorDataset(X_test, y_test)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 3. Create DataLoaders\n", + "# Create Dataloaders to train and test data in batches\n", + "train_loader = DataLoader(train_dataset, batch_size=32, shuffle=True)\n", + "test_loader = DataLoader(test_dataset, batch_size=32, shuffle=False)\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 4. Print shape of one batch\n", + "# Print dataset sizes\n", + "print(\"Train dataset:\", len(train_dataset))\n", + "print(\"Test dataset:\", len(test_dataset))\n", + "\n", + "# Get the first batch from the training DataLoader\n", + "X_batch, y_batch = next(iter(train_loader))\n", + "print(f\"Training batch input shape: {X_batch.shape}\")\n", + "print(f\"Training batch labels shape: {y_batch.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 5. Display sample images\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" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your training loop here:\n", + "def train_one_epoch(model, optimizer, criterion, train_loader, device):\n", + " # Set the model to training mode\n", + " model.train()\n", + "\n", + " running_loss = 0.0\n", + "\n", + " for X_batch, y_batch in train_loader:\n", + " # Move batch to the selected device\n", + " X_batch = X_batch.view(X_batch.size(0), -1).to(device)\n", + " y_batch = y_batch.to(device)\n", + "\n", + " # Forward pass\n", + " outputs = model(X_batch) # shape: (batch_size, 10)\n", + " loss = criterion(outputs, y_batch)\n", + "\n", + " # Backward pass & optimization\n", + " optimizer.zero_grad() # Clear previous gradients\n", + " loss.backward() # Compute gradients\n", + " optimizer.step() # Update model parameters\n", + "\n", + " running_loss += loss.item()\n", + "\n", + " # Average loss over all batches\n", + " avg_loss = running_loss / len(train_loader)\n", + "\n", + " return avg_loss" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your validation loop here:\n", + "def validate(model, criterion, test_loader, device):\n", + " # Set the model to evaluation mode\n", + " model.eval()\n", + "\n", + " running_loss = 0.0\n", + " correct = 0\n", + " total = 0\n", + "\n", + " with torch.no_grad():\n", + " for X_batch, y_batch in test_loader:\n", + " # Move data to device\n", + " X_batch = X_batch.view(X_batch.size(0), -1).to(device)\n", + " y_batch = y_batch.to(device)\n", + "\n", + " # Forward pass\n", + " outputs = model(X_batch) # shape: (batch_size, 10)\n", + " loss = criterion(outputs, y_batch)\n", + " running_loss += loss.item()\n", + "\n", + " # Apply Softmax to get probabilities\n", + " probabilities = F.softmax(outputs, dim=1)\n", + "\n", + " # Multiclass predictions\n", + " predicted = torch.argmax(probabilities, dim=1)\n", + "\n", + " # Accuracy calculation\n", + " correct += (predicted == y_batch).sum().item()\n", + " total += y_batch.size(0)\n", + "\n", + " avg_loss = running_loss / len(test_loader)\n", + " accuracy = correct / total\n", + "\n", + " return avg_loss, accuracy" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Define device, model, loss, optimizer:\n", + "# Device setup\n", + "device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n", + "\n", + "# Model parameters\n", + "input_dim = 28 * 28 # MNIST images flattened\n", + "hidden_dim = 14 # Design choice\n", + "output_dim = 10 # Digits 0–9\n", + "\n", + "# Instantiate model\n", + "model = 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", + "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": [ + "# 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/167/Q3.ipynb b/submissions_extracted/167/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..8be9f10aa403119e0ef446df0dc937b83d4f63c1 --- /dev/null +++ b/submissions_extracted/167/Q3.ipynb @@ -0,0 +1,264 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "import math # for mathematical operations\n", + "from copy import deepcopy # for copying object\n", + "\n", + "import numpy as np # for numerical operations\n", + "import pandas as pd\n", + "\n", + "\n", + "from sklearn.model_selection import train_test_split # for splitting the dataset into training and testing sets\n", + "from sklearn.preprocessing import StandardScaler # for scaling the data\n", + "from sklearn.preprocessing import MinMaxScaler # for scaling the data\n", + "from sklearn.preprocessing import LabelEncoder # for encoding the labels\n", + "from sklearn.preprocessing import OneHotEncoder # for one-hot encoding the categorical variables\n", + "\n", + "from sklearn.linear_model import LinearRegression # for linear regression model\n", + "from sklearn.linear_model import LogisticRegression # for logistic regression model\n", + "from sklearn.metrics import confusion_matrix # for calculating confusion matrix for classification task\n", + "\n", + "from sklearn.metrics import mean_squared_error # for calculating mean squared error\n", + "from sklearn.metrics import mean_absolute_error # for calculating mean absolute error\n", + "from sklearn.metrics import r2_score # for calculating r2 score\n", + "from sklearn.metrics import accuracy_score # for calculating accuracy score\n", + "from sklearn.metrics import precision_score # for calculating precision score\n", + "from sklearn.metrics import recall_score # for calculating recall score\n", + "from sklearn.metrics import f1_score # for calculating f1 score\n", + "\n", + "import torch\n", + "import torch.nn as nn\n", + "import torch.optim as optim\n", + "from torch.optim import SGD\n", + "import os\n", + "\n", + "\n", + "\n", + "# Download latest version\n", + "\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q3-exam-data\")\n", + "\n", + "\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "delivery_path = os.path.join(path, 'Q3_data.csv')\n", + "df = pd.read_csv(delivery_path)" + ], + "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": [ + "# 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": [ + "df.drop(columns=['D_137','D_138','D_142','D_42'])\n", + "df.dropna()\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "df.head()" + ], + "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", + "duplicates = df.duplicated().sum()\n", + "print(f\"Duplicates: {duplicates}\")\n", + "\n", + "# No duplicates exist" + ], + "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", + "\n", + "# No categorical columns exist" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# First, let's convert the target variable to numeric\n", + "# status: Default = 1, No Deafult = 0\n", + "df['Target'] = df['Target'].map({'No Default': 0, 'Not Default': 1})" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "scaler = StandardScaler()\n", + "data_scaled = scaler.fit_transform(df['P_2','D_39', 'B_1'])\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", + "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}\")\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:\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/168/Q1.ipynb b/submissions_extracted/168/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..228acbe464eb9caec2d7e6ec7db651ad994d451d --- /dev/null +++ b/submissions_extracted/168/Q1.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/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", + "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": [ + "# Task 5: Write your code here:\n", + "import matplotlib.pyplot as plt\n", + "plt.hist(df[\"Delivery_Time\"].dropna(), bins=30, edgecolor='black', color='blue')\n", + "plt.title(f\"Target Distribution\")\n", + "plt.xlabel(\"Delivery Time\")\n", + "plt.ylabel(\"Frequency\")" + ], + "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", + "# First let's inspect columns with missing values\n", + "\n", + "missing_values = df.isnull().sum()\n", + "missing_values = missing_values[missing_values>0]\n", + "print(missing_values)\n", + "#Task Continued Below" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Let's look at the data types of these columns\n", + "for col in missing_values.index:\n", + " print(f\"{col}'s Data type : {df[col].dtype}\")\n", + "\n", + " # Task continued below" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# First rows with key features (and target) missing\n", + "df.dropna(subset=['Traffic_Level', 'Time_of_Day', 'Delivery_Time'], inplace=True)\n", + "df.isnull().sum()\n", + "# Task continued below" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Now filling the weather with the mode and the experience years with the mean\n", + "\n", + "df['Weather'] = df['Weather'].fillna(df['Weather'].mode()[0])\n", + "df['Courier_Experience_yrs'] = df['Courier_Experience_yrs'].fillna(df['Courier_Experience_yrs'].mean())\n", + "print(f\"{df.isnull().sum().sum()} Missing Values Remaining\")\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "duplicate_count = df.duplicated().sum()\n", + "if duplicate_count>0:\n", + " df.drop_duplicates(inplace=True)\n", + " print(\"Duplicates Removed\")\n", + "else:\n", + " print(\"No duplicates found\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "\n", + "# Let's first check the categoricla columns in the dataset\n", + "categorical_cols = df.select_dtypes(include=['object']).columns\n", + "print(categorical_cols)\n", + "\n", + "# Task continued below" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Now let's choose the encoders based on them\n", + "# Traffic Level is ordinal -> use label encoder\n", + "# Vehicle type, Weather, Time of day are nominal -> use one hot encoder\n", + "\n", + "from sklearn.preprocessing import OneHotEncoder\n", + "from sklearn.preprocessing import LabelEncoder\n", + "\n", + "ordinal = ['Traffic_Level']\n", + "nominal = ['Vehicle_Type', 'Weather', 'Time_of_Day']\n", + "\n", + "for ord in ordinal:\n", + " le = LabelEncoder()\n", + " df[ord] = le.fit_transform(df[ord])\n", + "\n", + "for nom in nominal:\n", + " onehot_encoder = OneHotEncoder(sparse_output=False)\n", + " categories = pd.DataFrame(df[nom])\n", + " df[nom] = onehot_encoder.fit_transform(categories)\n", + "\n", + "df[categorical_cols].head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "from sklearn.preprocessing import StandardScaler\n", + "scaler = StandardScaler()\n", + "features = df.drop(columns='Delivery_Time').columns\n", + "targets = df['Delivery_Time']\n", + "\n", + "df[features] = scaler.fit_transform(df[features])\n", + "\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", + "\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", + "\n", + "# Using KFold since we are dealing with a regressin task\n", + "import numpy as np\n", + "from sklearn.model_selection import KFold\n", + "from sklearn.ensemble import RandomForestRegressor\n", + "from sklearn.metrics import mean_squared_error\n", + "\n", + "kfold = KFold(n_splits=5, shuffle=True, random_state=42)\n", + "rf = RandomForestRegressor(n_estimators=200)\n", + "\n", + "train_losses = []\n", + "\n", + "for fold, (train_idx, test_idx) in enumerate(kfold.split(X), start=1):\n", + " print(f\"\\nTraining Fold {fold}/5..]\\n\")\n", + "\n", + " X_train, X_test = X.iloc[train_idx], X.iloc[test_idx]\n", + " y_train, y_test = y.iloc[train_idx], y.iloc[test_idx]\n", + "\n", + " rf.fit(X_train, y_train)\n", + "\n", + " y_pred = rf.predict(X_test)\n", + "\n", + " mse = mean_squared_error(y_test, y_pred)\n", + "\n", + " train_losses.append(mse)\n", + "\n", + "avg_loss = np.mean(np.array(train_losses))\n", + "#Task continued below" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "print(f\"Average MSE Across All Folds: {avg_loss}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "\n", + "importances = rf.feature_importances_\n", + "\n", + "features = X.columns\n", + "\n", + "sorted_idx = np.argsort(importances)\n", + "\n", + "plt.barh(features[sorted_idx], importances[sorted_idx])\n", + "plt.xlabel(\"Features\")\n", + "plt.ylabel(\"Importance\")\n", + "plt.title(\"Feature Importances\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "\n", + "predicted_time = rf.predict(X)\n", + "plt.hist(predicted_time, bins=30, edgecolor='black')\n", + "plt.xlabel(\"Predicted Delivery Time\")\n", + "plt.ylabel(\"Frequency\")\n", + "plt.title(\"Predicted Delivery Time Distribution\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:\n", + "from sklearn.ensemble import RandomForestRegressor\n", + "from catboost import CatBoostRegressor\n", + "\n", + "model1 = RandomForestRegressor(n_estimators=200)\n", + "model2 = CatBoostRegressor(verbose=0)\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "\n", + "# Using KFold since we are dealing with a regressin task\n", + "import numpy as np\n", + "from sklearn.model_selection import KFold\n", + "from sklearn.ensemble import RandomForestRegressor\n", + "from sklearn.metrics import mean_squared_error\n", + "\n", + "kfold = KFold(n_splits=5, shuffle=True, random_state=42)\n", + "\n", + "train_losses = []\n", + "\n", + "for fold, (train_idx, test_idx) in enumerate(kfold.split(X), start=1):\n", + " print(f\"\\nTraining Fold {fold}/5..]\\n\")\n", + "\n", + " X_train, X_test = X.iloc[train_idx], X.iloc[test_idx]\n", + " y_train, y_test = y.iloc[train_idx], y.iloc[test_idx]\n", + "\n", + " model1.fit(X_train, y_train)\n", + " model2.fit(X_train, y_train)\n", + "\n", + " y_pred1 = model1.predict(X_test)\n", + " y_pred2 = model2.predict(X_test)\n", + "\n", + " avg_pred = (y_pred1+y_pred2)/2\n", + " mse = mean_squared_error(y_test, avg_pred)\n", + "\n", + " train_losses.append(mse)\n", + "\n", + "avg_loss = np.mean(np.array(train_losses))\n", + "#Task continued below" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "print(f\"MSE of Average Predictions: {avg_loss}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Better than Random Forest alone! :)" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/168/Q2.ipynb b/submissions_extracted/168/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..b6706b739e4d0261281ec9f6e74388bd4ace3753 --- /dev/null +++ b/submissions_extracted/168/Q2.ipynb @@ -0,0 +1,380 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q2-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import os\n", + "import pandas as pd\n", + "import numpy as np\n", + "from PIL import Image\n", + "from sklearn.model_selection import train_test_split\n", + "\n", + "# Load Labels\n", + "labels_df = pd.read_csv(os.path.join(path, \"labels.csv\"))\n", + "img_dir = os.path.join(path, \"images\")\n", + "\n", + "images = []\n", + "ages = []\n", + "\n", + "# Load Images and Resize\n", + "print(\"Loading images...\")\n", + "for index, row in labels_df.iterrows():\n", + " img_name = row.iloc[0]\n", + " age = row.iloc[1]\n", + " img_path = os.path.join(img_dir, img_name)\n", + "\n", + " if os.path.exists(img_path):\n", + " img = Image.open(img_path).convert('RGB')\n", + " img_array = np.array(img) / 255.0 # Normalize pixel values to [0, 1]\n", + " images.append(img_array)\n", + " ages.append(age)\n", + "\n", + "X = np.array(images)\n", + "y = np.array(ages)\n", + "\n", + "# Transpose image dimensions to match PyTorch format (N, C, H, W)\n", + "X = np.transpose(X, (0, 3, 1, 2))\n", + "\n", + "# Split Data\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n", + "\n", + "print(f\"X_train shape: {X_train.shape}\")\n", + "print(f\"X_test shape: {X_test.shape}\")\n", + "print(f\"y_train shape: {y_train.shape}\")\n", + "print(f\"y_test shape: {y_test.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "X_train.dtype, y_train.dtype" + ], + "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", + "X_train = torch.tensor(X_train, dtype=torch.float32)\n", + "y_train = torch.tensor(y_train, dtype=torch.float32)\n", + "X_test = torch.tensor(X_test, dtype=torch.float32)\n", + "y_test = torch.tensor(y_test, dtype=torch.float32)\n", + "\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 2. Create TensorDataset objects\n", + "\n", + "from torch.utils.data import TensorDataset, DataLoader\n", + "\n", + "train_dataset = TensorDataset(\n", + " X_train, y_train\n", + ")\n", + "\n", + "test_dataset = TensorDataset(\n", + " X_test, y_test\n", + ")\n", + "\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 3. Create DataLoaders\n", + "\n", + "train_loader = DataLoader(\n", + " train_dataset,\n", + " batch_size=32,\n", + " shuffle=True,\n", + " num_workers=2\n", + ")\n", + "\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_train_batch, y_train_batch = next(iter(train_loader))\n", + "X_test_batch, y_test_batch = next(iter(test_loader))\n", + "\n", + "print(f\"Train Batch Shape for X: {X_train_batch.shape}, and for y : {y_train_batch.shape}\")\n", + "\n", + "print(f\"Test Batch Shape for X: {X_test_batch.shape}, and for y: {y_test_batch.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 5. Display sample images\n", + "\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].squeeze()[2], 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", + "\n", + "class NN4Layer(nn.Module):\n", + " def __init__(self, input_dim, hidden_dim, output_dim):\n", + " super(NN4Layer, self).__init__()\n", + "\n", + " self.layer1 = nn.Linear(input_dim, hidden_dim)\n", + " 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", + " 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", + " 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, train_loader, optimizer, criterion, device):\n", + " model.train()\n", + "\n", + " epoch_loss = 0.0\n", + "\n", + " for X_batch, y_batch in train_loader:\n", + " X_batch = X_batch.flatten(start_dim=1).to(device)\n", + " y_batch = y_batch.view(-1, 1).to(device)\n", + "\n", + " # Forward Propagation\n", + "\n", + " outputs = model(X_batch)\n", + " loss = criterion(outputs, y_batch)\n", + "\n", + " # Backward Propagation\n", + "\n", + " optimizer.zero_grad()\n", + " loss.backward()\n", + " optimizer.step()\n", + "\n", + " epoch_loss += loss.item()\n", + " avg_loss = epoch_loss/len(train_loader)\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, test_loader, criterion, device):\n", + "\n", + " model.eval()\n", + "\n", + " with torch.no_grad():\n", + " val_loss = 0.0\n", + " for X_batch, y_batch in test_loader:\n", + "\n", + " X_batch = X_batch.flatten(start_dim=1).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", + " val_loss += loss.item()\n", + "\n", + " avg_loss = val_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 = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n", + "\n", + "input_dim = 3*36*36\n", + "hidden_dim=30\n", + "output_dim=1\n", + "\n", + "model = NN4Layer(input_dim, hidden_dim, output_dim)\n", + "\n", + "criterion = nn.MSELoss()\n", + "\n", + "learning_rate = 0.001\n", + "optimizer = torch.optim.AdamW(model.parameters(), lr = learning_rate, weight_decay=.09)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Start training for 20 epochs:\n", + "NUM_EPOCHS = 20\n", + "\n", + "val_losses = []\n", + "train_losses = []\n", + "\n", + "for epoch in range(NUM_EPOCHS):\n", + " train_loss = train_one_epoch(model, train_loader, optimizer, criterion, device)\n", + "\n", + " val_loss = validate(model, test_loader, criterion, device)\n", + "\n", + " val_losses.append(val_loss)\n", + "\n", + " train_losses.append(train_loss)\n", + "\n", + " print(f\"\\nEpoch {epoch+1}/{NUM_EPOCHS}\\n\")\n", + " print(f\"Training Loss : {train_loss}, Validation Loss: {val_loss}\\n\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "plt.plot(train_losses, label=\"TRAINING\", color='blue')\n", + "plt.plot(val_losses, label=\"VALIDATION\", color='orange')\n", + "plt.xlabel(\"EPOCH\")\n", + "plt.ylabel(\"MSE Loss\")\n", + "plt.grid()\n", + "plt.legend()" + ], + "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", + "\n", + "# Move tensors back to CPU for plotting\n", + "images = images.cpu()\n", + "outputs = outputs.cpu()\n", + "labels = labels.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()[0], cmap='gray')\n", + " plt.title(f\"True: {labels[i]} | Pred: {int(outputs.squeeze()[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/168/Q3.ipynb b/submissions_extracted/168/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..24ed7f235f0c17e48e94d45bf451be61012aedda --- /dev/null +++ b/submissions_extracted/168/Q3.ipynb @@ -0,0 +1,317 @@ +{ + "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 matplotlib.pyplot as plt\n", + "import pandas as pd\n", + "import numpy as np\n", + "\n", + "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", + "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", + " if missing_values.sum() == 0:\n", + " print(\"No Missing Values Found.\")\n", + " else:\n", + " print(missing_values[missing_values>0])\n", + " print(f\"{missing_values.sum()} missing values found.\")\n", + "check_missing_values(df)\n", + "\n", + "# Task continued below" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "#Since all the data is numerical and a large portion is missing, the best choice is imputing missing values with the mean\n", + "\n", + "missing_values = df.isnull().sum()\n", + "missing_cols = missing_values[missing_values>0].index\n", + "\n", + "for col in missing_cols:\n", + " df[col] = df[col].fillna(df[col].mean())\n", + "\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "duplicates = df.duplicated().sum()\n", + "if duplicates>0:\n", + " df.drop_duplicates(inplace=True)\n", + " print(\"Duplicated removed\")\n", + "else:\n", + " print(\"no duplicates 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", + "print(categorical_cols)\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", + "scaler = StandardScaler()\n", + "features = df.drop(columns='Target').columns\n", + "df[features] = scaler.fit_transform(df[features])\n", + "df.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "\n", + "target = df['Target']\n", + "plt.bar(target.value_counts().index, target.value_counts().values, color='blue')\n", + "plt.xlabel(\"Target\")\n", + "plt.ylabel(\"Frequency\")\n", + "plt.title(\"Target Distribution\")\n", + "# Task continued below" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Target is clearly imbalanced, I must use Stratified KFold & F1 score" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "\n", + "X = df[features]\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 accuracy_score, f1_score\n", + "skf = StratifiedKFold(n_splits=5, random_state=42, shuffle=True)\n", + "\n", + "model = CatBoostClassifier(verbose=0, n_estimators=300, max_depth = 5, learning_rate=.05)\n", + "\n", + "accuracy = []\n", + "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", + " model.fit(X_train, y_train)\n", + "\n", + " y_pred = model.predict(X_test)\n", + "\n", + " accuracy.append(accuracy_score(y_test, y_pred))\n", + " f1.append(f1_score(y_test, y_pred, zero_division=0))\n", + "\n", + "acc_mean = np.mean(accuracy)\n", + "f1_mean = np.mean(f1)\n", + "\n", + "print(\"Results\\n\")\n", + "print(f\"Mean Accuracy: {acc_mean:.4f}\")\n", + "print(f\"F1 Score Mean: {f1_mean:.4f}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "\n", + "features = X.columns\n", + "importances = model.feature_importances_\n", + "sorted_idx = np.argsort(importances)\n", + "\n", + "plt.figure(figsize=(6, 10))\n", + "plt.barh(features[sorted_idx], importances[sorted_idx], color='purple')\n", + "plt.xlabel(\"Importances\")\n", + "plt.ylabel(\"Features\", fontsize=.01)\n", + "plt.title(\"Feature Importances\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "highest_import_idx = np.argsort(importances)[-1]\n", + "golden_feature=features[highest_import_idx]\n", + "print(f\"The Golden Feature is : {golden_feature}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "X = pd.DataFrame(df[golden_feature])\n", + "y = pd.DataFrame(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 accuracy_score, f1_score\n", + "skf = StratifiedKFold(n_splits=5, random_state=42, shuffle=True)\n", + "\n", + "model = CatBoostClassifier(verbose=0, n_estimators=300, max_depth = 5, learning_rate=.05)\n", + "\n", + "accuracy = []\n", + "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", + " model.fit(X_train, y_train)\n", + "\n", + " y_pred = model.predict(X_test)\n", + "\n", + " accuracy.append(accuracy_score(y_test, y_pred))\n", + " f1.append(f1_score(y_test, y_pred, zero_division=0))\n", + "\n", + "acc_mean = np.mean(accuracy)\n", + "f1_mean = np.mean(f1)\n", + "\n", + "print(\"Results\\n\")\n", + "print(f\"Mean Accuracy: {acc_mean:.4f}\")\n", + "print(f\"F1 Score Mean: {f1_mean:.4f}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Noice :)" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/169/Q1.ipynb b/submissions_extracted/169/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..2e9d2e176e55beb555a5aff72df95c01e485907b --- /dev/null +++ b/submissions_extracted/169/Q1.ipynb @@ -0,0 +1,187 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# There is some code that I didn't saved. This is the last saved version I have." + ], + "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", + "import pandas as pd\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": [ + "# 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/169/Q2.ipynb b/submissions_extracted/169/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..e9cafda9d533d5a1897e34647e65a095209da3a8 --- /dev/null +++ b/submissions_extracted/169/Q2.ipynb @@ -0,0 +1,201 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# I didn't save it and got rest" + ], + "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" + ], + "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/169/Q3.ipynb b/submissions_extracted/169/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..aad6fd8934c7cfb4cba269c8dc2816fd5433bcbf --- /dev/null +++ b/submissions_extracted/169/Q3.ipynb @@ -0,0 +1,169 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# I didn't save it and got rest" + ], + "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:" + ], + "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/17/Q1.ipynb b/submissions_extracted/17/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..6ae6aca2eb4eb141481fbf4e6afcd1fca8e018a1 --- /dev/null +++ b/submissions_extracted/17/Q1.ipynb @@ -0,0 +1,311 @@ +{ + "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, 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", + "# 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": [], + "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", + "df_data.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "df_data.head(0)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "df_data.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "df_data.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "plt.figure(figsize=(10, 5))\n", + "plt.hist(df_data['Delivery_Time'].dropna(), bins=50, edgecolor='black')\n", + "plt.title('Data 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", + "stat_cols = ['Order_ID']\n", + "df_data = df_data.dropna(subset=stat_cols).copy()\n", + "print(f\"Shape after cleaning: {df_data.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "df_data['Order_ID'] = df_data['Order_ID'].fillna('none')" + ], + "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_data)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "le = LabelEncoder()\n", + "df_data['Order_ID'] = le.fit_transform(df_data['Order_ID'])\n", + "df_data['Order_ID'] = le.fit_transform(df_data['Order_ID'])" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "from sklearn.preprocessing import MinMaxScaler\n", + "\n", + "features = df_data.columns.drop(\"Order_ID\") # DON'T SCALE THE TARGET\n", + "\n", + "scaler = MinMaxScaler()\n", + "df_data[features] = scaler.fit_transform(df_data[features])\n", + "df_data.head()\n", + "\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 6: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "feature_cols = stat_cols + ['Distance_km', 'Preparation_Time_min', 'Courier_Experience_yrs', 'Delivery_Time']\n", + "\n", + "X = df_data[feature_cols]\n", + "y = df_data['Order_ID']\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", + "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 2,3,4,5: Write your code here:\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!\")\n", + "\n", + "\n", + "\n", + "def mean_Absolute_error(y, y_hat):\n", + " return (1 / (2 * len(y))) * np.sum((y_hat - y) ** 2)\n", + "\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}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "\n", + "# Feature Scaling\n", + "scaler = StandardScaler()\n", + "X_scaled = scaler.fit_transform(X)\n", + "\n", + "# Define Model\n", + "model = LinearRegression()\n", + "\n", + "# K-Fold Cross Validation\n", + "kf = KFold(n_splits=5, shuffle=True, random_state=42)\n", + "\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", + " # Train model\n", + " model.fit(X_train, y_train)\n", + "\n", + " # Predict\n", + " y_pred = model.predict(X_test)\n", + "\n", + " # Evaluation metrics\n", + "\n", + " mae_scores.append(mean_absolute_error(y_test, y_pred))\n", + "\n", + "\n", + "\n", + "\n", + "\n", + " model = RandomForestRegressor(n_estimators=100, max_depth=20, random_state=42, n_jobs=-1)\n", + "model.fit(X_train_scaled, y_train)\n", + "print(\"Model trained!\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 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='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/17/Q2.ipynb b/submissions_extracted/17/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..8b14ca9e30847cf0b8df4530c9dca6b244333b07 --- /dev/null +++ b/submissions_extracted/17/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", + "\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 2. Create TensorDataset objects\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", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 3. Create DataLoaders\n", + "\n", + "import torch\n", + "\n", + "# 1️⃣ Flatten - Convert any shape to (batch_size, features)\n", + "x = torch.randn(32, 3, 28, 28)\n", + "x_flat = x.flatten(start_dim=1)\n", + "print(\"Flatten:\", x_flat.shape) # (32, 2352)\n", + "\n", + "# 2️⃣ Squeeze - Remove dimensions with size 1\n", + "x = torch.randn(1, 3, 28, 28)\n", + "x_sq = x.squeeze()\n", + "print(\"Squeeze:\", x_sq.shape) # (3, 28, 28)\n", + "\n", + "# 3️⃣ Unsqueeze - Add a new dimension of size 1\n", + "x = torch.randn(3, 28, 28)\n", + "x_unsq = x.unsqueeze(0)\n", + "print(\"Unsqueeze:\", x_unsq.shape) # (1, 3, 28, 28)\n", + "\n", + "# 4️⃣ View - Reshape freely while keeping same number of elements\n", + "x = torch.randn(32, 28, 28, 3)\n", + "x_view = x.view(32, -1) # Flatten all except batch\n", + "print(\"View:\", x_view.shape) # (32, 28*28*3)\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/17/Q3.ipynb b/submissions_extracted/17/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..6773ce99a38083da25a9c38fa7feeac5b6308a6d --- /dev/null +++ b/submissions_extracted/17/Q3.ipynb @@ -0,0 +1,183 @@ +{ + "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", + "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", + "df_data.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "df_data.head(0)\n" + ], + "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:" + ], + "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_data)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "x = torch.tensor([1.0, 2.0, 3.0])\n", + "y = torch.randn(3)\n", + "print(\"x:\", x)\n", + "print(\"y:\", y)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 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/170/Q1.ipynb b/submissions_extracted/170/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..bd5ccebed22ca497126f4ca55e8131bf953e54ca --- /dev/null +++ b/submissions_extracted/170/Q1.ipynb @@ -0,0 +1,385 @@ +{ + "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", + "\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", + "%matplotlib inline\n", + "\n", + "import kagglehub" + ], + "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": [], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "\n", + "csv_path = os.path.join(path, \"Q1_data.csv\")\n", + "\n", + "df = pd.read_csv(csv_path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "\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 5: Write your code here:\n", + "\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\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "df=df.drop(\"Order_ID\", axis=1)\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "def check_missing_values(df):\n", + " missing_values = df.isnull().sum()\n", + " print(\"Missing Values per Column:\")\n", + " print(missing_values[missing_values > 0])\n", + " if missing_values.any():\n", + " print(\"\\nHandle Missing Values as needed.\")\n", + " else:\n", + " print(\"\\nNo Missing Values Found.\")\n", + "\n", + "check_missing_values(df)\n", + "\n", + "#---------------------------\n", + "\n", + "# Fill cylinders with mode - discrete feature, mode is most representative\n", + "\n", + "df['Traffic_Level'] = df['Traffic_Level'].fillna(df['Traffic_Level'].mode()[0])\n", + "df['Weather'] = df['Weather'].fillna('unknown')\n", + "df['Time_of_Day'] = df['Time_of_Day'].fillna(df['Time_of_Day'].mode()[0])\n", + "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", + "\n", + "\n", + "print(\"Missing values remaining:\", df.isnull().sum().sum())\n", + "\n", + "\n", + "\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "def check_duplicates(df):\n", + " duplicates = df.duplicated().sum()\n", + " print(f\"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", + "\n", + "# 3. Do we have categorical columns s oto Encode?\n", + "categorical_cols = df.select_dtypes(include=[\"object\"]).columns\n", + "\n", + "print(\"Categorical Columns:\", list(categorical_cols))\n", + "\n", + "\n", + "\n", + "\n", + "from sklearn.preprocessing import LabelEncoder\n", + "\n", + "label_encoders = {}\n", + "for col in categorical_cols:\n", + " le = LabelEncoder()\n", + " df[col] = le.fit_transform(df[col])\n", + " label_encoders[col] = le\n", + "\n", + "df" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: 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", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 6: Write your code here:\n", + "\n", + "# 1. Is the target imbalanced?\n", + "def check_target_imbalance(df, target_column):\n", + " print(\"Target Distribution:\")\n", + " 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", + "\n", + "from sklearn.ensemble import RandomForestClassifier\n", + "\n", + "X = df.drop(\"Delivery_Time\", axis=1).astype(float)y = df['Delivery_Time'].astype(float)\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", + "# 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", + "\n", + "# Predict and evaluate\n", + "y_pred = model.predict(X_test_scaled)\n", + "\n", + "mae = mean_absolute_error(y_test, y_pred)\n", + "r\n", + "\n", + "print(f\"MAE: ${mae:,.2f}\")\n", + "\n", + "\n", + "\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_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", + "\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": [ + "# 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" + ], + "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/170/Q3.ipynb b/submissions_extracted/170/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..1597ddfcfdac0fe2b0627c6dd464b0bf5dbae1c0 --- /dev/null +++ b/submissions_extracted/170/Q3.ipynb @@ -0,0 +1,351 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import pandas as pd\n", + "import numpy as np\n", + "import matplotlib.pyplot as plt\n", + "import seaborn as sns\n", + "import kagglehub\n", + "import os\n", + "from tqdm import tqdm\n", + "\n", + "%matplotlib inline\n", + "\n", + "import kagglehub\n", + "\n", + "\n", + "\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", + "# Task 1: Write your code here:\n", + "\n", + "csv_path = os.path.join(path, \"Q3_data.csv\")\n", + "\n", + "df = pd.read_csv(csv_path)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "\n", + "df.head()\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "\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", + "\n", + "\n", + "# Task 2: Write your code here:\n", + "def check_missing_values(df):\n", + " missing_values = df.isnull().sum()\n", + " print(\"Missing Values per Column:\")\n", + " print(missing_values[missing_values > 0])\n", + " if missing_values.any():\n", + " print(\"\\nHandle Missing Values as needed.\")\n", + " else:\n", + " print(\"\\nNo Missing Values Found.\")\n", + "\n", + "check_missing_values(df)\n", + "\n", + "\n", + "\n", + "# 3. Do we have categorical columns s oto Encode?\n", + "categorical_cols = df.select_dtypes(include=[\"object\"]).columns\n", + "\n", + "print(\"Categorical Columns:\", list(categorical_cols))\n", + "\n", + "\n", + "for col in df :\n", + " df[col]=df[col].fillna(df[col].mode()[0])\n", + "\n", + "\n", + "\n", + "print(\"Missing values remaining:\", df.isnull().sum().sum())\n", + "\n", + "\n", + "\n", + "\n", + "\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)\n", + "\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "\n", + "\n", + "# 3. Do we have categorical columns s oto Encode?\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", + "\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", + "# Task 6: Write your code here:\n", + "\n", + "# 1. Is the target imbalanced?\n", + "def check_target_imbalance(df, target_column):\n", + " print(\"Target Distribution:\")\n", + " 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" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "from sklearn.ensemble import RandomForestClassifier\n", + "\n", + "X = df.drop(\"Target\", axis=1).astype(float)\n", + "y = df['Target'].astype(float)\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "\n", + "\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", + "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", + "sklearn_models = {\n", + " \"CatBoost\": CatBoostClassifier(\n", + " verbose=0,\n", + " n_estimators=320,\n", + " max_depth=4\n", + " )\n", + "}\n", + "\n", + "n_splits = 5 # K\n", + "\n", + "# Stratified 5-Fold Cross-Validation, shuffled\n", + "skf = StratifiedKFold(n_splits=n_splits, shuffle=True, random_state=42)\n", + "\n", + "\n", + "for fold_idx, (train_index, test_index) in enumerate(skf.split(X, y)):\n", + " print(f\"\\nFold {fold_idx + 1}/{n_splits}\")\n", + "\n", + " # 1. Split data\n", + " X_train, X_test = X.iloc[train_index], X.iloc[test_index]\n", + " y_train, y_test = y.iloc[train_index], y.iloc[test_index]\n", + "\n", + " # 2. Train & Validate sklearn models\n", + " for model_name, model in sklearn_models.items():\n", + " print(f\"Training {model_name}...\")\n", + " model.fit(X_train, y_train) # train\n", + " y_pred = model.predict(X_test) # validate\n", + "\n", + " # 3. Save metrics for that model in this fold\n", + " accuracy = accuracy_score(y_test, y_pred)\n", + " precision = precision_score(y_test, y_pred, zero_division=0)\n", + " recall = recall_score(y_test, y_pred, zero_division=0)\n", + " f1 = f1_score(y_test, y_pred, zero_division=0)\n", + "\n", + " all_results[model_name]['accuracy'].append(accuracy)\n", + " all_results[model_name]['precision'].append(precision)\n", + " all_results[model_name]['recall'].append(recall)\n", + " all_results[model_name]['f1'].append(f1)\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "\n", + "# 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()\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/171/Q1.ipynb b/submissions_extracted/171/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..9b0934b81bcf1eb30f1b2730ebdbd77211ce2f90 --- /dev/null +++ b/submissions_extracted/171/Q1.ipynb @@ -0,0 +1,299 @@ +{ + "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": [ + "# Task 1: Write your code here:\n", + "import pandas as pd\n", + "import os\n", + "csv_path = os.path.join(path, \"Q1_data.csv\")\n", + "\n", + "df = pd.read_csv(csv_path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "df.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "df.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "import matplotlib.pyplot as plt\n", + "plt.figure(figsize=(10, 5))\n", + "plt.hist(df['Delivery_Time'].dropna(), bins=50, edgecolor='black')\n", + "plt.title('Delivery_Time Distribution')\n", + "plt.xlabel('Delivery_Time')\n", + "plt.ylabel('Frequency')\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "import matplotlib.pyplot as plt\n", + "import seaborn as sns\n", + "print(\"\\nValue counts for the target variable 'Delivery_Time':\")\n", + "class_distribution = df['Delivery_Time'].value_counts()\n", + "print(class_distribution)\n", + "\n", + "plt.figure(figsize=(6, 4))\n", + "sns.countplot(data=df, x='Delivery_Time')\n", + "plt.title('Distribution of Target Variable (Delivery_Time)')\n", + "plt.xlabel('Delivery_Time')\n", + "plt.ylabel('Count')\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "df.drop(columns=['Order_ID'], inplace=True)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "\n", + "df.drop(columns=['Courier_Experience_yrs'])\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "print(\"Checking for duplicate rows\")\n", + "duplicate_rows = df.duplicated().sum()\n", + "if duplicate_rows > 0:\n", + " print(f\"Found {duplicate_rows} duplicate rows. Removing them\")\n", + " df.drop_duplicates(inplace=True)\n", + " print(\"Duplicate rows removed\")\n", + "else:\n", + " print(\"No duplicate rows found\")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "from sklearn.preprocessing import OneHotEncoder #import OneHotEncoder\n", + "import pandas as pd\n", + "\n", + "Weather = pd.DataFrame({\"Weather\": ['Windy', 'Snowy', 'Foggy', 'Clear', 'Rainy']}) # DataFrame of one column\n", + "print(\"Before encoding:\")\n", + "Weather\n", + "\n", + "print('data before encoding:\\n', Weather) #show before encoding\n", + "onehot_encoder = OneHotEncoder(sparse_output=False) # Instantiate OneHotEncoder\n", + "data_onehot_encoded = onehot_encoder.fit_transform(Weather) # 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: Write your code here:\n", + "from sklearn.preprocessing import StandardScaler\n", + "\n", + "scaler = StandardScaler()\n", + "data_scaled = scaler.fit_transform(df[numerical_cols])" + ], + "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", + "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": [ + "X = df.drop(\"Target column\",axis=1)\n", + "y = df['Target column']\n", + "x_train, x_test, y_train, y_test = train_test_split(X, y, test_size=0.3)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:\n", + "from sklearn.model_selection import KFold\n", + "from sklearn.metrics import mean_squared_error as sklearn_mse, mean_absolute_error, r2_score\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_scores.append(mean_absolute_error(y_test, y_pred))\n", + "\n", + " # Store results\n", + " all_results[model_name][\"mae\"].append(mae)" + ], + "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/171/Q2.ipynb b/submissions_extracted/171/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..893c0327aadc4e6eefb2109ddd8fedbb02e0ffaa --- /dev/null +++ b/submissions_extracted/171/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", + "from sklearn.preprocessing import StandardScaler\n", + "from torch.utils.data import DataLoader, TensorDataset\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", + "\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.long)\n", + "X_test_tensor = torch.tensor(X_test, dtype=torch.float32)\n", + "y_test_tensor = torch.tensor(y_test, dtype=torch.long)\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)" + ], + "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/171/Q3.ipynb b/submissions_extracted/171/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..41ef67263270d38084282532e726da391096b722 --- /dev/null +++ b/submissions_extracted/171/Q3.ipynb @@ -0,0 +1,168 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "\n", + "\n", + "# Download latest version\n", + "\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q3-exam-data\")\n", + "\n", + "\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "import pandas as pd\n", + "import os\n", + "csv_path = os.path.join(path, \"Q3_data.csv\")\n", + "\n", + "df = pd.read_csv(csv_path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "df.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "df.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n" + ], + "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/172/Q1.ipynb b/submissions_extracted/172/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..65764f97f76ae81a5164f41ca546cbe7d5ecf39a --- /dev/null +++ b/submissions_extracted/172/Q1.ipynb @@ -0,0 +1,306 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "import pandas as pd\n", + "import matplotlib.pyplot as plt\n", + "import os\n", + "import numpy as pd\n", + "from sklearn.preprocessing import StandardScaler, LabelEncoder\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" + ], + "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", + "dfr = pd.read_csv(df_path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "dfr.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "dfr.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "dfr.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "plt.figure(figsize=(7, 8))\n", + "plt.hist(dfr['Delivery_Time'], bins=30, edgecolor='darkblue')" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "dfc = dfr.copy()\n", + "dfc.drop(columns=['Order_ID'], axis =1)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "dfc.isnull().sum()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "dfc['Weather'] = dfc['Weather'].fillna(dfc['Weather'].mode()[0])\n", + "dfc['Courier_Experience_yrs'] = dfc['Courier_Experience_yrs'].fillna(dfc['Courier_Experience_yrs'].median())\n", + "dfc['Delivery_Time'] = dfc['Delivery_Time'].fillna(dfc['Delivery_Time'].median())\n", + "dfc['Traffic_Level'] = dfc['Traffic_Level'].fillna(dfc['Traffic_Level'].mode()[0])\n", + "dfc['Time_of_Day'] = dfc['Time_of_Day'].fillna(dfc['Time_of_Day'].mode()[0])" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "dfc.isnull().sum()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "from sklearn.preprocessing import LabelEncoder" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "categorical_cols = ['Weather',\t'Traffic_Level',\t'Time_of_Day',\t'Vehicle_Type']\n", + "for c in categorical_cols:\n", + " encoder = LabelEncoder()\n", + " dfc[c] = encoder.fit_transform(dfc[c].astype(str))\n", + "dfc.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "from sklearn.preprocessing import StandardScaler" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "x = dfc[[\t'Distance_km',\t'Weather',\t'Traffic_Level',\t'Time_of_Day',\t'Vehicle_Type',\t'Preparation_Time_min',\t'Courier_Experience_yrs']]\n", + "y = dfc['Delivery_Time']" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "ss = StandardScaler()" + ], + "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.model_selection import train_test_split, KFold\n", + "import numpy as np" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "X_train, y_train, X_test, y_test = train_test_split(x, y,test_size=0.2, shuffle=True, random_state=42)\n", + "\n", + "scaler = StandardScaler()\n", + "X_train_scaled = scaler.fit_transform(X_train)\n", + "X_test_scaled = scaler.transform(X_test)\n", + "\n", + "print(f\"\\nScaled ranges - Min: {X_train_scaled.min():.2f}, Max: {X_train_scaled.max():.2f}\")\n", + "pd.DataFrame(X_train_scaled, columns=X_train.columns).head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "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_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", + " RF.fit(X_fold_train, y_fold_train)\n", + " y_fold_pred = RF.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}\")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "from sklearn.ensemble import RandomForestRegressor as RF\n", + "from sklearn.metrics import mean_absolute_error" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:\n", + "RF = RandomForestRegressor(n_estimators=100, max_depth=20, random_state=42, n_jobs=-1)\n", + "RF.fit(X_train_scaled, y_train)\n", + "print('Model training finshed')\n", + "\n", + "y_pred = RF.predict(X_test)\n", + "mae = mean_absolute_error(y_test, y_pred)\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/172/Q2.ipynb b/submissions_extracted/172/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..41385d3b9642c19b1cf2e63491268f75ab03556e --- /dev/null +++ b/submissions_extracted/172/Q2.ipynb @@ -0,0 +1,342 @@ +{ + "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 torch.nn.functional as F\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import os\n", + "import pandas as pd\n", + "import numpy as np\n", + "from PIL import Image\n", + "from sklearn.model_selection import train_test_split\n", + "\n", + "# Load Labels\n", + "labels_df = pd.read_csv(os.path.join(path, \"labels.csv\"))\n", + "img_dir = os.path.join(path, \"images\")\n", + "\n", + "images = []\n", + "ages = []\n", + "\n", + "# Load Images and Resize\n", + "print(\"Loading images...\")\n", + "for index, row in labels_df.iterrows():\n", + " img_name = row.iloc[0]\n", + " age = row.iloc[1]\n", + " img_path = os.path.join(img_dir, img_name)\n", + "\n", + " if os.path.exists(img_path):\n", + " img = Image.open(img_path).convert('RGB')\n", + " img_array = np.array(img) / 255.0 # Normalize pixel values to [0, 1]\n", + " images.append(img_array)\n", + " ages.append(age)\n", + "\n", + "X = np.array(images)\n", + "y = np.array(ages)\n", + "\n", + "# Transpose image dimensions to match PyTorch format (N, C, H, W)\n", + "X = np.transpose(X, (0, 3, 1, 2))\n", + "\n", + "# Split Data\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n", + "\n", + "print(f\"X_train shape: {X_train.shape}\")\n", + "print(f\"X_test shape: {X_test.shape}\")\n", + "print(f\"y_train shape: {y_train.shape}\")\n", + "print(f\"y_test shape: {y_test.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "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" + ], + "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", + "train_dataset = TensorDataset(X_train, y_train)\n", + "test_dataset = TensorDataset(X_test, y_test)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 2. Create TensorDataset objects\n", + "train_dataset = TensorDataset(X_train, y_train)\n", + "test_dataset = TensorDataset(X_test, y_test)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 3. Create DataLoaders\n", + "train_loader = DataLoader(train_dataset, batch_size=32, shuffle=True)\n", + "test_loader = DataLoader(test_dataset, batch_size=32, shuffle=False)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 4. Print shape of one batch\n", + "print(\"Train dataset:\", len(train_dataset))\n", + "print(\"Test dataset:\", len(test_dataset))" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 5. Display sample images\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your model class here:\n", + "class NNFourLayer(nn.Module):\n", + "\n", + " def __init__(self, input_dim, hidden_dim, output_dim):\n", + " super(NNFourLayer, 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", + " # hidden layers\n", + " a1 = self.relu(self.layer1(x))\n", + " a2 = self.relu(self.layer2(a1))\n", + " a3 = self.relu(self.layer3(a2))\n", + "\n", + " output = self.layer4(a3)\n", + "\n", + " return output\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your training loop here:\n", + "def train_one_epoch(model, optimizer, criterion, train_loader, device):\n", + " model.train()\n", + "\n", + " running_loss = 0.0\n", + "\n", + " for X_batch, y_batch in train_loader:\n", + " X_batch = X_batch.to(device)\n", + " y_batch = y_batch.to(device)\n", + "\n", + " # Forward pass\n", + " outputs = model(X_batch)\n", + " loss = criterion(outputs, y_batch)\n", + "\n", + " # Backward pass, optimization\n", + " optimizer.zero_grad()\n", + " loss.backward()\n", + " optimizer.step()\n", + "\n", + " running_loss += loss.item()\n", + "\n", + " # Average loss over all batches\n", + " avg_loss = running_loss / len(train_loader)\n", + "\n", + " return avg_loss" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your validation loop here:\n", + "def validate(model, criterion, test_loader, device):\n", + " 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", + " X_batch = X_batch.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", + " # Softmax\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", + "print(f\"Using device: {device}\")\n", + "\n", + "" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "from torch.optim import Adam\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", + "# Model, Criterion, Optimizer\n", + "input_dim = X_train.shape[1]\n", + "hidden_dim = 10\n", + "criterion = nn.BCELoss()\n", + "optimizer = Adam(NNFourLayer.parameters(), lr=learning_rate)\n", + "\n", + "\n", + "# Run Training\n", + "train_losses = []\n", + "val_losses = []\n", + "val_accuracies = []\n", + "for epoch in range(num_epochs):\n", + " # Train one epoch\n", + " train_loss = train_one_epoch(NNFourLayer, optimizer, criterion, train_loader, device)\n", + "\n", + " # Validate\n", + " val_loss, val_accuracy = validate(NNFourLayer, 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" + ], + "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/172/Q3.ipynb b/submissions_extracted/172/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..1aed8009fd23faec457a985fb3d5e6154174ce7c --- /dev/null +++ b/submissions_extracted/172/Q3.ipynb @@ -0,0 +1,223 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "import pandas as pd\n", + "import os\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", + "df_path = os.path.join(path,'Q3_data.csv' )\n", + "dfr = pd.read_csv(df_path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "dfr.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "dfr.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "dfr.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "dfr.isnull().sum()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "dfr['P_2'] = dfr['P_2'].fillna(dfr['P_2'].median())\n", + "dfr['D_142'] = dfr['D_142'].fillna(dfr['D_142'].median())\n", + "dfr['B_2'] = dfr['B_2'].fillna(dfr['B_2'].median())\n", + "dfr['D_143'] = dfr['D_143'].fillna(dfr['D_143'].median())\n", + "dfr['D_144'] = dfr['D_144'].fillna(dfr['D_144'].median())\n", + "dfr['D_145'] = dfr['D_145'].fillna(dfr['D_145'].median())\n", + "dfr['D_43'] = dfr['D_43'].fillna(dfr['D_43'].median())\n", + "dfr['D_42'] = dfr['D_42'].fillna(dfr['D_42'].median())\n", + "dfr['D_43'] = dfr['D_43'].fillna(dfr['D_43'].median())\n", + "dfr['D_137'] = dfr['D_137'].fillna(dfr['D_137'].median())\n", + "dfr['D_138'] = dfr['D_138'].fillna(dfr['D_138'].median())\n", + "dfr.isnull().sum()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "print(dfr.duplicated().sum())" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "dfr['P_2'] = dfr['P_2'].fillna(dfr['P_2'].median())\n", + "dfr['D_142'] = dfr['D_142'].fillna(dfr['D_142'].median())\n", + "dfr['B_2'] = dfr['B_2'].fillna(dfr['B_2'].median())\n", + "dfr['D_143'] = dfr['D_143'].fillna(dfr['D_143'].median())\n", + "dfr['D_144'] = dfr['D_144'].fillna(dfr['D_144'].median())\n", + "dfr['D_145'] = dfr['D_145'].fillna(dfr['D_145'].median())\n", + "dfr.isnull().sum()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "from sklearn.preprocessing import StandardScaler\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "# NO need for it" + ], + "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", + "ss = StandardScaler()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "dfc = dfr.drop(columns=['P_2'], axis=1)\n", + "dfc = ss.fit_transform(dfr.columns)" + ], + "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/173/Q1.ipynb b/submissions_extracted/173/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..fa770008b4b2b13b6430b49aaae085b0f8d8a95f --- /dev/null +++ b/submissions_extracted/173/Q1.ipynb @@ -0,0 +1,285 @@ +{ + "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", + "from sklearn.preprocessing import StandardScaler, LabelEncoder\n", + "from sklearn.model_selection import KFold\n", + "from sklearn.linear_model import LinearRegression\n", + "from sklearn.metrics import mean_squared_error, mean_absolute_error\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(f\"{path}/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": [ + "def check_target_distribution(df, delivery_time):\n", + " df[delivery_time].figure(bins=30, edgecolor='black')\n", + "\n", + "plt.title(f\"Target Distribution ({delivery_time})\")\n", + "plt.xlabel(delivery_time)\n", + "plt.ylabel(\"Frequency\")\n", + "plt.grid(False)\n", + "\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "cols = ['Order_ID',\t'Distance_km',\t'Preparation_Time_min',\t'Courier_Experience_yrs',\t'Delivery_Time']\n", + "df_clean = df[cols].copy()\n", + "df_clean = df_clean.dropna(subset=['Order_ID'])" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "df_clean['Courier_Experience_yrs'] = df_clean['Courier_Experience_yrs'].fillna(df_clean['Courier_Experience_yrs'].mean())" + ], + "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": [ + "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": [ + "standard_scaler = StandardScaler() # Instantiate StandardScaler\n", + "data_standard_scaled = standard_scaler.fit_transform('Weather', 'Traffic_Level',\t'Time_of_Day',\t'Vehicle_Type') # 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": [ + "def check_target_imbalance(df, delivery_time):\n", + " print(\"Target Distribution:\")\n", + "\n", + " df[delivery_time].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", + "\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42, stratify=y)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:\n", + "\n", + "n_splits = 5 # K=5 Folds\n", + "\n", + "# 5-Fold Cross-Validation, shuffled\n", + "kf = KFold(n_splits=n_splits, shuffle=True, random_state=42)\n", + "\n", + "# Storage for linear regression results for each fold\n", + "lr_losses = []\n", + "lr_mse = []\n", + "lr_rmse = []\n", + "lr_r2 = []\n", + "\n", + "for fold_idx, (train_index, test_index) in enumerate(kf.split(X)):\n", + " print(f\"\\nFold {fold_idx + 1}/{n_splits}\")\n", + "\n", + " X_train, X_test = X.iloc[train_index], X.iloc[test_index]\n", + " y_train, y_test = y.iloc[train_index], y.iloc[test_index]\n", + "\n", + " # 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", + "model = RandomForestClassifier(n_estimators=100, max_depth=20, random_state=42, n_jobs=-1, class_weight='balanced')\n", + "model.fit(X_train_scaled, y_train)\n", + "print(\"Model trained!\")\n", + "\n", + "mae = mean_absolute_error(y_test.numpy(), predictions)\n", + "print(\"Model Evaluation\")\n", + "print(f\" MAE: ${mae:.2f}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\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 Delivery time', fontsize=12)\n", + "plt.ylabel('Predicted delivery time', fontsize=12)\n", + "plt.title('Predicted vs Actual delivery time', fontsize=14)\n", + "plt.legend()\n", + "plt.grid(True, alpha=0.3)\n", + "\n", + "plt.tight_layout()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "\n", + "plt.figure(figsize=(10, 5))\n", + "plt.hist(df_cars['price'].dropna(), bins=50, edgecolor='black')\n", + "plt.title('Delivery time')\n", + "plt.xlabel('Delivery time')\n", + "plt.ylabel('Frequency')\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/173/Q2.ipynb b/submissions_extracted/173/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..4ddc206f28f8742872785cbf9060daf31d296fdd --- /dev/null +++ b/submissions_extracted/173/Q2.ipynb @@ -0,0 +1,418 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q2-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import os\n", + "import pandas as pd\n", + "import numpy as np\n", + "from PIL import Image\n", + "from sklearn.model_selection import train_test_split\n", + "\n", + "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", + "import torch\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", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 2. Create TensorDataset objects\n", + "from torch.utils.data import TensorDataset\n", + "train_dataset = TensorDataset(X_train, y_train)\n", + "test_dataset = TensorDataset(X_test, y_test)\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "train_loader = DataLoader(\n", + " train_dataset,\n", + " batch_size=32,\n", + " shuffle=True,\n", + " num_workers=2\n", + ")\n", + "# DataLoader for test/validation data\n", + "test_loader = DataLoader(\n", + " test_dataset,\n", + " batch_size=32,\n", + " shuffle=False,\n", + " num_workers=2\n", + ")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 4. Print shape of one batch\n", + "\n", + "# Get the first batch from the training DataLoader\n", + "X_batch, y_batch = next(iter(train_loader))\n", + "print(f\"Training batch input shape: {X_batch.shape}\")\n", + "print(f\"Training batch labels shape: {y_batch.shape}\")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 5. Display sample images\n", + "\n", + "images, labels = next(iter(train_loader))\n", + "\n", + "# Display the first 6 images in the batch\n", + "plt.figure(figsize=(8, 4))\n", + "\n", + "for i in range(6):\n", + " plt.subplot(2, 3, i + 1)\n", + " plt.imshow(images[i].squeeze(), cmap='gray')\n", + " plt.title(f\"Label: {labels[i].item()}\")\n", + " plt.axis('off')\n", + "\n", + "plt.tight_layout()\n", + "plt.show()\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your model class here:\n", + "\n", + "class NN3Layer(nn.Module):\n", + "\n", + " def __init__(self, input_dim, hidden_dim, output_dim):\n", + " super(NN3Layer, self).__init__()\n", + "\n", + " # First linear layer: input features -> hidden layer\n", + " self.layer1 = nn.Linear(input_dim, hidden_dim)\n", + "\n", + " # Second linear layer: hidden layer -> hidden layer\n", + " self.layer2 = nn.Linear(hidden_dim, hidden_dim)\n", + "\n", + " # Output layer: hidden layer -> number of classes (logits)\n", + " self.layer3 = nn.Linear(hidden_dim, output_dim)\n", + "\n", + " # ReLU activation for non-linearity\n", + " self.relu = nn.ReLU()\n", + "\n", + " # Defines how input data flows through the network\n", + " def forward(self, x):\n", + " # First hidden layer\n", + " z1 = self.layer1(x)\n", + " a1 = self.relu(z1)\n", + "\n", + " # Second hidden layer\n", + " z2 = self.layer2(a1)\n", + " a2 = self.relu(z2)\n", + "\n", + " # Output layer (raw scores / logits)\n", + " output = self.layer3(a2) # there is something missing here, remember? :)\n", + "\n", + " return output\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your training loop here:\n", + "\n", + "def train_one_epoch(model, optimizer, criterion, train_loader, device):\n", + " # Set the model to training mode\n", + " model.train()\n", + "\n", + " running_loss = 0.0\n", + "\n", + " for X_batch, y_batch in train_loader:\n", + " # Move batch to the selected device\n", + " X_batch = X_batch.view(X_batch.size(0), -1).to(device)\n", + " y_batch = y_batch.to(device)\n", + "\n", + " # Forward pass\n", + " outputs = model(X_batch) # shape: (batch_size, 10)\n", + " loss = criterion(outputs, y_batch)\n", + "\n", + " # Backward pass & optimization\n", + " optimizer.zero_grad() # Clear previous gradients\n", + " loss.backward() # Compute gradients\n", + " optimizer.step() # Update model parameters\n", + "\n", + " running_loss += loss.item()\n", + "\n", + " # Average loss over all batches\n", + " avg_loss = running_loss / len(train_loader)\n", + "\n", + " return avg_loss" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your validation loop here:\n", + "\n", + "def validate(model, criterion, test_loader, device):\n", + " # Set the model to evaluation mode\n", + " model.eval()\n", + "\n", + " running_loss = 0.0\n", + " correct = 0\n", + " total = 0\n", + "\n", + " with torch.no_grad():\n", + " for X_batch, y_batch in test_loader:\n", + " # Move data to device\n", + " X_batch = X_batch.view(X_batch.size(0), -1).to(device)\n", + " y_batch = y_batch.to(device)\n", + "\n", + " # Forward pass\n", + " outputs = model(X_batch) # shape: (batch_size, 10)\n", + " loss = criterion(outputs, y_batch)\n", + " running_loss += loss.item()\n", + "\n", + " # Apply Softmax to get probabilities\n", + " probabilities = F.softmax(outputs, dim=1)\n", + "\n", + " # Multiclass predictions\n", + " predicted = torch.argmax(probabilities, dim=1)\n", + "\n", + " # Accuracy calculation\n", + " correct += (predicted == y_batch).sum().item()\n", + " total += y_batch.size(0)\n", + "\n", + " avg_loss = running_loss / len(test_loader)\n", + " accuracy = correct / total\n", + "\n", + " return avg_loss, accuracy" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Define device, model, loss, optimizer:\n", + "\n", + "# Device setup\n", + "device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n", + "\n", + "# Model parameters\n", + "input_dim = 28 * 28 # MNIST images flattened\n", + "hidden_dim = 14 # Design choice\n", + "output_dim = 10 # Digits 0–9\n", + "\n", + "# Instantiate model\n", + "model = NN3Layer(input_dim, hidden_dim, output_dim).to(device)\n", + "\n", + "# Print the model architecture\n", + "print(\"Model Architecture:\\n\")\n", + "print(model)\n", + "\n", + "# Calculate the total number of trainable parameters\n", + "total_params = sum(p.numel() for p in model.parameters() if p.requires_grad)\n", + "print(f\"\\nTotal trainable parameters: {total_params}\")\n", + "\n", + "num_epochs = 10\n", + "learning_rate = 0.001\n", + "\n", + "# Define criterion (loss function) - using CrossEntropyLoss as model now outputs logits\n", + "criterion = nn.CrossEntropyLoss()\n", + "# Define optimizer\n", + "optimizer = Adam(model.parameters(), learning_rate)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Start training for 20 epochs:\n", + "\n", + "# Run Training\n", + "train_losses = []\n", + "val_losses = []\n", + "val_accuracies = []\n", + "\n", + "print('Starting Training...')\n", + "for epoch in range(20):\n", + " # Train one epoch\n", + " train_loss = train_one_epoch(model, optimizer, criterion, train_loader, device)\n", + "\n", + " # Validate\n", + " val_loss, 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/173/Q3.ipynb b/submissions_extracted/173/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..8856d182c26395091404f7e27222aa0fceac699b --- /dev/null +++ b/submissions_extracted/173/Q3.ipynb @@ -0,0 +1,278 @@ +{ + "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", + "from sklearn.preprocessing import StandardScaler, LabelEncoder\n", + "from sklearn.model_selection import KFold\n", + "from sklearn.linear_model import LinearRegression\n", + "from sklearn.metrics import mean_squared_error, mean_absolute_error\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", + "\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()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "df.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "df.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "\n", + "def check_missing_values(df):\n", + "\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)\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", + "\n", + "label_encoders = {}\n", + "for col in categorical_cols:\n", + " le = LabelEncoder()\n", + " df[col] = le.fit_transform(df[col])\n", + " label_encoders[col] = le" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "\n", + "from sklearn.preprocessing import StandardScaler\n", + "\n", + "numerical_cols = df.select_dtypes(include=[\"int64\", \"float64\"]).columns.drop(\"status\") # 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", + "def check_target_imbalance(df, TARGET):\n", + " print(\"Target Distribution:\")\n", + "\n", + " df[TARGET].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", + "\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42, stratify=y)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: 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 {ANON}...\")\n", + "\n", + " # Fit the model on train data\n", + " model.fit(X_train, y_train)\n", + "\n", + " # Use the model to predict the test data\n", + " y_pred = model.predict(X_test)\n", + "\n", + " # Calculate evaluation metrics\n", + " accuracy = accuracy_score(y_test, y_pred)\n", + " f1 = f1_score(y_test, y_pred, average='macro') # for multiclass f1 score, you should set the average hyperparameter (\"macro\", \"micro\", \"weighted\")\n", + "\n", + " results[model_name]['accuracy'].append(accuracy)\n", + " results[model_name]['f1'].append(f1)\n", + "\n", + " for model_name in results:\n", + " print(f\"\\n{model_name}:\")\n", + " # Print the average of each evaluation metric across folds\n", + " print(f\" Accuracy: {np.mean(results[ANON]['accuracy']):.4f}\")\n", + " print(f\" F1-Score: {np.mean(results[ANON]['f1']):.4f}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "\n", + "# Task 1: Write your code here:\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 Delivery time', fontsize=12)\n", + "plt.ylabel('Predicted delivery time', fontsize=12)\n", + "plt.title('Predicted vs Actual delivery time', fontsize=14)\n", + "plt.legend()\n", + "plt.grid(True, alpha=0.3)\n", + "\n", + "plt.tight_layout()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "\n", + "print(\"The most important feature is P_2\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/174/Q1.ipynb b/submissions_extracted/174/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..d74b35cb4f233cb475d0a1fadfc0baa49d66e7ee --- /dev/null +++ b/submissions_extracted/174/Q1.ipynb @@ -0,0 +1,379 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q1-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "from pathlib import Path\n", + "import os\n", + "import pandas as pd\n", + "# Task 1: Write your code here:\n", + "delivery_path= os.path.join( path ,'Q1_data.csv')\n", + "df_delivery= pd.read_csv (delivery_path)\n", + "\n", + "print(f\"Dataset shape:{df_delivery.shape}\")\n", + "df_delivery.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "df_delivery.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "\n", + "df_delivery.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "import matplotlib.pyplot as plt\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Price distribution (target variable)\n", + "plt.figure(figsize=(10, 5))\n", + "plt.hist(df_delivery['Distance_km'].dropna(), bins=50, edgecolor='black')\n", + "plt.title('Delivery time')\n", + "plt.xlabel('distance')\n", + "plt.ylabel('Time')\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# we will select and name the coloumns\n", + "cols = ['Order_ID','Distance_km', 'Weather','Traffic_Level', 'Vehicle_Type', 'Preparation_Time_min', 'Courier_Experience_yrs', 'Delivery_Time','Time_of_Day']\n", + "df_clean = df_delivery[cols].copy()\n", + "\n", + "#drop order id coloumn\n", + "print(f\"Before: {df_clean.shape}\")\n", + "df_clean = df_clean.dropna(subset=['Order_ID'])\n", + "print(f\"After dropping Order_ID : {df_clean.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "\n", + "for col in ['Distance_km','Weather','Traffic_Level','Vehicle_Type','Preparation_Time_min','Delivery_Time']:\n", + " df_clean[col] = df_clean[col].fillna('unknown')\n", + "\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": [ + "\n", + "\n", + "from sklearn.model_selection import train_test_split, KFold\n", + "from sklearn.preprocessing import StandardScaler, LabelEncoder\n", + "\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3:\n", + "categorical_cols = ['Distance_km', 'Weather', 'Traffic_Level', 'Vehicle_Type', 'Preparation_Time_min','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": [ + "\n", + "\n", + "from sklearn.model_selection import train_test_split, KFold\n", + "\n", + "\n", + "import warnings\n", + "warnings.filterwarnings('ignore')\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "\n", + "feature_cols = ['Distance_km', 'Weather', 'Traffic_Level', 'Vehicle_Type',\n", + " 'Preparation_Time_min', 'Delivery_Time']\n", + "X = df_clean[feature_cols]\n", + "y = df_clean['Distance_km']\n", + "\n", + "\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n", + "print(f\"Train: {X_train.shape}, Test: {X_test.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "print(f\"\\nFeature ranges - Min: {X_train.min().min():.2f}, Max: {X_train.max().max():.2f}\")\n", + "X_train.head(3)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "\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" + ], + "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": [ + "import numpy as np\n", + "from sklearn.ensemble import RandomForestRegressor\n", + "from sklearn.metrics import mean_absolute_error, mean_squared_error\n", + "\n", + "import warnings\n", + "warnings.filterwarnings('ignore')\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "\n", + "#i already did the step up there" + ], + "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": [ + "# 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": [ + "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": [ + "# 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, 5))\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": [ + "# 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 Bonus: Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/174/Q3.ipynb b/submissions_extracted/174/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..44d1026e1c12141b31b2fe669c68549255695833 --- /dev/null +++ b/submissions_extracted/174/Q3.ipynb @@ -0,0 +1,191 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "\n", + "\n", + "# Download latest version\n", + "\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q3-exam-data\")\n", + "\n", + "\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1 and 2 : Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import os\n", + "import pandas as pd\n", + "csv_path = os.path.join(path, 'Q3_data.csv')\n", + "df = pd.read_csv(csv_path)\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", + "\n", + "df.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "df.describe()\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "\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\n", + "\n", + "df.duplicated()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "\n", + "df.drop_duplicates()" + ], + "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/175/Q1.ipynb b/submissions_extracted/175/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..5a51e572f7549f7c8d83bfca1505c990464e728b --- /dev/null +++ b/submissions_extracted/175/Q1.ipynb @@ -0,0 +1,294 @@ +{ + "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 seaborn as sns\n", + "from sklearn.preprocessing import StandardScaler, LabelEncoder, OneHotEncoder\n", + "from sklearn.model_selection import train_test_split, KFold\n", + "from sklearn.ensemble import RandomForestRegressor\n", + "from sklearn.metrics import mean_absolute_error, mean_squared_error\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q1-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "food_path = os.path.join(path, 'Q1_data.csv')\n", + "df_food = pd.read_csv(food_path)\n", + "\n", + "df_food.shape\n", + "print(df_food['Delivery_Time'])" + ], + "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", + "counts = df_food['Delivery_Time'].value_counts()\n", + "plt.figure(figsize=(10, 5))\n", + "plt.bar(counts.index, 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_clean = df_food.drop(columns=['Order_ID']).copy()\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() #for every feature, default is axis = 1\n", + " print(\"Missing Values per Column:\")\n", + " print(missing_values[missing_values > 0])\n", + " if missing_values.any(): #any() .. ?\n", + " print(\"\\nHandle Missing Values as needed.\")\n", + " else:\n", + " print(\"\\nNo Missing Values Found.\")\n", + "\n", + "check_missing_values(df_clean)\n", + "cols = ['Weather', 'Traffic_Level', 'Time_of_Day', 'Courier_Experience_yrs',\"Delivery_Time\"]\n", + "# Drop rows with missing stat values\n", + "df_clean = df_clean.dropna(subset=cols).copy()\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "def check_duplicates(df):\n", + " duplicates = df.duplicated().sum()\n", + " print(f\"Number of Duplicate Samples: {duplicates}\")\n", + " if duplicates > 0:\n", + " print(\"Dropping Duplicates...\")\n", + " df.drop_duplicates(inplace=True)\n", + " print(\"Duplicates Dropped.\")\n", + " else:\n", + " print(\"No Duplicate Samples Found.\")\n", + "\n", + "check_duplicates(df_clean)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "categorical_cols = df_clean.select_dtypes(include=[\"object\"]).columns\n", + "\n", + "print(\"Categorical Columns:\", list(categorical_cols))\n", + "\n", + "categorical_cols = ['Weather', 'Traffic_Level', 'Time_of_Day', 'Vehicle_Type']\n", + "\n", + "for col in categorical_cols:\n", + " le = LabelEncoder()\n", + " df_clean[col] = le.fit_transform(df_clean[col].astype(str))\n", + "\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "standard_scaler = StandardScaler()\n", + "data_standard_scaled = standard_scaler.fit_transform(df_clean)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 6: Write your code here:\n", + "def check_target_imbalance(df, target_column):\n", + " print(\"Target Distribution:\")\n", + " 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", + "\n", + "#we dont include 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", + "\n", + "X = df_clean[feature_cols]\n", + "y = df_clean['Delivery_Time']\n", + "\n", + "\n", + "" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:\n", + "\n", + "\n", + "# Use previously generated random data (example: regression data)\n", + "\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", + "model = RandomForestRegressor(n_estimators=100, max_depth=20, random_state=42, n_jobs=-1)\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", + "print(f\"MAE: ${mae:,.2f}\")\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" + ], + "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_food['Delivery_Time'].dropna(), bins=30, edgecolor='black')\n", + "plt.title('Delivery_Time Distribution')\n", + "plt.xlabel('Delivery_Time')\n", + "plt.ylabel('Count')\n", + "plt.show()\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/175/Q2.ipynb b/submissions_extracted/175/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..5879ab1277610bd1697db07c4a16ebf7da313e63 --- /dev/null +++ b/submissions_extracted/175/Q2.ipynb @@ -0,0 +1,333 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\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", + "# 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.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", + "\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", + "# Create Dataloaders to train and test data in batches\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", + "print(f\"Training batch input shape: {X_batch.shape}\")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 5. Display sample images\n", + "\n" + ], + "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", + "\n", + " # First linear layer: input features -> hidden layer\n", + " self.layer1 = nn.Linear(input_dim, hidden_dim)\n", + "\n", + " # Second linear layer: hidden layer -> hidden layer\n", + " self.layer2 = nn.Linear(hidden_dim, hidden_dim)\n", + "\n", + " # Third linear layer: hidden layer -> hidden layer\n", + " self.layer3 = nn.Linear(hidden_dim, hidden_dim)\n", + "\n", + " # Output layer: hidden layer -> number of classes (logits)\n", + " self.layer4 = nn.Linear(hidden_dim, output_dim)\n", + "\n", + " # ReLU activation for non-linearity\n", + " self.relu = nn.ReLU()\n", + "\n", + " # Defines how input data flows through the network\n", + " def forward(self, x):\n", + " # First hidden layer\n", + " a1 = self.relu(self.layer1(x))\n", + "\n", + " # Second hidden layer\n", + " a2 = self.relu(self.layer2(a1))\n", + "\n", + " # Third hidden layer\n", + " a3 = self.relu(self.layer3(a2))\n", + "\n", + " # Output layer (raw scores / logits)\n", + " output = self.layer4(a3) # we said we'll use softmax, where is it? ¯\\(ツ)/¯\n", + "\n", + " return output" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your training loop here:\n", + "def train_one_epoch(model, optimizer, criterion, train_loader, device):\n", + " # Set the model to training mode\n", + " model.train()\n", + "\n", + " running_loss = 0.0\n", + "\n", + " for X_batch, y_batch in train_loader:\n", + " # Move batch to the selected device\n", + " X_batch = X_batch.to(device) # shape: (batch_size, num_features)\n", + " y_batch = y_batch.to(device) # shape: (batch_size,)\n", + "\n", + " # Forward pass (outputs are logits)\n", + " outputs = model(X_batch) # shape: (batch_size, num_classes)\n", + " loss = criterion(outputs, y_batch)\n", + "\n", + " # Backward pass & optimization\n", + " optimizer.zero_grad() # Clear previous gradients\n", + " loss.backward() # Compute gradients\n", + " optimizer.step() # Update model parameters\n", + "\n", + " running_loss += loss.item()\n", + "\n", + " # Average loss over all batches\n", + " avg_loss = running_loss / len(train_loader)\n", + "\n", + " return avg_loss" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your validation loop here:\n", + "def validate(model, criterion, test_loader, device):\n", + " # Set the model to evaluation mode\n", + " model.eval()\n", + "\n", + " running_loss = 0.0\n", + " correct = 0\n", + " total = 0\n", + "\n", + " with torch.no_grad():\n", + " for X_batch, y_batch in test_loader:\n", + " # Move data to device\n", + " X_batch = X_batch.to(device) # shape: (batch_size, num_features)\n", + " y_batch = y_batch.to(device) # shape: (batch_size,)\n", + "\n", + " # Forward pass\n", + " outputs = model(X_batch) # shape: (batch_size, num_classes)\n", + " loss = criterion(outputs, y_batch)\n", + " running_loss += loss.item()\n", + "\n", + " # Apply Softmax to get probabilities\n", + " probabilities = F.softmax(outputs, dim=1)\n", + "\n", + " # Pick the classes with highest probabilities\n", + " predicted = torch.argmax(probabilities, dim=1)\n", + "\n", + " # Accuracy calculation\n", + " correct += (predicted == y_batch).sum().item()\n", + " total += y_batch.size(0)\n", + "\n", + " avg_loss = running_loss / len(test_loader)\n", + " accuracy = correct / total\n", + "\n", + " return avg_loss, accuracy" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Define device, model, loss, optimizer:\n", + "device = 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)" + ], + "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/175/Q3.ipynb b/submissions_extracted/175/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..a07315fd8a0bd5893fed7e06d46143299e5bcc39 --- /dev/null +++ b/submissions_extracted/175/Q3.ipynb @@ -0,0 +1,236 @@ +{ + "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 seaborn as sns\n", + "from sklearn.preprocessing import StandardScaler, LabelEncoder, OneHotEncoder\n", + "from sklearn.model_selection import train_test_split, KFold, StratifiedKFold\n", + "from sklearn.ensemble import RandomForestRegressor\n", + "from sklearn.metrics import mean_absolute_error, mean_squared_error\n", + "\n", + "# 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" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "df.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "df.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "def check_missing_values(df):\n", + " missing_values = df.isnull().sum()\n", + " print(\"Missing Values per Column:\")\n", + " print(missing_values[missing_values > 0])\n", + " if missing_values.any():\n", + " print(\"\\nHandle Missing Values as needed.\")\n", + " else:\n", + " print(\"\\nNo Missing Values Found.\")\n", + "\n", + "check_missing_values(df)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "def check_duplicates(df):\n", + " duplicates = df.duplicated().sum()\n", + " print(f\"Number of Duplicate Samples: {duplicates}\")\n", + " if duplicates > 0:\n", + " print(\"Dropping Duplicates...\")\n", + " df.drop_duplicates(inplace=True)\n", + " print(\"Duplicates Dropped.\")\n", + " else:\n", + " print(\"No Duplicate Samples Found.\")\n", + "\n", + "check_duplicates(df)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "categorical_cols = df.select_dtypes(include=[\"object\"]).columns\n", + "\n", + "print(\"Categorical Columns:\", list(categorical_cols))" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "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", + "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()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "\n", + "\n", + "# Show full dataset class distribution\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:\n", + "full_ratio = (y.value_counts(normalize=True) * 100).sort_index()\n", + "print(\"Full Dataset Class Distribution\")\n", + "print(\" y class percentages:\", {k: f\"{v:.2f}%\" for k, v in full_ratio.items()})\n", + "print(\"-\" * 40)\n", + "\n", + "# Define Stratified K-Fold\n", + "skf = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)\n", + "\n", + "print(\"Stratified K-Fold Cross Validation\\n\" + \"-\"*40)\n", + "\n", + "for fold, (train_idx, test_idx) in enumerate(skf.split(X, y), start=1):\n", + " # indexing for each fold\n", + " X_train, X_test = X.iloc[train_idx], X.iloc[test_idx]\n", + " y_train, y_test = y.iloc[train_idx], y.iloc[test_idx]\n", + "\n", + " print(f\"Fold {fold}\")\n", + " print(\" X_train shape:\", X_train.shape)\n", + " print(\" X_test shape :\", X_test.shape)\n", + " print(\" y_train shape:\", y_train.shape)\n", + " print(\" y_test shape :\", y_test.shape)\n", + "\n", + " # showing class distribution\n", + " train_ratio = (y_train.value_counts(normalize=True) * 100).sort_index()\n", + " test_ratio = (y_test.value_counts(normalize=True) * 100).sort_index()\n", + "\n", + " print(\" y_train class percentages:\", {k: f\"{v:.2f}%\" for k, v in train_ratio.items()})\n", + " print(\" y_test class percentages :\", {k: f\"{v:.2f}%\" for k, v in test_ratio.items()})\n", + "\n", + " print(\"-\" * 40)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 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/176/Q1.ipynb b/submissions_extracted/176/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..75b2e9669ccfd8ca154d5ca108e8f72f4cca4733 --- /dev/null +++ b/submissions_extracted/176/Q1.ipynb @@ -0,0 +1,302 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q1-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "import os\n", + "import matplotlib.pyplot as plt\n", + "import numpy as np\n", + "import pandas as pd\n", + "import warnings\n", + "warnings.filterwarnings('ignore')\n", + "\n", + "file_path = os.path.join(path, 'Q1_data.csv')\n", + "df = pd.read_csv(file_path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "df.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "df.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "# Price distribution (target variable)\n", + "plt.figure(figsize=(10, 5))\n", + "plt.hist(df['Delivery_Time'].dropna(), bins=40, edgecolor='black')\n", + "plt.title('Price Distribution')\n", + "plt.xlabel('Delivery_Time')\n", + "plt.ylabel('Frequency')\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "#Drop Order_ID column\n", + "df.drop(columns=['Order_ID'],inplace=True)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "#Handling missing values\n", + "for col in df.columns:\n", + " if df[col].isnull().sum != 0 and df[col].dtypes == 'float64':\n", + " df[col].fillna(df[col].mean(),inplace=True)\n", + "\n", + "df.dropna(inplace=True)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "#Removing Duplicates\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)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "#Encode the catogical columns\n", + "from sklearn.preprocessing import LabelEncoder\n", + "\n", + "\n", + "for col in df.columns:\n", + " if df[col].dtypes == 'object': # Checking the category columns\n", + " label_encoder = LabelEncoder()\n", + " df[col] = label_encoder.fit_transform(df[col])\n", + "df" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# # Task 5: Write your code here:\n", + "from sklearn.preprocessing import StandardScaler\n", + "\n", + "scaler = StandardScaler()\n", + "df = scaler.fit_transform(df)\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 6: Write your code here:\n", + "#the data is balanced" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "#Split dataset\n", + "X = df.drop(columns=['Delivery_Time'],inplace=False)\n", + "y = df['Delivery_Time']" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:\n", + "from sklearn.model_selection import KFold\n", + "from sklearn.ensemble import RandomForestRegressor\n", + "from sklearn.metrics import mean_absolute_error\n", + "\n", + "\n", + "#Score for each Fold\n", + "scores = 0\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", + "\n", + " # Train the Model\n", + " model = RandomForestRegressor(n_estimators=100, max_depth=20, random_state=42, n_jobs=-1)\n", + " model.fit(X_train, y_train)\n", + "\n", + " # Predict and evaluate\n", + " y_pred = model.predict(X_test)\n", + " mae = mean_absolute_error(y_test, y_pred)\n", + " scores += mae\n", + "\n", + "print(f\"Averaged score across all folds: {scores/5}\")" + ], + "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': 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", + "#" + ], + "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", + "\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", + "\n", + " # Train the Model\n", + " model_forest = RandomForestRegressor(n_estimators=100, max_depth=20, random_state=42, n_jobs=-1)\n", + " model_forest.fit(X_train, y_train)\n", + "\n", + " model_cat = CatBoostRegressor(verbose=0)\n", + " model_cat.fit(X_train, y_train)\n", + "\n", + " # Predict and evaluate\n", + " y_pred_forest = model_forest.predict(X_test)\n", + " y_pred_cat = model_forest.predict(X_test)\n", + "\n", + " y_pred_average = (y_pred_forest + y_pred_cat)/2\n", + "\n", + " mae = mean_absolute_error(y_test, y_pred_average)\n", + "\n", + " print(\"MAE:\",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/176/Q2.ipynb b/submissions_extracted/176/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..0ca7fc6e4fefe392a0dbfb37461a3d5a80b5a113 --- /dev/null +++ b/submissions_extracted/176/Q2.ipynb @@ -0,0 +1,387 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q2-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import os\n", + "import pandas as pd\n", + "import numpy as np\n", + "from PIL import Image\n", + "from sklearn.model_selection import train_test_split\n", + "\n", + "# Load Labels\n", + "labels_df = pd.read_csv(os.path.join(path, \"labels.csv\"))\n", + "img_dir = os.path.join(path, \"images\")\n", + "\n", + "images = []\n", + "ages = []\n", + "\n", + "# Load Images and Resize\n", + "print(\"Loading images...\")\n", + "for index, row in labels_df.iterrows():\n", + " img_name = row.iloc[0]\n", + " age = row.iloc[1]\n", + " img_path = os.path.join(img_dir, img_name)\n", + "\n", + " if os.path.exists(img_path):\n", + " img = Image.open(img_path).convert('RGB')\n", + " img_array = np.array(img) / 255.0 # Normalize pixel values to [0, 1]\n", + " images.append(img_array)\n", + " ages.append(age)\n", + "\n", + "X = np.array(images)\n", + "y = np.array(ages)\n", + "\n", + "# Transpose image dimensions to match PyTorch format (N, C, H, W)\n", + "X = np.transpose(X, (0, 3, 1, 2))\n", + "\n", + "# Split Data\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n", + "\n", + "print(f\"X_train shape: {X_train.shape}\")\n", + "print(f\"X_test shape: {X_test.shape}\")\n", + "print(f\"y_train shape: {y_train.shape}\")\n", + "print(f\"y_test shape: {y_test.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 1. Convert Numpy arrays to PyTorch Tensors\n", + "import torch\n", + "\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", + "y_test\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 2. Create TensorDataset objects\n", + "from torch.utils.data import TensorDataset\n", + "\n", + "train_dataset = TensorDataset(X_train, y_train)\n", + "test_dataset = TensorDataset(X_test, y_test)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 3. Create DataLoaders\n", + "from torch.utils.data import DataLoader\n", + "\n", + "# DataLoader for training data\n", + "train_loader = DataLoader(\n", + " train_dataset,\n", + " batch_size=32,\n", + " shuffle=True,\n", + " num_workers=2\n", + ")\n", + "# DataLoader for test/validation data\n", + "test_loader = DataLoader(\n", + " test_dataset,\n", + " batch_size=32,\n", + " shuffle=False,\n", + " num_workers=2\n", + ")\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 4. Print shape of one batch\n", + "\n", + "# Get the first batch from the training DataLoader\n", + "X_batch, y_batch = next(iter(train_loader))\n", + "print(f\"Training batch input shape: {X_batch.shape}\")\n", + "print(f\"Training batch labels shape: {y_batch.shape}\")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 5. Display sample images\n", + "\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", + "\n", + "class NN5Layer(nn.Module):\n", + "\n", + " def __init__(self, input_dim, hidden_dim, output_dim):\n", + " super(NN5Layer, self).__init__()\n", + "\n", + " self.layer1 = nn.Linear(input_dim, hidden_dim)\n", + "\n", + " self.layer2 = nn.Linear(hidden_dim, hidden_dim)\n", + "\n", + " self.layer3 = nn.Linear(hidden_dim, hidden_dim)\n", + "\n", + " self.layer4 = nn.Linear(hidden_dim, hidden_dim)\n", + "\n", + " # activation function for non-linearity\n", + " self.relu = nn.ReLU()\n", + "\n", + " # Defines how input data flows through the network\n", + " def forward(self, x):\n", + " z1 = self.layer1(x)\n", + " a1 = self.relu(z1)\n", + "\n", + " z2 = self.layer2(a1)\n", + " a2 = self.relu(z2)\n", + "\n", + " z3 = self.layer3(a2)\n", + " a3 = self.relu(z3)\n", + "\n", + " # Output layer\n", + " z4 = self.layer4(a3)\n", + "\n", + " return z4" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your training loop here:\n", + "def train_one_epoch(model, optimizer, criterion, train_loader, device):\n", + " # Set the model to training mode\n", + " model.train()\n", + "\n", + " running_loss = 0.0\n", + "\n", + " for X_batch, y_batch in train_loader:\n", + " # Move batch to the selected device\n", + " X_batch = X_batch.view(X_batch.size(0), -1).to(device)\n", + " y_batch = y_batch.to(device)\n", + "\n", + " # Forward pass\n", + " outputs = model(X_batch)\n", + " loss = criterion(outputs, y_batch)\n", + "\n", + " # Backward pass & optimization\n", + " optimizer.zero_grad() # Clear previous gradients\n", + " loss.backward() # Compute gradients\n", + " optimizer.step() # Update model parameters\n", + "\n", + " running_loss += loss.item()\n", + "\n", + " # Average loss over all batches\n", + " avg_loss = running_loss / len(train_loader)\n", + "\n", + " return avg_loss" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your validation loop here:\n", + "def validate(model, criterion, test_loader, device):\n", + " # Set the model to evaluation mode\n", + " model.eval()\n", + "\n", + " running_loss = 0.0\n", + " correct = 0\n", + " total = 0\n", + "\n", + " with torch.no_grad():\n", + " for X_batch, y_batch in test_loader:\n", + " # Move data to device\n", + " X_batch = X_batch.view(X_batch.size(0), -1).to(device)\n", + " y_batch = y_batch.to(device)\n", + "\n", + " # Forward pass\n", + " outputs = model(X_batch)\n", + " loss = criterion(outputs, y_batch)\n", + " running_loss += loss.item()\n", + "\n", + " probabilities = F.softmax(outputs, dim=1)\n", + "\n", + " predicted = torch.argmax(probabilities, dim=1)\n", + "\n", + " # Accuracy calculation\n", + " correct += (predicted == y_batch).sum().item()\n", + " total += y_batch.size(0)\n", + "\n", + " avg_loss = running_loss / len(test_loader)\n", + " accuracy = correct / total\n", + "\n", + " return avg_loss, accuracy" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Define device, model, loss, optimizer:\n", + "from torch.optim import AdamW\n", + "\n", + "# Device setup\n", + "device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n", + "\n", + "# Model parameters\n", + "input_dim = 3 * 36 * 36\n", + "hidden_dim = 64 # Design choice\n", + "\n", + "output_dim = 100\n", + "model = NN5Layer(input_dim, hidden_dim, output_dim).to(device)\n", + "\n", + "learning_rate = 0.001\n", + "\n", + "criterion = nn.CrossEntropyLoss()\n", + "\n", + "optimizer = AdamW(model.parameters(), learning_rate)\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", + "\n", + "num_epochs = 1\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/176/Q3.ipynb b/submissions_extracted/176/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..ece271cee9f913c05e4ef4b65dd83104467de004 --- /dev/null +++ b/submissions_extracted/176/Q3.ipynb @@ -0,0 +1,240 @@ +{ + "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 matplotlib.pyplot as plt\n", + "import numpy as np\n", + "import pandas as pd\n", + "import warnings\n", + "import seaborn as sns\n", + "warnings.filterwarnings('ignore')\n", + "\n", + "file_path = os.path.join(path, 'Q3_data.csv')\n", + "df = pd.read_csv(file_path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "df.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "df.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "for col in df.columns:\n", + " if df[col].isnull().sum != 0 and (df[col].dtypes == 'float64' or df[col].dtypes == 'int64'):\n", + " df[col].fillna(df[col].mean(),inplace=True)\n", + "\n", + "df.dropna(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", + " df.drop_duplicates(inplace=True)\n", + "\n", + "check_duplicates(df)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "from sklearn.preprocessing import LabelEncoder\n", + "\n", + "\n", + "for col in df.columns:\n", + " if df[col].dtypes == 'object': # Checking the category columns\n", + " label_encoder = LabelEncoder()\n", + " df[col] = label_encoder.fit_transform(df[col])" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "from sklearn.preprocessing import StandardScaler\n", + "\n", + "scaler = StandardScaler()\n", + "df_new = scaler.fit_transform(df)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "X = df.drop(columns=['Target'],inplace=False)\n", + "y = df['Target']" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:\n", + "from sklearn.model_selection import KFold\n", + "from catboost import CatBoostRegressor\n", + "from sklearn.metrics import accuracy_score, f1_score\n", + "\n", + "#accuracy for each Fold\n", + "accuracies = 0\n", + "f1_scores = 0\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", + "\n", + " # Train the Model\n", + " model_cat = CatBoostRegressor(verbose=0)\n", + " model_cat.fit(X_train, y_train)\n", + "\n", + " # Predict and evaluate\n", + " y_pred = model_cat.predict(X_test)\n", + " accuracy = accuracy_score(y_test, bool(y_pred).sum())\n", + " f1_score = f1_score(y_test, bool(y_pred).sum())\n", + "\n", + " accuracies += accuracy\n", + " f1_scores +=f1_score\n", + "\n", + "print(f\"Averaged score across all folds: {accuracies/5}\")" + ], + "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': X.columns,\n", + " 'importance': model_cat.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/177/Q1.ipynb b/submissions_extracted/177/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..f93cfb1c9f99fc2d24858e7807e2618ab58974b2 --- /dev/null +++ b/submissions_extracted/177/Q1.ipynb @@ -0,0 +1,331 @@ +{ + "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", + "\n", + "# Sklearn\n", + "from sklearn.model_selection import train_test_split, cross_val_score\n", + "from sklearn.preprocessing import StandardScaler, LabelEncoder, OneHotEncoder\n", + "from sklearn.linear_model import LinearRegression, Ridge, Lasso, LogisticRegression\n", + "from sklearn.tree import DecisionTreeClassifier, DecisionTreeRegressor\n", + "from sklearn.ensemble import RandomForestClassifier, RandomForestRegressor\n", + "from sklearn.neighbors import KNeighborsClassifier\n", + "from sklearn.svm import SVC, SVR\n", + "from sklearn.decomposition import PCA\n", + "from sklearn.manifold import TSNE\n", + "from sklearn.cluster import KMeans\n", + "from sklearn.metrics import (\n", + " mean_absolute_error, mean_squared_error, r2_score,\n", + " accuracy_score, precision_score, recall_score, f1_score,\n", + " confusion_matrix, classification_report\n", + ")\n", + "\n", + "# PyTorch\n", + "import torch\n", + "import torch.nn as nn\n", + "from torch.utils.data import DataLoader, TensorDataset\n", + "from torchvision import datasets, transforms\n", + "\n", + "# Settings\n", + "import warnings\n", + "warnings.filterwarnings('ignore')\n", + "plt.style.use('seaborn-v0_8-whitegrid')\n", + "\n", + "print(\"All imports successful!\")" + ], + "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)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1:\n", + "import os\n", + "for file in os.listdir(path):\n", + " if file.endswith('.csv'):\n", + " print(f\"Found: {file}\")\n", + "\n", + "# Load the CSV file\n", + "df = pd.read_csv(f\"{path}/Q1_data.csv\") # <-- CHANGE THIS: put the actual filename\n", + "\n", + "# Check your data\n", + "print(f\"Shape: {df.shape}\")\n", + "print(f\"Columns: {list(df.columns)}\")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2:\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3:\n", + "df.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4:\n", + "df.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "column_name = 'Delivery_Time'\n", + "plt.figure(figsize=(10, 6))\n", + "plt.hist(df[column_name], bins=30, edgecolor='black', alpha=0.7)\n", + "plt.xlabel(column_name)\n", + "plt.ylabel('Count')\n", + "plt.title(f'Distribution of {column_name}')\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1:\n", + "target_column = 'Delivery_Time'\n", + "\n", + "X = df.drop(columns=[target_column]) # Features (everything except target)\n", + "y = df[target_column] # Target (what we predict)\n", + "\n", + "print(f\"Features (X) shape: {X.shape}\")\n", + "print(f\"Target (y) shape: {y.shape}\")\n", + "print(f\"\\nTarget values: {y.unique()}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2:\n", + "\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 3: Write your code here:\n", + "df = df.dropna()\n", + "#Finding Duplicates:\n", + "df.duplicated()\n", + "#Removing Duplicates:\n", + "df.drop_duplicates()\n", + "print(f\"Shape after handling missing values: {df.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "# Find categorical columns\n", + "categorical_cols = X.select_dtypes(include=['object']).columns.tolist()\n", + "print(f\"Categorical columns to encode: {categorical_cols}\")\n", + "\n", + "# Encode each categorical column\n", + "le = LabelEncoder()\n", + "for col in categorical_cols:\n", + " X[col] = le.fit_transform(X[col])\n", + "\n", + "print(\"\\nEncoding complete!\")\n", + "print(X.head())" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5:\n", + "# Scale features - fit on train, transform both\n", + "scaler = StandardScaler()\n", + "X_train_scaled = scaler.fit_transform(X_train)\n", + "X_test_scaled = scaler.transform(X_test)\n", + "print(f\"\\nScaled ranges - Min: {X_train_scaled.min():.2f}, Max:{X_train_scaled.max():.2f}\")\n", + "pd.DataFrame(X_train_scaled, columns=X_train.columns).head(3)" + ], + "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", + "target_column = 'Delivery_Time' # <-- CHANGE THIS: column you want to predict\n", + "\n", + "X = df.drop(columns=[target_column]) # Features (everything except target)\n", + "y = df[target_column] # Target (what we predict)\n", + "\n", + "print(f\"Features (X) shape: {X.shape}\")\n", + "print(f\"Target (y) shape: {y.shape}\")\n", + "print(f\"\\nTarget values: {y.unique()}\")" + ], + "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", + "# Use previously generated random data (example: regression data )\n", + "X, y = X.copy(), y.copy()\n", + "# Define K-Fold Cross Validation\n", + "kf = KFold(n_splits=5, shuffle=True, random_state=42)\n", + "# Iterate through folds\n", + "model = RandomForestRegressor(n_estimators=100, random_state=42)\n", + "\n", + "for fold, (train_idx, test_idx) in enumerate(kf.split(X), start=1):\n", + " # indexing for each fold\n", + " X_train, X_test = X.iloc[train_idx], X.iloc[test_idx]\n", + " y_train, y_test = y.iloc[train_idx], y.iloc[test_idx]\n", + " # print shapes\n", + " print(f\"Fold {fold}\")\n", + " print(\" X_train shape:\", X_train.shape)\n", + " print(\" X_test shape :\", X_test.shape)\n", + " print(\" y_train shape:\", y_train.shape)\n", + " print(\" y_test shape :\", y_test.shape)\n", + " print(\"-\" * 30)\n", + "\n", + " model.fit(X_train, y_train)\n", + " y_pred = model.predict(X_test)\n", + " mae = mean_absolute_error(y_test, y_pred)\n", + " print(f\"MAE (Mean Absolute Error): {mae:.4f}\")\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "\n", + "importances = model.feature_importances_\n", + "\n", + "\n", + "\n", + "fig, axes = plt.subplots(1, 2, figsize=(18, 6))\n", + "axes = axes.flatten()\n", + "features = X.columns\n", + "\n", + "# Sort features by importance for a cleaner plot\n", + "sorted_idx = np.argsort(importances)\n", + "\n", + "ax = axes[0]\n", + "ax.barh(features[sorted_idx], importances[sorted_idx])\n", + "ax.set_title(f\"{model} 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", + "column_name = 'delivery_time' # <-- CHANGE THIS\n", + "\n", + "plt.figure(figsize=(10, 6))\n", + "plt.hist(df[column_name], bins=30, edgecolor='black', alpha=0.7)\n", + "plt.xlabel(column_name)\n", + "plt.ylabel('Count')\n", + "plt.title(f'Distribution of {column_name}')\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/177/Q2.ipynb b/submissions_extracted/177/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..0a99b98cacfcf835d8665c6e0ed07b118687399c --- /dev/null +++ b/submissions_extracted/177/Q2.ipynb @@ -0,0 +1,537 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "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)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "print(\"Shape of x:\", x.shape)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "a = torch.tensor([1.0, 2.0, 3.0])\n", + "b = torch.tensor([4.0, 5.0, 6.0])\n", + "\n", + "# Element-wise operations\n", + "print(\"Addition:\", a + b)\n", + "print(\"Multiplication:\", a * b)\n", + "\n", + "# Matrix multiplication\n", + "A = torch.randn(2, 3)\n", + "B = torch.randn(3, 2)\n", + "C = A @ B\n", + "\n", + "print(\"Matrix multiplication result shape:\", C.shape)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import torch\n", + "\n", + "# 1️⃣ Flatten - Convert any shape to (batch_size, features)\n", + "x = torch.randn(32, 3, 28, 28)\n", + "x_flat = x.flatten(start_dim=1)\n", + "print(\"Flatten:\", x_flat.shape) # (32, 2352)\n", + "\n", + "# 2️⃣ Squeeze - Remove dimensions with size 1\n", + "x = torch.randn(1, 3, 28, 28)\n", + "x_sq = x.squeeze()\n", + "print(\"Squeeze:\", x_sq.shape) # (3, 28, 28)\n", + "\n", + "# 3️⃣ Unsqueeze - Add a new dimension of size 1\n", + "x = torch.randn(3, 28, 28)\n", + "x_unsq = x.unsqueeze(0)\n", + "print(\"Unsqueeze:\", x_unsq.shape) # (1, 3, 28, 28)\n", + "\n", + "# 4️⃣ View - Reshape freely while keeping same number of elements\n", + "x = torch.randn(32, 28, 28, 3)\n", + "x_view = x.view(32, -1) # Flatten all except batch\n", + "print(\"View:\", x_view.shape) # (32, 28*28*3)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import torch\n", + "\n", + "# Create a float32 tensor\n", + "x = torch.tensor([1.2, 2.3, 3.4], dtype=torch.float32)\n", + "print(x.dtype) # Output: torch.float32\n", + "\n", + "# Convert to float16\n", + "x_half = x.to(torch.float16)\n", + "print(x_half.dtype) # Output: torch.float16" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Automatically select CPU or GPU\n", + "device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n", + "\n", + "# Create a tensor and move it to GPU\n", + "x_gpu = x.to(device)\n", + "print(x_gpu.device) # Output: cuda:0 (if GPU is available) or cpu" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "from sklearn.datasets import load_breast_cancer\n", + "from sklearn.model_selection import train_test_split\n", + "from sklearn.preprocessing import StandardScaler\n", + "from torch.utils.data import TensorDataset\n", + "from torch.utils.data import DataLoader\n", + "import torch\n", + "\n", + "# load data\n", + "data = load_breast_cancer()\n", + "X = data.data\n", + "y = data.target\n", + "\n", + "# Split the dataset into training and testing sets\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42, stratify=y)\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}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "from torchvision.datasets import MNIST\n", + "from torchvision.transforms.functional import to_tensor\n", + "\n", + "# Training dataset\n", + "train_dataset = MNIST(\n", + " root='./datasets', # Dataset storage path\n", + " train=True, # Use training data\n", + " transform=to_tensor, # Convert images to tensors\n", + " download=True # Download if not available\n", + ")\n", + "\n", + "# Testing dataset\n", + "test_dataset = MNIST(\n", + " root='./datasets', # Dataset storage path\n", + " train=False, # Use test data\n", + " transform=to_tensor, # Convert images to tensors\n", + " download=True # Download if not available\n", + ")\n", + "\n", + "# print one sample from the dataset\n", + "# Each sample consists of an image tensor and its label\n", + "sample_image, sample_label = train_dataset[0]\n", + "\n", + "print(f\"\\n Image shape: {sample_image.shape}\") # (1, 28, 28)\n", + "print(f\"Label: {sample_label}\")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "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" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import torch\n", + "import torch.nn as nn\n", + "\n", + "# Create a linear layer: 3 input features -> 1 output\n", + "linear = nn.Linear(in_features=3, out_features=1)\n", + "\n", + "# Example input: batch of 4 samples, each with 3 features\n", + "x = torch.randn(4, 3)\n", + "\n", + "# Forward through the layer\n", + "y = linear(x)\n", + "\n", + "print(\"Input shape:\", x.shape) # torch.Size([4, 3])\n", + "print(\"Output shape:\", y.shape) # torch.Size([4, 1])" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "class NN1Layer(nn.Module):\n", + "\n", + " def __init__(self, input_dim):\n", + "\n", + " super(NN1Layer, self).__init__()\n", + " # input_dim = num of features, Output for binary classification is 1\n", + " self.layer_1 = nn.Linear(input_dim, 1)\n", + "\n", + " # output activation function\n", + " self.sigmoid = nn.Sigmoid()\n", + "\n", + " # forward pass\n", + " def forward(self, x):\n", + " z = self.layer_1(x)\n", + " a = self.sigmoid(z)\n", + " return a" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "class NN2Layer(nn.Module):\n", + "\n", + " def __init__(self, input_dim, hidden_dim):\n", + "\n", + " super(NN2Layer, self).__init__()\n", + " # input_dim = num of features, hidden_dim = num of neurons\n", + " #TODO\n", + " # hidden_dim = num of neurons, Output for binary classification is 1\n", + " #TODO\n", + "\n", + " # non-linearity activation function\n", + " #TODO\n", + " # output activation function\n", + " #TODO\n", + "\n", + " # forward pass\n", + " def forward(self, x):\n", + " #TODO\n", + " return #TODO" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Instantiate the model\n", + "input_dim = 4 # number of input features\n", + "hidden_dim = 3 # number of hidden neurons\n", + "\n", + "model = NN2Layer(input_dim, hidden_dim)\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}\")" + ], + "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", + "\n", + "\n", + " running_loss = 0.0\n", + "\n", + " for X_batch, y_batch in train_loader:\n", + " # Move batch to the selected device\n", + "\n", + "\n", + " # Forward pass\n", + "\n", + "\n", + " # Backward pass & optimization\n", + "\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": [ + "# Example predictions and targets\n", + "y_pred = torch.tensor([[2.5], [3.0], [4.5]])\n", + "y_true = torch.tensor([[3.0], [2.5], [5.0]])\n", + "\n", + "criterion = nn.MSELoss()\n", + "loss = criterion(y_pred, y_true)\n", + "print(\"MSE Loss:\", loss.item())" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Predicted probabilities (after sigmoid)\n", + "y_pred = torch.tensor([[0.8], [0.3], [0.6]])\n", + "y_true = torch.tensor([[1.0], [0.0], [1.0]])\n", + "\n", + "criterion = nn.BCELoss()\n", + "loss = criterion(y_pred, y_true)\n", + "print(\"Binary Cross Entropy Loss:\", loss.item())" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Raw model outputs (logits), shape: (batch_size, num_classes)\n", + "logits = torch.tensor([\n", + " [2.0, 0.5, 1.0],\n", + " [0.1, 1.5, 0.3]\n", + "])\n", + "# True class indices\n", + "targets = torch.tensor([0, 1])\n", + "\n", + "criterion = nn.CrossEntropyLoss()\n", + "loss = criterion(logits, targets)\n", + "print(\"Cross Entropy Loss:\", loss.item())" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "def validate(model, criterion, test_loader, device):\n", + " # Set the model to evaluation mode\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", + "\n", + "\n", + " # Forward pass\n", + "\n", + " # Binary predictions\n", + "\n", + "\n", + " # Accuracy calculation\n", + "\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": [ + "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": [ + "data = load_breast_cancer()\n", + "\n", + "X = data.data\n", + "y = data.target\n", + "\n", + "# Split the dataset into training and testing sets\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42, stratify=y)\n", + "\n", + "# Standardize the data\n", + "scaler = StandardScaler()\n", + "X_train = scaler.fit_transform(X_train)\n", + "X_test = scaler.transform(X_test)\n", + "\n", + "# transform to tensors\n", + "X_train = torch.tensor(X_train, dtype=torch.float32)\n", + "X_test = torch.tensor(X_test, dtype=torch.float32)\n", + "y_train = torch.tensor(y_train, dtype=torch.float32)\n", + "y_test = torch.tensor(y_test, dtype=torch.float32)\n", + "\n", + "# Create TensorDatasets for training and testing\n", + "train_dataset = TensorDataset(X_train, y_train)\n", + "test_dataset = TensorDataset(X_test, y_test)\n", + "\n", + "# Create Dataloaders to train and test data in batches\n", + "train_loader = DataLoader(train_dataset, batch_size=32, shuffle=True)\n", + "test_loader = DataLoader(test_dataset, batch_size=32, shuffle=False)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 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", + "\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", + "\n", + " # Validate\n", + "\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='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/177/Q3.ipynb b/submissions_extracted/177/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..c97832709061629f03a86d1f40306ca8a3e2a744 --- /dev/null +++ b/submissions_extracted/177/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/178/Q1.ipynb b/submissions_extracted/178/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..14b050be436c27b2656504ea4a05743614c5deda --- /dev/null +++ b/submissions_extracted/178/Q1.ipynb @@ -0,0 +1,245 @@ +{ + "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", + "path = kagglehub.dataset_download(\"ANON_OWNER/q1-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "delivery_path = os.path.join(path, 'Q1_data.csv')\n", + "df = pd.read_csv(delivery_path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "df.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "df.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "plt.figure(figsize=(10, 5))\n", + "plt.hist(df['Delivery_Time'].dropna(), bins=50, edgecolor='black')\n", + "plt.title('Delivery Time')\n", + "plt.xlabel('Deliver_time')\n", + "plt.ylabel('Frequency')\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "target_column = \"Order_ID\"\n", + "df_clean = df.drop(columns = target_column, axis=1)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "df_clean = df_clean.dropna().copy()\n", + "df_clean" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "def check_duplicates(df):\n", + " duplicates = df.duplicated().sum()\n", + " print(f\"Number of Duplicate Samples: {duplicates}\")\n", + " if duplicates > 0:\n", + " print(\"Dropping Duplicates...\")\n", + " df.drop_duplicates(inplace=True)\n", + " print(\"Duplicates Dropped.\")\n", + " else:\n", + " print(\"No Duplicate Samples Found.\")\n", + "\n", + "check_duplicates(df_clean)\n", + "df_clean" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "from sklearn.preprocessing import StandardScaler, LabelEncoder\n", + "\n", + "\n", + "categorical_cols = df.select_dtypes(include=[\"object\"]).columns\n", + "\n", + "\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" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "df_clean.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "scaler = StandardScaler()\n", + "features = df_clean.columns.drop(\"Delivery_Time\")\n", + "df_clean[features] = scaler.fit_transform(df_clean[features])\n", + "df_clean" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "plt.figure(figsize=(10, 5))\n", + "plt.hist(df['Delivery_Time'].dropna(), bins=30, edgecolor='black')\n", + "plt.title('Delivery Time')\n", + "plt.xlabel('Deliver_time')\n", + "plt.ylabel('Frequency')\n", + "plt.show()\n", + "\n", + "# a slight skewness, forgot how to handle imbalance :)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "from sklearn.model_selection import train_test_split, KFold\n", + "# Define features (X) and target (y)\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", + "# Train-test split (80% train, 20% test)\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n", + "print(f\"Train: {X_train.shape}, Test: {X_test.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "from sklearn.ensemble import RandomForestRegressor\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!\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "y_pred = model.predict(X_test)\n", + "from sklearn.metrics import mean_absolute_error, mean_squared_error\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 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/178/Q2.ipynb b/submissions_extracted/178/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..f6ae572eb41bd66067199b3a13adb378f4c9aabf --- /dev/null +++ b/submissions_extracted/178/Q2.ipynb @@ -0,0 +1,222 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q2-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import os\n", + "import pandas as pd\n", + "import numpy as np\n", + "from PIL import Image\n", + "from sklearn.model_selection import train_test_split\n", + "\n", + "# Load Labels\n", + "labels_df = pd.read_csv(os.path.join(path, \"labels.csv\"))\n", + "img_dir = os.path.join(path, \"images\")\n", + "\n", + "images = []\n", + "ages = []\n", + "\n", + "# Load Images and Resize\n", + "print(\"Loading images...\")\n", + "for index, row in labels_df.iterrows():\n", + " img_name = row.iloc[0]\n", + " age = row.iloc[1]\n", + " img_path = os.path.join(img_dir, img_name)\n", + "\n", + " if os.path.exists(img_path):\n", + " img = Image.open(img_path).convert('RGB')\n", + " img_array = np.array(img) / 255.0 # Normalize pixel values to [0, 1]\n", + " images.append(img_array)\n", + " ages.append(age)\n", + "\n", + "X = np.array(images)\n", + "y = np.array(ages)\n", + "\n", + "# Transpose image dimensions to match PyTorch format (N, C, H, W)\n", + "X = np.transpose(X, (0, 3, 1, 2))\n", + "\n", + "# Split Data\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n", + "\n", + "print(f\"X_train shape: {X_train.shape}\")\n", + "print(f\"X_test shape: {X_test.shape}\")\n", + "print(f\"y_train shape: {y_train.shape}\")\n", + "print(f\"y_test shape: {y_test.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import torch\n", + "from torch.utils.data import TensorDataset\n", + "from sklearn.preprocessing import StandardScaler\n", + "\n", + "x = torch.randn(32, 3, 36, 36)\n", + "x_flat = x.flatten(start_dim=1)\n", + "print(\"Flatten:\", x_flat.shape)\n", + "\n", + "# 2️⃣ Squeeze - Remove dimensions with size 1\n", + "x = torch.randn(1, 3, 36, 36)\n", + "x_sq = x.squeeze()\n", + "print(\"Squeeze:\", x_sq.shape)\n", + "\n", + "x = torch.randn(3, 36, 36)\n", + "x_unsq = x.unsqueeze(0)\n", + "print(\"Unsqueeze:\", x_unsq.shape)\n", + "\n", + "x = torch.randn(32, 36, 36, 3)\n", + "x_view = x.view(32, -1)\n", + "print(\"View:\", x_view.shape)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "train_dataset = TensorDataset(X_train, y_train)\n", + "test_dataset = TensorDataset(X_test, y_test)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "train_loader = DataLoader(train_dataset, batch_size=32, shuffle=True)\n", + "test_loader = DataLoader(test_dataset, batch_size=32, shuffle=False)" + ], + "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}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "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", + " 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:" + ], + "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/178/Q3.ipynb b/submissions_extracted/178/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..bb1685d7861d4d9fa6949035dfb58d6a3cff525d --- /dev/null +++ b/submissions_extracted/178/Q3.ipynb @@ -0,0 +1,180 @@ +{ + "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", + "# Download latest version\n", + "\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q3-exam-data\")\n", + "\n", + "\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "delivery_path = os.path.join(path, 'Q3_data.csv')\n", + "df = pd.read_csv(delivery_path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "df.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "df.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Analyze missing values\n", + "missing_percentage = (df.isnull().sum() / len(df)) * 100\n", + "missing_data = pd.DataFrame({\n", + " 'Column': missing_percentage.index,\n", + " 'Missing_Percentage': missing_percentage.values\n", + "})\n", + "missing_data = missing_data[missing_data['Missing_Percentage'] > 0].sort_values('Missing_Percentage', ascending=False)\n", + "\n", + "print(\"Missing Data Analysis:\")\n", + "missing_data.head(10)\n", + "\n", + "plt.figure(figsize=(10, 5))\n", + "plt.hist(df['Target'].dropna(), bins=50, edgecolor='black')\n", + "plt.title('Target Distribution')\n", + "plt.xlabel('Target')\n", + "plt.ylabel('Frequency')\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 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/179/Q1.ipynb b/submissions_extracted/179/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..5418dc211b5e9783c2cf0438f8d2e7eca1e02022 --- /dev/null +++ b/submissions_extracted/179/Q1.ipynb @@ -0,0 +1,173 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q1-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1:df = pd.read_csv(f\"{path}/weather_classification_data.csv\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2:df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: df.select_dtypes(include=[\"object\"]).columns" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4:or colin categorical_cols:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5:print(f\"Encoding column: {col}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: pd.read_csv(f\"{order_id}/weather_classification_data.csv\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2:df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: df.select_dtypes(include=[\"order\"]).columns" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4::or colin categorical_cols:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5:print(f\"Encoding column: {col}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 6:df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1:x = torch.randn(1)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5:y = tensor([2., 3., 4.,5.])" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1:plt.plot(train_losses, label='Train Loss')" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2:plt.plot(val_losses, label='Validation Loss')" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus:plt.title('Loss over Epochs')" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/179/Q2.ipynb b/submissions_extracted/179/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..03b51aece767874a92fa661dd9e396558d20deab --- /dev/null +++ b/submissions_extracted/179/Q2.ipynb @@ -0,0 +1,195 @@ +{ + "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", + "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" + ], + "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", + "\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:linear =self.layer1 = nn.Linear(input_dim, hidden_dim)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2:x =self.layer2 = nn.Linear(hidden_dim, hidden_dim)\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3:y =self.layer3 = nn.Linear(hidden_dim, output_dim)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4:self.layer4 = nn.Linear(hidden_dim, output_dim)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5:self.layer5 = nn.Linear(hidden_dim, output_dim)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1:plt.plot(train_losses, label='Train Loss')" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2 (Bonus):plt.plot(val_losses, label='Validation Loss')" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/179/Q3.ipynb b/submissions_extracted/179/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..a8f635fab7bb104a5929bbcb5f36530c3190ab65 --- /dev/null +++ b/submissions_extracted/179/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:df = pd.read_csv(f\"{path}/weather_classification_data.csv\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2:df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3:df.info():" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4:df.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1:cols = ['price', 'year', 'manufacturer', 'condition', 'cylinders', 'fuel', 'odometer', 'transmission', 'type']\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2:df_clean = df_cars[cols].copy(" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3:print(f\"Before: {df_clean.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4:df_clean = df_clean.dropna(subset=['price', 'year', 'odometer'])" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5:print(f\"After dropping missing price/year/odometer: {df_clean.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1:X = df_clean[feature_cols]" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5:y = df_clean['price']" + ], + "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/18/Q1.ipynb b/submissions_extracted/18/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..0c3899e8395b26ad87205005057684b876f5b697 --- /dev/null +++ b/submissions_extracted/18/Q1.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/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 seaborn as sns\n", + "import matplotlib.pyplot as plt\n", + "\n", + "# 1. red\n", + "df = pd.read_csv('Q1_data.csv')\n", + "\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:2\n", + "print(\"--- First 5 Rows ---\")\n", + "print(df.head)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "# 3 (Types, non-null counts)\n", + "print(\"\\n--- Dataset Information ---\")\n", + "df.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "# 4. (Mean, Std, Min, Max, etc.)\n", + "print(\"\\n--- Statistical Description ---\")\n", + "print(df.describe())" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "#(delivery_time)\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')\n", + "plt.ylabel('Frequency')\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "# Drop ID column\n", + "data = data.drop('ID_LAT_LON_YEAR_WEEK', axis=1)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + " Check missing values\n", + "missing_values = data.isnull().sum()\n", + "print(\"Hint: I guess you want to have a closer look at the columns with missing values :\")\n", + "print(missing_values[missing_values > 0])\n", + "# Fill missing values with mean for each column\n", + "data = data.fillna(data.mean())" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "lt.figure(figsize=(10, 6))\n", + "plt.hist(data['emission'], bins=60, edgecolor='black')\n", + "plt.title('Distribution of Emissions')\n", + "plt.xlabel('Emission')\n", + "plt.ylabel('Count')\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "from sklearn.preprocessing import LabelEncoder\n", + "\n", + "categorical_cols = train_df.select_dtypes(include=[\"object\"]).columns\n", + "for col in categorical_cols:\n", + " print(f\"Encoding column: {col}\")\n", + " le = LabelEncoder()\n", + " train_df[col] = le.fit_transform(train_df[col])\n", + "train_df\n", + "\n", + "Encoding" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "rom sklearn.preprocessing import LabelEncoder\n", + "\n", + "categorical_cols = train_df.select_dtypes(include=[\"object\"]).columns\n", + "for col in categorical_cols:\n", + " print(f\"Encoding column: {col}\")\n", + " le = LabelEncoder()\n", + " train_df[col] = le.fit_transform(train_df[col])\n", + "train_df" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 6: Write your code here:\n", + "rom sklearn.metrics import mean_absolute_error\n", + "\n", + "# Calculate baseline predictions using median\n", + "baseline_pred = data['emission'].median()\n", + "baseline_mae = mean_absolute_error(data['emission'], [baseline_pred] *\n", + "len(data))\n", + "print(f\"Baseline MAE: {baseline_mae:.4f}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "majority_class = y.value_counts().idxmax()\n", + "baseline_pred = [majority_class] * len(y)\n", + "\n", + "# Evaluate the baseline\n", + "baseline_f1 = f1_score(y, baseline_pred, average='weighted')\n", + "print(f\"Baseline F1-Score (majority class): {baseline_f1:.4f}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:\n", + "# Define classification models\n", + "models = {\n", + " \"Logistic Regression\": LogisticRegression(max_iter=10000),\n", + " \"Random Forest Classifier\":\n", + "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\n", + "Regression\"]), ('gnb', models[\"Random Forest Classifier\"])],\n", + "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.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'))" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + " Plot feature importance\n", + "importance = pd.DataFrame({\n", + "'feature': features,\n", + "'importance': model.feature_importances_\n", + "})\n", + "importance = importance.sort_values('importance',\n", + "ascending=True).tail(trained)\n", + "plt.figure(figsize=())\n", + "plt.barh(importance['feature'], importance['importance'])\n", + "plt.title('Top 10 Feature Importance')\n", + "plt.xlabel('Importance')\n", + "plt.tight_layout()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "plt.figure(figsize=(trained))\n", + "plt.hist(valid_pred, bins=30, edgecolor='black')\n", + "plt.title('Distribution of Predictions')\n", + "plt.xlabel('Predicted Emission')\n", + "plt.ylabel('Count')\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:\n", + "from lightgbm import LGBMRegressor\n", + "\n", + "# Initialize and train model\n", + "model = LGBMRegressor(random_state=42, verbose=-1)\n", + "model.fit(X_train, y_train)\n", + "\n", + "from sklearn.metrics import mean_absolute_error\n", + "\n", + "# Calculate baseline predictions using median\n", + "baseline_pred = data['emission'].median()\n", + "baseline_mae = mean_absolute_error(data['emission'], [baseline_pred] *\n", + "len(data))\n", + "print(f\"Baseline MAE: {baseline_mae:.4f}\")\n", + "\n", + "\n", + "from sklearn.metrics import mean_absolute_error\n", + "\n", + "# Calculate baseline predictions using median\n", + "baseline_pred = data['emission'].median()\n", + "baseline_mae = mean_absolute_error(data['emission'], [baseline_pred] *\n", + "len(data))\n", + "print(f\"Baseline MAE: {baseline_mae:.4f}\")\n", + "\n", + "\n" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/18/Q2.ipynb b/submissions_extracted/18/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..f65ded586b7a72636185e471abe13e11196028e9 --- /dev/null +++ b/submissions_extracted/18/Q2.ipynb @@ -0,0 +1,317 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/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.nn as nn\n", + "import torch.optim as optim\n", + "from torch.utils.data import DataLoader, TensorDataset\n", + "\n", + "# Create a simple neural network (maximum 5 layers)\n", + "class SimpleNN(nn.Module):\n", + " def __init__(X_train, X_test, y_train, y_test):\n", + " super(SimpleNN, self).__init__()\n", + " self.model = nn.Sequential(\n", + " nn.Flatten(),\n", + " nn.Linear(input_size,X_train ),\n", + " nn.ReLU(),\n", + " nn.Linear(X_test),\n", + " nn.ReLU(),\n", + " nn.Linear(y_train, y_test)\n", + " )\n", + "\n", + " def forward(self, x):\n", + " return self.model(x)\n", + "\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 2. Create TensorDataset objects\n", + "\n", + "# Prepare the dataset\n", + "X_train = data['X_train'].reshape(data['X_train'].shape[0], -1) #\n", + "Flatten for fully connected layers\n", + "y_train = data['y_train'].long()\n", + "X_test = data['X_test'].reshape(data['X_test'].shape[0], -1)\n", + "y_test = data['y_test'].long()\n", + "\n", + "train_dataset = TensorDataset(X_train, y_train)\n", + "train_loader = DataLoader(train_dataset, batch_size=32, shuffle=True)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 3. Create DataLoaders\n", + "\n", + "\n", + "\n", + "import torch.nn as nn\n", + "import torch.optim as optim\n", + "from torch.utils.data import DataLoader, TensorDataset\n", + "\n", + "# Create a simple neural network (maximum 5 layers)\n", + "class SimpleNN(nn.Module):" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 4. Print shape of one batch\n", + "\n", + "epochs = X_train, X_test, y_train, y_test\n", + "for epoch in range(epochs):\n", + " for inputs, labels in train_loader:\n", + " optimizer.zero_grad()\n", + " outputs = model(inputs)\n", + " loss = criterion(outputs, labels)\n", + " loss.backward()\n", + " optimizer.step()\n", + " print(f\"Epoch {X_train}/{X_test}, Loss: {(y_train):. y_test}\")\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 5. Display sample images\n", + "\n", + "# 1. Determine the number of unique labels in y_train\n", + "number_of_labels = len(torch.unique(data['y_train']))\n", + "print(f\"Number of unique labels: {number_of_labels}\")\n", + "\n", + "# 2. Determine the shape of the input data (X_train)\n", + "data_shape = data['X_train'].shape\n", + "print(f\"Shape of the input data (X_train): {data_shape} (n_samples,\n", + "channels, time_steps, subcarriers)\")\n", + "\n", + "# 3. Find the maximum value in the dataset (X_train)\n", + "maximum_value = torch.max(data['X_train'])\n", + "print(f\"Maximum value in X_train: {maximum_value}\")\n", + "\n", + "# 4. Find the minimum value in the dataset (X_train)\n", + "minimum_value = torch.min(data['X_train'])\n", + "print(f\"Minimum value in X_train: {minimum_value}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your model class here:\n", + "import torch.nn as nn\n", + "import torch.optim as optim\n", + "from torch.utils.data import DataLoader, TensorDataset\n", + "\n", + "\n", + "\n", + "# Prepare the dataset\n", + "X_train = data['X_train'].reshape(data['X_train'].shape[0], -1) #\n", + "Flatten for fully connected layers\n", + "y_train = data['y_train'].long()\n", + "X_test = data['X_test'].reshape(data['X_test'].shape[0], -1)\n", + "y_test = data['y_test'].long()\n", + "\n", + "train_dataset = TensorDataset(X_train, y_train)\n", + "train_loader = DataLoader(train_dataset, batch_size=32, shuffle=True)\n", + "\n", + "# Initialize the model\n", + "input_size = X_train.shape[1]\n", + "num_classes = number_of_labels\n", + "model = SimpleNN(input_size, num_classes)\n", + "\n", + "\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your training loop here:\n", + "class SimpleNN(nn.Module):\n", + " def __init__(self, input_size, num_classes):\n", + " super(SimpleNN, self).__init__()\n", + " self.model = nn.Sequential(\n", + " nn.Flatten(),\n", + " nn.Linear(input_size, 128),\n", + " nn.ReLU(),\n", + " nn.Linear(128, 64),\n", + " nn.ReLU(),\n", + " nn.Linear(64, num_classes)\n", + " )\n", + "\n", + " def forward(self, x):\n", + " return self.model(x)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your validation loop here:\n", + "plt.figure(figsize=(10, 6))\n", + "plt.hist(valid_pred, bins=30, edgecolor='black')\n", + "plt.title('Distribution of Predictions')\n", + "plt.xlabel('Predicted Emission')\n", + "plt.ylabel('Count')\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Define device, model, loss, optimizer:\n", + "# Define loss function and optimizer\n", + "criterion = nn.CrossEntropyLoss()\n", + "optimizer = optim.Adam(model.parameters(), lr=0.001)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Start training for 20 epochs:\n", + "# Train the model\n", + "epochs = 20\n", + "for epoch in range(epochs):\n", + " for inputs, labels in train_loader:\n", + " optimizer.zero_grad()\n", + " outputs = model(inputs)\n", + " loss = criterion(outputs, labels)\n", + " loss.backward()\n", + " optimizer.step()\n", + " print(f\"Epoch {epoch+1}/{epochs}, Loss: {loss.item():.4f}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "\n", + "\n", + "import torch.nn as nn\n", + "import torch.optim as optim\n", + "from torch.utils.data import DataLoader, TensorDataset\n", + "\n", + "# Create a simple neural network (maximum 5 layers)\n", + "class SimpleNN(nn.Module):" + ], + "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/18/Q3.ipynb b/submissions_extracted/18/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..99c9da277a39d35c520cf03eed19cdef49d500a5 --- /dev/null +++ b/submissions_extracted/18/Q3.ipynb @@ -0,0 +1,346 @@ +{ + "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", + "df = pd.read_csv(\"_data.csv\", usecols=[\"column1\", \"column2\"], nrows=10)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:Here’s how you can inspect the first few rows of a Pandas DataFrame using the head() method in Python.\n", + "Pythonimport pandas as pd\n", + "\n", + "# Example DataFrame\n", + "data = {\n", + " 'Name': ['Alice', 'Bob', 'Charlie', 'David', 'Eva', 'Frank'],\n", + " 'Age': [25, 30, 35, 40, 45, 50],\n", + " 'City': ['NY', 'LA', 'Chicago', 'Houston', 'Phoenix', 'Seattle']\n", + "}\n", + "\n", + "df = pd.DataFrame(data)\n", + "\n", + "# View the first 5 rows (default)\n", + "print(\"First 5 rows:\")\n", + "print(df.head())\n", + "\n", + "# View the first 3 rows\n", + "print(\"\\nFirst 3 rows:\")\n", + "print(df.head(3))\n", + "\n", + "Explanation:\n", + "\n", + "df.head() → Returns the first 5 rows by default.\n", + "df.head(n) → Returns the first n rows, where n is an integer you specify.\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:Here’s a complete Python example showing how to display dataset information using Pandas’ info() method.\n", + "Pythonimport pandas as pd\n", + "\n", + "# Sample dataset\n", + "data = {\n", + " \"Name\": [\"Alice\", \"Bob\", \"Charlie\", \"David\"],\n", + " \"Age\": [25, 30, None, 40],\n", + " \"City\": [\"New York\", \"Los Angeles\", \"Chicago\", None]\n", + "}\n", + "\n", + "# Create DataFrame\n", + "df = pd.DataFrame(data)\n", + "\n", + "# Display the DataFrame\n", + "print(\"Dataset Preview:\")\n", + "print(df, \"\\n\")\n", + "\n", + "# Display dataset information\n", + "print(\"Dataset Information:\")\n", + "df.info()\n", + "\n", + "\n", + "\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "What info() Shows:\n", + "\n", + "Index range (e.g., RangeIndex: 4 entries, 0 to 3)\n", + "Column names\n", + "Non-null counts (helps detect missing values)\n", + "Data types (int64, float64, object, etc.)\n", + "Memory usage" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "\n", + "# Example dataset with missing values and duplicates\n", + "data = {\n", + " 'Name': ['Alice', 'Bob', 'Charlie', 'Alice', None],\n", + " 'Age': [25, None, 30, 25, 22],\n", + " 'City': ['NY', 'LA', None, 'NY', 'Chicago']\n", + "}\n", + "\n", + "# Create DataFrame\n", + "df = pd.DataFrame(data)\n", + "print(\"Original DataFrame:\\n\", df, \"\\n\")\n", + "\n", + "\n", + "\n", + "\n", + "# Option A: Fill missing values (example: fill with defaults)\n", + "df_filled = df.fillna({\n", + " 'Name': 'Unknown',\n", + " 'Age': df['Age'].mean(), # Replace missing Age with mean\n", + " 'City': 'Not Specified'\n", + "})\n", + "\n", + "# Option B: Drop rows with missing values (if preferred)\n", + "df_dropped = df.dropna()\n", + "\n", + "print(\"After Filling Missing Values:\\n\", df_filled, \"\\n\")\n", + "print(\"After Dropping Missing Values:\\n\", df_dropped, \"\\n\")\n", + "\n", + "\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:# Remove exact duplicate rows\n", + "df_no_duplicates = df_filled.drop_duplicates()\n", + "\n", + "print(\"After Removing Duplicates:\\n\", df_no_duplicates)\n", + "\n", + "\n", + "How it works\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "ef 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(train_df)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "from sklearn.preprocessing import LabelEncoder\n", + "\n", + "categorical_cols = train_df.select_dtypes(include=[\"object\"]).columns\n", + "for col in categorical_cols:\n", + " print(f\"Encoding column: {col}\")\n", + " le = LabelEncoder()\n", + " train_df[col] = le.fit_transform(train_df[col])\n", + "train_df" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "rom sklearn.metrics import mean_absolute_error\n", + "\n", + "# Calculate baseline predictions using median\n", + "baseline_pred = data['emission'].median()\n", + "baseline_mae = mean_absolute_error(data['emission'], [baseline_pred] *\n", + "len(data))\n", + "print(f\"Baseline MAE: {baseline_mae:.4f}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "majority_class = y.value_counts().idxmax()\n", + "baseline_pred = [majority_class] * len(y)\n", + "\n", + "# Evaluate the baseline\n", + "baseline_f1 = f1_score(y,x baseline_pred, average='weighted')\n", + "print(f\"Baseline F1-Score (majority class): {baseline_f1:.4f}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:\n", + "# Define classification models\n", + "models = {\n", + " \"Logistic Regression\": LogisticRegression(max_iter=10000),\n", + " \"Random Forest Classifier\":\n", + "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\n", + "Regression\"]), ('gnb', models[\"Random Forest Classifier\"])],\n", + "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.loc[train_index, :], X.loc[test_index, :]\n", + " y_Train, y_Test = y.iloc[train_index], y.iloc[test_index]\n", + " # Train the model\n", + " model.fit(X_Train, y_Train)\n", + " # Predict on the test set\n", + " y_pred = model.predict(X_Test)\n", + "\n", + " # Calculate metrics\n", + " scores_f1.append(f1_score(y_Test, y_pred, average='weighted'))\n", + "\n", + " # Print the results\n", + " print(f\"{model_name} F1-Score: {np.mean(scores_f1):.4f}\")\n", + " print(\"\\n\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:# Plot feature importance\n", + "importance = pd.DataFrame({\n", + "'feature': features,\n", + "'importance': model.feature_importances_\n", + "})\n", + "importance = importance.sort_values('importance',\n", + "ascending=True).tail(10)\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", + "lt.hist(valid_pred, bins=30, edgecolor='golden feature')\n", + "plt.title('Distribution of Predictions')\n", + "plt.xlabel('Predicted Emission')\n", + "plt.ylabel('Count')\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:\n", + "rom 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", + "\n", + "\n", + "import warnings\n", + "warnings.simplefilter(action='ignore', category=FutureWarning)\n", + "pd.options.mode.chained_assignment = None # default='warn'\n", + "#pd.set_option('display.float_format', lambda x: '%.3f' % x)\n", + "plt.rcParams[\"figure.figsize\"] = (12, 8)\n", + "pd.set_option('display.max_columns', None)" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/180/Q1.ipynb b/submissions_extracted/180/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..1bd6143db1aa375bc07ba3864bfad41fe4f1235f --- /dev/null +++ b/submissions_extracted/180/Q1.ipynb @@ -0,0 +1,266 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import numpy as np\n", + "import pandas as pd\n", + "import matplotlib.pyplot as plt\n", + "import seaborn as sns\n", + "import os\n", + "from sklearn.model_selection import train_test_split, StratifiedKFold, cross_val_score\n", + "from sklearn.preprocessing import StandardScaler, LabelEncoder\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": [ + "Q1_path = os.path.join(path, 'Q1_data.csv')\n", + "df_Q = pd.read_csv(Q1_path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "os.listdir(path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "df_Q.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "df_Q.describe().T" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "df_Q.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# we use the plot tp see if our target Class imbalance or not\n", + "plt.figure(figsize=(10, 5))\n", + "plt.hist(df_Q['Delivery_Time'].dropna(), bins=30, edgecolor='black', color='Pink')\n", + "plt.title(' Delivery Time ')\n", + "plt.xlabel('Dlivery')\n", + "plt.ylabel('Frequency')\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "df_dro = df_Q.drop(['Order_ID'], axis=1)\n", + "df_dro" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "df_Q.isnull().sum()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "#Handle missing values appropriately\n", + "df_miss = df_Q.copy()\n", + "df_miss['Weather'] = df_mode['Weather'].fillna(df_mode['Weather'].mode()[0])\n", + "df_miss['Traffic_Level'] = df_mode['Traffic_Level'].fillna(df_mode['Traffic_Level'].mode()[0])\n", + "df_miss['Time_of_Day'] = df_mode['Time_of_Day'].fillna(df_mode['Time_of_Day'].mode()[0])\n", + "df_miss['Courier_Experience_yrs'] = df_mean['Courier_Experience_yrs'].fillna(df_mean['Courier_Experience_yrs'].median())\n", + "df_miss['Delivery_Time'] = df_mean['Delivery_Time'].fillna(df_mean['Delivery_Time'].mean())\n", + "df_miss" + ], + "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)\n", + "df.drop_duplicates(inplace=True)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Encode categorical variables\n", + "from sklearn.preprocessing import LabelEncoder\n", + "categorical_cols = df.select_dtypes(include=[\"object\"]).columns\n", + "\n", + "for col in categorical_cols:\n", + " print(f\"Encoding column: {col}\")\n", + " le = LabelEncoder()\n", + " # TODO: Apply fit_transform to encode the column\n", + " df[col] = le.fit_transform(df[col])\n", + "\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "\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": [ + "# Check for target imbalance and state if it is imbalanced or not" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Split the dataset into features (X) and target (y)\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, test_size=0.2, random_state=42\n", + ")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "from sklearn.ensemble import RandomForestClassifier\n", + "from sklearn.ensemble import RandomForestRegressor\n", + "from sklearn.metrics import mean_absolute_error\n", + "#Use the correct split: KFold OR StratifiedKFold\n", + "n_splits = 5\n", + "skf = StratifiedKFold(n_splits=n_splits, shuffle=True, random_state=42)\n", + "rf = RandomForestRegressor(n_estimators=100, max_depth=5, random_state=42)\n", + "mae = mean_absolute_error(y_train,y_test)\n", + "print(f\"MAE: {mae:.2f}\")\n", + "print(\" → Average absolute error\")\n", + "print(\" → Easy to interpret (same units as target)\")" + ], + "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/180/Q3.ipynb b/submissions_extracted/180/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..774d2b123225b5e1898f8863b53f9422c6e7eda8 --- /dev/null +++ b/submissions_extracted/180/Q3.ipynb @@ -0,0 +1,209 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import numpy as np\n", + "import pandas as pd\n", + "import matplotlib.pyplot as plt\n", + "import seaborn as sns\n", + "import os\n", + "from sklearn.model_selection import train_test_split, StratifiedKFold, cross_val_score\n", + "from sklearn.preprocessing import StandardScaler, LabelEncoder\n", + "import kagglehub\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": [ + "os.listdir(path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "csv_path = os.path.join(path, \"Q3_data.csv\")\n", + "\n", + "df = pd.read_csv(csv_path)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\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": [ + "df.isnull().sum()\n", + "df_miss = df.copy()\n", + "df_miss['D_142\t'] = df_mean['D_142\t'].fillna(df_mean['D_142\t'].median())\n", + "df_miss['D_144\t'] = df_mean['D_142\t'].fillna(df_mean['D_144\t'].median())\n", + "df_miss['D_144\t'] = df_mean['D_142\t'].fillna(df_mean['D_144\t'].median())\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)\n", + "df.drop_duplicates(inplace=True)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "\n", + "numerical_cols = df.select_dtypes(include=[\"number\"]).columns.drop(\"Target\")\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 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/181/Q1.ipynb b/submissions_extracted/181/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..cff8ae9e3e7ee81ed3ce2ebd11cb5fe69fcd2d86 --- /dev/null +++ b/submissions_extracted/181/Q1.ipynb @@ -0,0 +1,292 @@ +{ + "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": [ + "# Task 1: Write your code here:\n", + "\n", + "delivery = os.path.join(path,'Q1_data.csv')\n", + "\n", + "df = pd.read_csv(delivery)\n", + "\n", + "print(\"the is shape is :\",df.shape)\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()" + ], + "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", + "# 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 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=df.drop(columns=['Order_ID']).copy()\n", + "\n" + ], + "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", + "\n", + "def check_duplicates(df_NOorder):\n", + " duplicates = df_NOorder.duplicated().sum()\n", + " print(f\"Number of Duplicate Samples: {duplicates}\")\n", + " if duplicates > 0:\n", + " print(\"Dropping Duplicates...\")\n", + " df_NOorder.drop_duplicates(inplace=True)\n", + " print(\"Duplicates Dropped.\")\n", + " else:\n", + " print(\"No Duplicate Samples Found.\")\n", + "\n", + "check_duplicates(df_NOorder)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "from sklearn.preprocessing import LabelEncoder, OneHotEncoder, StandardScaler\n", + "categorical_cols=df.select_dtypes(include=[\"object\"]).columns\n", + "\n", + "onehot_encoder = OneHotEncoder(handle_unknown='ignore', sparse_output=False)\n", + "X_encoded = pd.DataFrame(onehot_encoder.fit_transform(df), columns=onehot_encoder.get_feature_names_out(df.columns))\n", + "\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", + "label_encoders = {}\n", + "for col in categorical_cols:\n", + " le = LabelEncoder()\n", + " df[col] = le.fit_transform(df[col])\n", + " label_encoders[col] = le\n", + "\n", + "df" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 6: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "X = df.drop(\"Delivery_Time\", axis=1).astype(np.float64)\n", + "y = df['Delivery_Time'].astype(np.float64)" + ], + "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 ,KFold\n", + "from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score\n", + "from sklearn.metrics import mean_squared_error\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", + "\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_mse = []\n", + "for fold_idx, (train_index, test_index) in enumerate(kf.split(X)):\n", + " print(f\"\\nFold {fold_idx + 1}/{n_splits}\")\n", + "\n", + " X_train, X_test = X.iloc[train_index], X.iloc[test_index]\n", + " y_train, y_test = y.iloc[train_index], y.iloc[test_index]\n", + "\n", + " model = RandomForestClassifier(n_estimators=100, max_depth=15,\n", + " class_weight='balanced', random_state=42)\n", + "\n", + "\n", + " mse = sklearn_mse(y_test, y_pred)\n", + "\n", + " # Store results\n", + " lr_mse.append(mse)\n", + "\n", + "y_pred = model.predict(X_test)\n", + "\n", + "model.fit(X_train, y_train)\n", + "print(\"Model trained!\")\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": [ + "# 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:\n", + "plt.figure(figsize=(10, 6))\n", + "plt.hist(avg_loss, label='Logistic Regression Loss', color='purple')\n", + "plt.title('Average Logistic Regression Loss Curve (Across 5 Folds)')\n", + "plt.xlabel('t')\n", + "plt.ylabel('d')\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/181/Q2.ipynb b/submissions_extracted/181/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..59593d1af9d6c04a44609906b8ebc1b8d148ad2a --- /dev/null +++ b/submissions_extracted/181/Q2.ipynb @@ -0,0 +1,395 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q2-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import os\n", + "import pandas as pd\n", + "import numpy as np\n", + "from PIL import Image\n", + "from sklearn.model_selection import train_test_split\n", + "import torch\n", + "import torch.nn as nn\n", + "from 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", + "import torch\n", + "X_train = torch.tensor(X_train, dtype=torch.float32)\n", + "X_test = torch.tensor(X_test, dtype=torch.float32)\n", + "y_train = torch.tensor(y_train, dtype=torch.float32)\n", + "y_test = torch.tensor(y_test, dtype=torch.float32)\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 2. Create TensorDataset objects\n", + "\n", + "train_dataset = TensorDataset(X_train, y_train)\n", + "test_dataset = TensorDataset(X_test, y_test)\n", + "\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 3. Create DataLoaders\n", + "\n", + "# Create Dataloaders to train and test data in batches\n", + "train_loader = DataLoader(train_dataset, batch_size=32, shuffle=True)\n", + "test_loader = DataLoader(test_dataset, batch_size=32, shuffle=False)\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 4. Print shape of one batch\n", + "X_batch, y_batch = next(iter(train_loader))\n", + "print(f\"Training batch input shape: {X_batch.shape}\")\n", + "print(f\"Training batch labels shape: {y_batch.shape}\")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 5. Display sample images\n", + "images, labels = next(iter(train_loader))\n", + "\n", + "plt.figure(figsize=(16, 8))\n", + "\n", + "plt.imshow(images[0].flatten(), cmap='gray')\n", + "plt.title(f\"Label: {labels[0].item()}\")\n", + "plt.axis('off')\n", + "\n", + "plt.tight_layout()\n", + "plt.show()\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your model class here:\n", + "class NN4Layer(nn.Module):\n", + "\n", + " def __init__(self, input_dim, hidden_dim, output_dim):\n", + " super(NN4Layer, self).__init__()\n", + "\n", + " # First linear layer: input features -> hidden layer\n", + " self.layer1 = nn.Linear(input_dim, hidden_dim)\n", + "\n", + " # Second linear layer: hidden layer -> hidden layer\n", + " self.layer2 = nn.Linear(hidden_dim, hidden_dim)\n", + "\n", + " # Third linear layer: hidden layer -> hidden layer\n", + " self.layer3 = nn.Linear(hidden_dim, hidden_dim)\n", + "\n", + " # Output layer: hidden layer -> number of classes (logits)\n", + " self.layer4 = nn.Linear(hidden_dim, output_dim)\n", + "\n", + " # ReLU activation for non-linearity\n", + " self.relu = nn.ReLU()\n", + "\n", + " # 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", + "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", + "\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", + "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 = 16 # 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", + "num_epochs = 20\n", + "learning_rate = 0.001\n", + "\n", + "train_losses = []\n", + "val_losses = []\n", + "\n", + "print('Starting Training...')\n", + "for epoch in range(num_epochs):\n", + " # Train one epoch\n", + " train_loss = train_one_epoch(model, optimizer, criterion, train_loader, device)\n", + "\n", + " # Validate\n", + " val_loss = validate(model, criterion, test_loader, device)\n", + "\n", + " train_losses.append(train_loss)\n", + " val_losses.append(val_loss)\n", + "\n", + " if (epoch + 1) % 5 == 0:\n", + " print(\n", + " f'Epoch [{epoch+1}/{num_epochs}], '\n", + " f'Train Loss: {train_loss:.4f}, '\n", + " f'Val Loss: {val_loss:.4f}'\n", + " )\n", + "\n", + "print('Training Complete!')" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "plt.figure(figsize=(7, 5))\n", + "\n", + "plt.plot(train_losses, label='Train Loss')\n", + "plt.plot(val_losses, label='Validation Loss')\n", + "plt.title('Loss over Epochs')\n", + "plt.xlabel('Epoch')\n", + "plt.ylabel('Loss')\n", + "plt.legend()\n", + "\n", + "plt.tight_layout()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2 (Bonus): Write your code here:\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/181/Q3.ipynb b/submissions_extracted/181/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..31d0ce090a187aeb6b3b073349a952f8757e0841 --- /dev/null +++ b/submissions_extracted/181/Q3.ipynb @@ -0,0 +1,292 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "import os\n", + "import pandas as pd\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", + "golden = os.path.join(path,'Q3_data.csv')\n", + "\n", + "df = pd.read_csv(golden)\n", + "\n", + "print(\"the is shape is :\",df.shape)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "\n", + "print('the dataset first few rows \\n',df.head())" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "\n", + "df.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "df.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "missing_percentage = (df.isnull().sum() / len(df)) * 100\n", + "missing_data = pd.DataFrame({\n", + " 'Column': missing_percentage.index,\n", + " 'Missing_Percentage': missing_percentage.values\n", + "})\n", + "missing_data = missing_data[missing_data['Missing_Percentage'] > 0].sort_values('Missing_Percentage', ascending=False)\n", + "\n", + "print(\"Missing Data Analysis:\")\n", + "missing_data.head(10)\n", + "\n", + "\n", + "\n", + "df.drop(columns=['D_87','D_88','B_39','D_110','D_111','D_108','B_42','D_73','D_135','D_136'])" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "\n", + "def check_duplicates(df):\n", + " duplicates = df.duplicated().sum()\n", + " print(f\"Number of Duplicate Samples: {duplicates}\")\n", + " if duplicates > 0:\n", + " print(\"Dropping Duplicates...\")\n", + " df.drop_duplicates(inplace=True)\n", + " print(\"Duplicates Dropped.\")\n", + " else:\n", + " print(\"No Duplicate Samples Found.\")\n", + "\n", + "check_duplicates(df)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "from sklearn.preprocessing import StandardScaler\n", + "from sklearn.preprocessing import LabelEncoder\n", + "categorical_cols=df.select_dtypes(include=[\"object\"]).columns\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", + "print(\"Categorical Columns:\", list(categorical_cols))\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "from sklearn.preprocessing import MinMaxScaler\n", + "\n", + "features = df.columns # DON'T SCALE THE TARGET\n", + "\n", + "scaler = MinMaxScaler()\n", + "df[features] = scaler.fit_transform(df[features])\n", + "df.head()\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "def softmax(z):\n", + " z_shifted = z - np.max(z, axis=1, keepdims=True)\n", + " exp_z = np.exp(z_shifted)\n", + " return exp_z / np.sum(exp_z, axis=1, keepdims=True)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "X = df.drop(\"P_2\", axis=1).astype(float)\n", + "y = df['P_2'].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", + "n_splits = 5 # K=5 Folds\n", + "\n", + "# 5-Fold Cross-Validation, shuffled\n", + "kf = KFold(n_splits=n_splits, shuffle=True, random_state=42)\n", + "lr_losses = []\n", + "lr_mse = []\n", + "lr_rmse = []\n", + "lr_r2 = []\n", + "\n", + "# Task 1: Write your code here:\n", + "from catboost import CatBoostRegressor\n", + "model=( CatBoostRegressor(verbose=0))\n", + "\n", + "\n", + "kf = KFold(n_splits=5, shuffle=True, random_state=42)\n", + "\n", + "for fold_idx, (train_index, test_index) in enumerate(kf.split(X)):\n", + " print(f\"\\nFold {fold_idx + 1}/{n_splits}\")\n", + "\n", + " X_train, X_test = X.iloc[train_index], X.iloc[test_index]\n", + " y_train, y_test = y.iloc[train_index], y.iloc[test_index]\n", + "\n", + "\n", + "\n", + " # Train\n", + "model.fit(X_train, y_train)\n", + "\n", + " # Predict\n", + "y_pred = model.predict(X_test)\n", + "\n", + " # Calculate metrics\n", + "mse = sklearn_mse(y_test, y_pred)\n", + "rmse = np.sqrt(mse)\n", + "r2 = r2_score(y_test, y_pred)\n", + "\n", + " # Store results\n", + "all_results[model_name][\"mse\"].append(mse)\n", + "all_results[model_name][\"rmse\"].append(rmse)\n", + "all_results[model_name][\"r2\"].append(r2)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "baseline_pred = np.full_like(y, y.mean())\n", + "\n", + "# Evaluate the baseline\n", + "baseline_mse = sklearn_mse(y, baseline_pred)\n", + "baseline_rmse = np.sqrt(baseline_mse)\n", + "baseline_r2 = r2_score(y, baseline_pred)\n", + "\n", + "print(f\"Baseline MSE (using mean target): {baseline_mse:.4f}\")\n", + "print(f\"Baseline RMSE (using mean target): {baseline_rmse:.4f}\")\n", + "print(f\"Baseline R2 (using mean target): {baseline_r2:.4f}\")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "coeffs = {}\n", + "\n", + "coeffs['Lasso'] = models['LASSO Regression'].coef_\n", + "coeffs['Ridge'] = models['Ridge Regression'].coef_\n", + "\n", + "fig, axes = plt.subplots(1, 2, figsize=(15, 6))\n", + "axes = axes.flatten()\n", + "features = X.columns\n", + "\n", + "for i, (model_name, coef) in enumerate(coeffs.items()):\n", + " # Sort features by absolute coefficient value\n", + " absolute_coef = np.abs(coef)\n", + " sorted_idx = np.argsort(absolute_coef)\n", + "\n", + " ax = axes[i]\n", + " ax.barh(features[sorted_idx], coef[sorted_idx])\n", + " ax.set_title(f\"{model_name} Coefficients\")\n", + " ax.set_xlabel(\"Coefficient Value (Impact)\")\n", + "\n", + "plt.tight_layout()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/182/Q1.ipynb b/submissions_extracted/182/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..f94bfb7e9d6ba10dd6e2a6a2826d462c2a3bfe80 --- /dev/null +++ b/submissions_extracted/182/Q1.ipynb @@ -0,0 +1,324 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "import pandas as pd\n", + "import matplotlib.pyplot as plt\n", + "\n", + "import numpy as np\n", + "import os\n", + "\n", + "from sklearn.model_selection import train_test_split, KFold\n", + "from sklearn.linear_model import LinearRegression\n", + "from sklearn.metrics import mean_absolute_error, mean_squared_error\n", + "\n", + "import warnings\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\")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "df.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "df.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "plt.figure(figsize=(6,4))\n", + "plt.plot(df[\"Delivery_Time\"])\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "df.drop(\"Order_ID\", inplace=True, axis = 1)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "missing = df.isnull().sum() / len(df) * 100\n", + "\n", + "missing_data = pd.DataFrame({\"Columns\": missing.index, 'Missing_Percentage': missing.values})\n", + "\n", + "missing_data = missing_data[missing_data['Missing_Percentage'] > 0].sort_values('Missing_Percentage', ascending=False)\n", + "\n", + "missing_data\n", + "\n", + "df = df.dropna(inplace=False)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "print(df.duplicated().sum())\n", + "df.drop_duplicates(inplace = True)\n", + "print(df.duplicated().sum())" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "from sklearn.preprocessing import LabelEncoder\n", + "\n", + "le = LabelEncoder()\n", + "categories = df.select_dtypes(include=[\"object\"]).columns\n", + "\n", + "for col in categories:\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", + "# delivery distance, restaurant preparation time, traffic conditions, and order details.\n", + "\n", + "from sklearn.preprocessing import StandardScaler\n", + "feature = [\"Distance_km\", \"Preparation_Time_min\", \"Traffic_Level\", \"Weather\", \"Time_of_Day\", \"Vehicle_Type\", \"Courier_Experience_yrs\"]\n", + "standard_scaler = StandardScaler()\n", + "df[feature] = standard_scaler.fit_transform(df[feature])\n", + "\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 6: Write your code here:\n", + "#No need because it is a continous target and we are forming a linear regression model" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "X = df.drop(\"Delivery_Time\", axis = 1, inplace = False)\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.ensemble import RandomForestRegressor\n", + "\n", + "model = RandomForestRegressor(n_estimators=100, max_depth=20, random_state=42, n_jobs=-1)\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):\n", + " X_train, X_test = X.iloc[train_idx], X.iloc[test_idx]\n", + " y_train, y_test = y.iloc[train_idx], y.iloc[test_idx]\n", + "\n", + " # Train model\n", + " model.fit(X_train, y_train)\n", + "\n", + " # Predict\n", + " y_pred = model.predict(X_test)\n", + "\n", + " # Evaluation metrics\n", + " mse_scores.append(mean_squared_error(y_test, y_pred))\n", + " mae_scores.append(mean_absolute_error(y_test, y_pred))\n", + "\n", + "\n", + "# Step 4 : print\n", + "\n", + "# 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)\n" + ], + "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_\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", + "y_pred = model.predict(X_test)\n", + "\n", + "plt.figure(figsize=(6,4))\n", + "plt.hist(y_pred)\n", + "plt.show()\n", + "\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": [ + "# Task Bonus: Write your code here:\n", + "from sklearn.ensemble import RandomForestRegressor\n", + "from catboost import CatBoostRegressor\n", + "from sklearn.metrics import mean_absolute_error\n", + "\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", + "\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 = mean_absolute_error(y_test, y_pred)\n", + "\n", + "\n", + " # Store results\n", + " all_results[model_name][\"mae\"].append(mae)\n", + "\n", + "for model_name in all_results:\n", + " print(f\"\\n{model_name}:\")\n", + " print(f\" MAE: {np.mean(all_results[model_name]['mae']):.4f}\")\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/182/Q2.ipynb b/submissions_extracted/182/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..87719d1e392e2299204205a8ee5107706fd8ae87 --- /dev/null +++ b/submissions_extracted/182/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": [ + "#Libraries I would use :3\n", + "\n", + "import torch\n", + "import torch.nn as nn\n", + "from torch.utils.data import DataLoader, TensorDataset\n", + "from torch.optim import AdamW\n", + "from torchvision.transforms.functional import to_tensor\n", + "import torch.nn.functional as F\n", + "import matplotlib.pyplot as plt\n", + "from torch.nn.modules.loss import CrossEntropyLoss" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 1. Convert Numpy arrays to PyTorch Tensors\n", + "\n", + "X_train = torch.tensor(X_train, dtype=torch.float32)\n", + "X_test = torch.tensor(X_test, dtype=torch.float32)\n", + "y_train = torch.tensor(y_train, dtype=torch.float32)\n", + "y_test = torch.tensor(y_test, dtype=torch.float32)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 2. Create TensorDataset objects\n", + "train_dataset = TensorDataset(X_train, y_train)\n", + "test_dataset = TensorDataset(X_test, y_test)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 3. Create DataLoaders\n", + "train_loader = DataLoader(\n", + " train_dataset,\n", + " batch_size=32,\n", + " shuffle=True\n", + ")\n", + "\n", + "test_loader = DataLoader(\n", + " test_dataset,\n", + " batch_size=32,\n", + " shuffle=False\n", + ")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 4. Print shape of one batch\n", + "X_batch, y_batch = next(iter(train_loader))\n", + "print(f\"Training batch input shape: {X_batch.shape}\")\n", + "print(f\"Training batch labels shape: {y_batch.shape}\")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 5. Display sample images\n", + "images, labels = next(iter(train_loader))\n", + "\n", + "# Display the first 6 images in the batch\n", + "plt.figure(figsize=(10, 8))\n", + "\n", + "for i in range(6):\n", + " plt.subplot(2, 3, i + 1)\n", + " plt.imshow(images[i][0].squeeze(), cmap='gray')\n", + " plt.title(f\"Label: {labels[i].item()}\")\n", + " plt.axis('off')\n", + "\n", + "plt.tight_layout()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your model class here:\n", + "class NN4Layer(nn.Module):\n", + "\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", + "\n", + " self.relu = nn.ReLU()\n", + "\n", + " def forward(self, x):\n", + " return self.layer4(self.relu\n", + " (self.layer3(self.relu(self.layer2\n", + " (self.relu(self.layer1(x)))))))" + ], + "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", + " # 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", + "\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)\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", + "\n", + "device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n", + "model = NN4Layer(36 * 36 * 3, 40, 1).to(device)\n", + "criterion = nn.MSELoss()\n", + "optimizer = AdamW(model.parameters(),0.001)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Start training for 20 epochs:\n", + "\n", + "num_epochs = 20\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=(6,4))\n", + "plt.plot(train_losses, color = 'red')\n", + "plt.plot(val_losses, color = 'blue')\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/182/Q3.ipynb b/submissions_extracted/182/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..cf12f61b32fa41c6e97e8b380bd2b0ca27cd9f10 --- /dev/null +++ b/submissions_extracted/182/Q3.ipynb @@ -0,0 +1,282 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "import pandas as pd\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", + "%pip install kagglehub catboost xgboost tqdm -q\n", + "\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "df = pd.read_csv(f\"{path}/Q3_data.csv\")" + ], + "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 = df.isnull().sum() / len(df) * 100\n", + "\n", + "missing_data = pd.DataFrame({\"Columns\": missing.index, 'Missing_Percentage': missing.values})\n", + "\n", + "missing_data = missing_data[missing_data['Missing_Percentage'] > 0].sort_values('Missing_Percentage', ascending=False)\n", + "\n", + "df.fillna(0, inplace = True)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "print(df.duplicated().sum())\n", + "#No duplicates" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "from sklearn.preprocessing import LabelEncoder\n", + "\n", + "le = LabelEncoder()\n", + "categories = df.select_dtypes(include=[\"object\"]).columns\n", + "\n", + "for col in categories:\n", + " df[col] = le.fit_transform(df[col])\n", + "\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", + "feature = df.select_dtypes(include=[\"float64\"]).columns\n", + "standard_scaler = StandardScaler()\n", + "df[feature] = standard_scaler.fit_transform(df[feature])\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", + " 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', inplace = False, 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, accuracy_score\n", + "\n", + "skf = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)\n", + "model = CatBoostClassifier(\n", + " verbose=0,\n", + " n_estimators=320,\n", + " max_depth=4\n", + " )\n", + "\n", + "acc_fold = []\n", + "f1_fold = []\n", + "\n", + "for fold_idx, (train_index, test_index) in enumerate(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.fit(X_train, y_train)\n", + " y_pred = model.predict(X_test)\n", + "\n", + " accuracy = accuracy_score(y_test, y_pred)\n", + " f1 = f1_score(y_test, y_pred, zero_division=0)\n", + "\n", + " acc_fold.append(accuracy)\n", + " f1_fold.append(f1)\n", + "\n", + " print(f\"fold no. {fold_idx}, acc = {accuracy}, f1 = {f1}\")\n", + "" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "feature = df.drop(\"Target\", inplace = False, axis = 1).columns\n", + "feature_importance = pd.DataFrame({\n", + " 'feature': feature,\n", + " 'importance': model.feature_importances_\n", + "}).sort_values('importance', ascending=False)\n", + "\n", + "plt.figure(figsize=(10, 6))\n", + "plt.barh(feature_importance['feature'], feature_importance['importance'])\n", + "plt.xlabel('Importance')\n", + "plt.title('Feature Importance')\n", + "plt.gca().invert_yaxis()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "print(feature_importance.iloc[0])" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:\n", + "X1 = df[feature_importance.iloc[0]['feature']]\n", + "\n", + "skf = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)\n", + "model = CatBoostClassifier(\n", + " verbose=0,\n", + " n_estimators=320,\n", + " max_depth=4\n", + " )\n", + "\n", + "acc1_fold = []\n", + "f11_fold = []\n", + "\n", + "for fold_idx, (train_index, test_index) in enumerate(skf.split(X1, y)):\n", + "\n", + " # 1. Split data\n", + " X_train, X_test = X.iloc[train_index], X.iloc[test_index]\n", + " y_train, y_test = y.iloc[train_index], y.iloc[test_index]\n", + "\n", + " model.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", + " acc1_fold.append(accuracy)\n", + " f11_fold.append(f1)\n", + "\n", + " print(f\"fold no. {fold_idx}, acc = {accuracy}, f1 = {f1}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "print(\"This is what I got for our original dataframe : \", acc_fold)\n", + "print(\"This is what I got for with the golden feature : \", acc1_fold)" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/183/Q1.ipynb b/submissions_extracted/183/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..12391782289f83daeff6c557f75fa25595d6b471 --- /dev/null +++ b/submissions_extracted/183/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 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')" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "food_path = os.path.join(path, 'Q1_data.csv')\n", + "df_food = pd.read_csv(food_path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "print(f\"Dataset shape: {df_food.shape}\")\n", + "df_food.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "df_food.info() # to check data types and structure\n" + ], + "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", + "# Delivery Time distribution (target variable)\n", + "\n", + "plt.figure(figsize=(10, 5))\n", + "plt.hist(df_food['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()\n" + ], + "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", + "print(f\"shape: {df_clean.shape}\")\n", + "df_clean" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "# check missing value percentage\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)\n", + "\n", + "\n", + "for col in ['Traffic_Level', 'Time_of_Day','Weather']:\n", + " df_clean[col] = df_clean[col].fillna(df_clean[col].mode()[0])\n", + "\n", + "for col in ['Courier_Experience_yrs','Delivery_Time']:\n", + " df_clean[col] = df_clean[col].fillna(df_clean[col].mean())\n", + "print(\"Missing values remaining:\", df_clean.isnull().sum().sum())\n", + "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", + "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", + "#i perfer label encoding\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", + "features = df_clean.columns.drop(\"Delivery_Time\") # we dont scale the target\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:\n" + ], + "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", + "\n", + "# Task 1: Write your code here:\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" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:\n", + "lr_mae = []\n", + "all_results = {}\n", + "model_RF = {\n", + " \"Random Forest Regressor\": RandomForestRegressor(n_estimators=200),\n", + "}\n", + "for name in model_RF:\n", + " all_results[name] = {'mae': []}\n", + "\n", + "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 model_RF.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", + " lr_mae.append(mae)\n", + "\n", + "print(\"RF Regression Results\")\n", + "print(f\" Average MAE: {np.mean(lr_mae):.4f}\")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "coeffs = {}\n", + "\n", + "coeffs['Random_Forest'] = model['Random Forest Regressor'].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", + "plt.figure(figsize=(10, 5))\n", + "plt.hist(df_clean['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 Bonus: Write your code here:\n", + "models = {\n", + " \"Ridge Regression\": Ridge(alpha=1.0, max_iter=10000),\n", + " \"LASSO Regression\": Lasso(alpha=1.0, max_iter=10000)\n", + " }\n", + "\n", + "for name in models:\n", + " all_results[name] = {'mae': []}\n", + "\n", + "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 model_RF.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", + " lr_mae.append(mae)\n", + "\n", + "print(\"RF Regression Results\")\n", + "print(f\" Average MAE: {np.mean(lr_mae):.4f}\")\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/183/Q2.ipynb b/submissions_extracted/183/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..0af98639cc0bbbd9aa54cb7bb2240811de5c4bff --- /dev/null +++ b/submissions_extracted/183/Q2.ipynb @@ -0,0 +1,394 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q2-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import torch\n", + "import torch.nn as nn\n", + "from torchvision.datasets import MNIST\n", + "from torch.utils.data import DataLoader, TensorDataset\n", + "from torch.optim import 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.optim import AdamW\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import os\n", + "import pandas as pd\n", + "import numpy as np\n", + "from PIL import Image\n", + "from sklearn.model_selection import train_test_split\n", + "\n", + "# Load Labels\n", + "labels_df = pd.read_csv(os.path.join(path, \"labels.csv\"))\n", + "img_dir = os.path.join(path, \"images\")\n", + "\n", + "images = []\n", + "ages = []\n", + "\n", + "# Load Images and Resize\n", + "print(\"Loading images...\")\n", + "for index, row in labels_df.iterrows():\n", + " img_name = row.iloc[0]\n", + " age = row.iloc[1]\n", + " img_path = os.path.join(img_dir, img_name)\n", + "\n", + " if os.path.exists(img_path):\n", + " img = Image.open(img_path).convert('RGB')\n", + " img_array = np.array(img) / 255.0 # Normalize pixel values to [0, 1]\n", + " images.append(img_array)\n", + " ages.append(age)\n", + "\n", + "X = np.array(images)\n", + "y = np.array(ages)\n", + "\n", + "# Transpose image dimensions to match PyTorch format (N, C, H, W)\n", + "X = np.transpose(X, (0, 3, 1, 2))\n", + "\n", + "# Split Data\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n", + "\n", + "print(f\"X_train shape: {X_train.shape}\")\n", + "print(f\"X_test shape: {X_test.shape}\")\n", + "print(f\"y_train shape: {y_train.shape}\")\n", + "print(f\"y_test shape: {y_test.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 1. Convert Numpy arrays to PyTorch Tensors\n", + "# Features are floats; labels are also stored as floats for binary classification.\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" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 3. Create DataLoaders\n", + "\n", + "# DataLoader for training data\n", + "train_loader = DataLoader(train_dataset, batch_size=32, shuffle=True)\n", + "\n", + "# DataLoader for test/validation data\n", + "test_loader = DataLoader(test_dataset, batch_size=32, shuffle=False)\n", + "# Get the first batch from the training DataLoader\n", + "X_batch, y_batch = next(iter(train_loader))\n", + "print(f\"Training batch input shape: {X_batch.shape}\")\n", + "print(f\"Training batch labels shape: {y_batch.shape}\")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 4. Print shape of one batch\n", + "\n", + "\n", + "# Inspect the shape of a single sample to confirm the number of input features\n", + "first_sample, _ = train_dataset[0]\n", + "print(f\"Shape of one sample: {first_sample.shape}\")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 5. Display sample images\n", + "# Get one batch of images and labels\n", + "images, labels = next(iter(train_loader))\n", + "\n", + "# Display the first 6 images in the batch\n", + "plt.figure(figsize=(8, 4))\n", + "\n", + "for i in range(6):\n", + " plt.subplot(2, 3, i + 1)\n", + " plt.imshow(images[i].squeeze(),cmap='gray')\n", + " plt.title(f\"Label: {labels[i].item()}\")\n", + " plt.axis('off')\n", + "\n", + "plt.tight_layout()\n", + "plt.show()\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your model class here:\n", + "class NN4Layer(nn.Module):\n", + "\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, hidden_dim)\n", + "\n", + " self.layer5 = nn.Linear(hidden_dim, output_dim)\n", + "\n", + " # ReLU activation for non-linearity\n", + " self.relu = nn.ReLU() # ReLU will be applied later in the loss/metrics\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", + " a4 = self.relu(self.layer4(a3))\n", + "\n", + " # Output layer (raw scores / logits)\n", + " output = self.layer5(a4) # why dont we apply ReLU to the output layer\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) # why are we applying it here?\n", + "\n", + " # Pick the classes with highest probabilities\n", + " predicted = torch.argmax(probabilities, dim=1)\n", + "\n", + " # Accuracy calculation\n", + " correct += (predicted == y_batch).sum().item()\n", + " total += y_batch.size(0)\n", + "\n", + " avg_loss = running_loss / len(test_loader)\n", + " accuracy = correct / total\n", + "\n", + " return avg_loss, accuracy" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Define device, model, loss, optimizer:\n", + "# Device setup\n", + "device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n", + "print(\"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", + "# 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", + "num_epochs = 20\n", + "learning_rate = 0.001\n", + "\n", + "# Define criterion (loss function) - using CrossEntropyLoss as model now outputs logits\n", + "criterion = nn.CrossEntropyLoss()\n", + "# Define optimizer\n", + "optimizer = AdamW(model.parameters(), learning_rate)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "# 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", + "# 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/183/Q3.ipynb b/submissions_extracted/183/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..24724f2f2ae285e07884863369f12be7fa627863 --- /dev/null +++ b/submissions_extracted/183/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": [ + "# Task 1: Write your code here:\n", + "import numpy as np\n", + "import pandas as pd\n", + "import matplotlib.pyplot as plt\n", + "import os\n", + "import kagglehub\n", + "\n", + "from sklearn.model_selection import train_test_split, KFold\n", + "from sklearn.preprocessing import 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", + "Golden_path = os.path.join(path, 'Q3_data.csv')\n", + "df_Golden = pd.read_csv(Golden_path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "# Display first few rows to understand feature values\n", + "df_Golden.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "# Check dataset info: data types & missing values\n", + "df_Golden.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "# Statistical summary (mean, std, min, max)\n", + "df_Golden.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "df_clean= df_Golden.copy()\n", + "print(f\"shape: {df_clean.shape}\")\n", + "df_clean\n", + "# check missing value percentage\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)\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_clean)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "#no need to encode the data there is no categorical value (only floats and intergers)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "from sklearn.preprocessing import StandardScaler\n", + "\n", + "features = df_clean.columns.drop(\"Target\") # we dont scale the target\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 5: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "from IPython.display import clear_output\n", + "\n", + "%pip install kagglehub catboost xgboost tqdm imbalanced-learn -q\n", + "\n", + "clear_output()\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 sklearn.model_selection import KFold\n", + "from sklearn.metrics import mean_squared_error as sklearn_mse, mean_absolute_error, r2_score\n", + "from sklearn.model_selection import StratifiedKFold\n", + "from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score\n", + "from sklearn.linear_model import LogisticRegression\n", + "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 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": [ + "from catboost import CatBoostClassifier" + ], + "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", + "\n", + "\n", + "\n", + "# Task 1: Write your code here:\n", + "\n", + "X = df_clean.drop(\"Target\", axis=1)\n", + "y = df_clean['Target']\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:\n", + "\n", + "n_splits = 5 # K=5 Folds\n", + "\n", + "# Stratified 5-Fold Cross-Validation, shuffled\n", + "skf = StratifiedKFold(n_splits=n_splits, shuffle=True, random_state=42)\n", + "# Storage for logistic regression results for each fold\n", + "lr_losses = []\n", + "lr_accuracy = []\n", + "lr_precision = []\n", + "lr_recall = []\n", + "lr_f1 = []\n", + "results = {}\n", + "model_CB = {\n", + " \"CatBoost\": CatBoostClassifier(\n", + " verbose=0,\n", + " n_estimators=200,\n", + " max_depth=4\n", + " )\n", + "}\n", + "for model_name in model_CB:\n", + " results[model_name] = {'accuracy': [], 'precision': [], 'recall': [], 'f1': []}\n", + "\n", + "for fold_idx, (train_index, test_index) in enumerate(skf.split(X, y)):\n", + " print(f\"\\nFold {fold_idx + 1}/{n_splits}\")\n", + "\n", + " # Get the train & test split for this fold\n", + " X_train, X_test = X.iloc[train_index], X.iloc[test_index]\n", + " y_train, y_test = y.iloc[train_index], y.iloc[test_index]\n", + "\n", + " # Train & Validate Models\n", + " for model_name, model in model_CB.items():\n", + "\n", + " print(f\"Training {model_name}...\")\n", + "\n", + " # Fit the model on train data\n", + " model.fit(X_train, y_train)\n", + "\n", + " # Use the model to predict the test data\n", + " y_pred = model.predict(X_test)\n", + "\n", + " # Calculate evaluation metrics\n", + " accuracy = accuracy_score(y_test, y_pred)\n", + " f1 = f1_score(y_test, y_pred, average='macro') # for multiclass f1 score, you should set the average hyperparameter (\"macro\", \"micro\", \"weighted\")\n", + "\n", + " results[model_name]['accuracy'].append(accuracy)\n", + " results[model_name]['f1'].append(f1)\n", + "for model_name in results:\n", + " print(f\"\\n{model_name}:\")\n", + " # Print the average of each evaluation metric across folds\n", + " print(f\" Accuracy: {np.mean(results[model_name]['accuracy']):.4f}\")\n", + " print(f\" F1-Score: {np.mean(results[model_name]['f1']):.4f}\")\n", + "" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "\n", + "coeffs = {}\n", + "\n", + "coeffs['CBoost'] = model_CB[' CatBoostClassifier '].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/184/Q1.ipynb b/submissions_extracted/184/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..7539f6a15cfa22843f3f909d088f2f0b347b1d06 --- /dev/null +++ b/submissions_extracted/184/Q1.ipynb @@ -0,0 +1,340 @@ +{ + "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 os\n", + "\n", + "df_path = os.path.join(path, 'Q1_data.csv')\n", + "\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 5: Write your code here:\n", + "plt.figure(figsize=(10, 5))\n", + "plt.hist(df['Delivery_Time'], bins=30, edgecolor='black')\n", + "plt.xlabel(\"Delivery Time (minutes)\")\n", + "plt.ylabel(\"Frequency\")\n", + "plt.title(\"Distribution of Delivery Time\")\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "from sklearn.preprocessing import StandardScaler\n", + "\n", + "df.drop(columns=['Order_ID'], inplace=True)\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "\n", + "# step1: check the missing values:\n", + "print(\"Missing values:\")\n", + "print(df.isnull().sum())\n", + "\n", + "# step2: handling:\n", + "# step2.1: we separate numerical and categorical to fill the numerical missing values with the median and the categorical missing values with the mode\n", + "\n", + "num_cols = df.select_dtypes(include=['int64', 'float64']).columns\n", + "cat_cols = df.select_dtypes(include=['object']).columns\n", + "\n", + "for col in num_cols:\n", + " df[col].fillna(df[col].median(), inplace=True)\n", + "\n", + "for col in cat_cols:\n", + " df[col].fillna(df[col].mode()[0], inplace=True)\n", + "\n", + "# step3: re-check\n", + "print('-----------------------')\n", + "print(\"Missing values after handling:\")\n", + "print(df.isnull().sum())\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "\n", + "print(\"Checking for duplicate rows...\")\n", + "duplicate_rows = df.duplicated().sum()\n", + "if duplicate_rows > 0:\n", + " print(f\"Found {duplicate_rows} duplicate rows. Removing them...\")\n", + " df.drop_duplicates(inplace=True)\n", + " print(\"Duplicate rows removed.\")\n", + "else:\n", + " print(\"No duplicate rows found.\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "from sklearn.preprocessing import OneHotEncoder\n", + "\n", + "# Identify categorical columns\n", + "categorical_cols = ['Weather', 'Traffic_Level', 'Time_of_Day', 'Vehicle_Type']\n", + "\n", + "# Apply One-Hot Encoding\n", + "df = pd.get_dummies(df, columns=categorical_cols, drop_first=True)\n", + "\n", + "# Check result\n", + "df.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", + "# Separate features and target\n", + "X = df.drop(columns=['Delivery_Time'])\n", + "y = df['Delivery_Time']\n", + "\n", + "# Apply StandardScaler\n", + "scaler = StandardScaler()\n", + "X_scaled = scaler.fit_transform(X)\n", + "\n", + "# Convert back to DataFrame\n", + "X_scaled = pd.DataFrame(X_scaled, columns=X.columns)\n", + "\n", + "X_scaled.head()\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 6: Write your code here:\n", + "print(\"Features shape:\", X_scaled.shape)\n", + "print(\"Target shape:\", y.shape)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: 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 = X_scaled\n", + "y = y" + ], + "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.iloc[train_index], X.iloc[test_index]\n", + " y_train, y_test = y.iloc[train_index], y.iloc[test_index]\n", + "\n", + " model = RandomForestRegressor(\n", + " n_estimators=100,\n", + " random_state=42\n", + " )\n", + "\n", + " model.fit(X_train, y_train)\n", + " y_pred = model.predict(X_test)\n", + "\n", + " mae = mean_absolute_error(y_test, y_pred)\n", + " mae_scores.append(mae)\n", + " #----\n", + "print(\"MAE scores per fold:\", mae_scores)\n", + "print(\"Average MAE:\", np.mean(mae_scores))" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "import matplotlib.pyplot as plt\n", + "\n", + "# Train model on full dataset for feature importance\n", + "final_model = RandomForestRegressor(\n", + " n_estimators=100,\n", + " random_state=42\n", + ")\n", + "final_model.fit(X, y)\n", + "\n", + "importances = final_model.feature_importances_\n", + "indices = np.argsort(importances)[-10:] # top 10 features\n", + "\n", + "plt.figure()\n", + "plt.barh(range(len(indices)), importances[indices])\n", + "plt.yticks(range(len(indices)), X.columns[indices])\n", + "plt.xlabel(\"Feature Importance\")\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", + "# Predict delivery time\n", + "y_pred_all = final_model.predict(X)\n", + "\n", + "plt.figure()\n", + "plt.hist(y_pred_all, bins=30)\n", + "plt.xlabel(\"Predicted Delivery Time (minutes)\")\n", + "plt.ylabel(\"Frequency\")\n", + "plt.title(\"Predicted Delivery Time Distribution\")\n", + "plt.show()\n" + ], + "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 catboost import CatBoostRegressor\n", + "kf = KFold(n_splits=5, shuffle=True, random_state=42)\n", + "\n", + "mae_scores_ensemble = []\n", + "\n", + "for train_index, test_index in kf.split(X_scaled):\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", + " rf_model = RandomForestRegressor(n_estimators=100, random_state=42)\n", + " rf_model.fit(X_train, y_train)\n", + " rf_pred = rf_model.predict(X_test)\n", + "\n", + " cb_model = CatBoostRegressor(\n", + " iterations=500, learning_rate=0.1, depth=6, verbose=0, random_state=42\n", + " )\n", + " cb_model.fit(X_train, y_train)\n", + " cb_pred = cb_model.predict(X_test)\n", + "\n", + " avg_pred = (rf_pred + cb_pred) / 2\n", + "\n", + " mae = mean_absolute_error(y_test, avg_pred)\n", + " mae_scores_ensemble.append(mae)\n", + "# results:\n", + "print(\"Ensemble MAE per fold:\", mae_scores_ensemble)\n", + "print(\"Average Ensemble MAE:\", np.mean(mae_scores_ensemble))" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/184/Q2.ipynb b/submissions_extracted/184/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..cbed8fe7bbb42f711b7a8edfb3afc7cef3ec0036 --- /dev/null +++ b/submissions_extracted/184/Q2.ipynb @@ -0,0 +1,339 @@ +{ + "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", + "from torch.utils.data import TensorDataset, DataLoader\n", + "import matplotlib.pyplot as plt\n", + "\n", + "X_train_tensor = torch.tensor(X_train, dtype=torch.float32)\n", + "X_test_tensor = torch.tensor(X_test, dtype=torch.float32)\n", + "\n", + "y_train_tensor = torch.tensor(y_train, dtype=torch.float32).unsqueeze(1) # shape (N,1)\n", + "y_test_tensor = torch.tensor(y_test, dtype=torch.float32).unsqueeze(1)\n", + "\n", + "print(\"Tensor shapes:\")\n", + "print(X_train_tensor.shape, y_train_tensor.shape)\n", + "print(X_test_tensor.shape, y_test_tensor.shape)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 2. Create TensorDataset objects\n", + "\n", + "train_dataset = TensorDataset(X_train_tensor, y_train_tensor)\n", + "test_dataset = TensorDataset(X_test_tensor, y_test_tensor)\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 3. Create DataLoaders\n", + "\n", + "train_loader = DataLoader(train_dataset, batch_size=32, shuffle=True)\n", + "test_loader = DataLoader(test_dataset, batch_size=32, shuffle=False)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 4. Print shape of one batch\n", + "\n", + "images_batch, ages_batch = next(iter(train_loader))\n", + "print(\"Batch image shape:\", images_batch.shape)\n", + "print(\"Batch age shape:\", ages_batch.shape)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 5. Display sample images\n", + "# ex 5 pics\n", + "fig, axes = plt.subplots(1, 5, figsize=(15, 3))\n", + "\n", + "for i in range(5):\n", + " img = images_batch[i].permute(1, 2, 0).numpy()\n", + " age = ages_batch[i].item()\n", + "\n", + " axes[i].imshow(img)\n", + " axes[i].set_title(f\"Age: {age}\")\n", + " axes[i].axis(\"off\")\n", + "\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", + "\n", + "class AgeRegressor4Layer(nn.Module):\n", + "\n", + " def __init__(self, input_dim, hidden_dim):\n", + " super(AgeRegressor4Layer, 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", + "\n", + " self.relu = nn.ReLU()\n", + "\n", + " def forward(self, x):\n", + " x = x.view(x.size(0), -1) # flatten image\n", + "\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", + " output = self.layer4(a3)\n", + " return output\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your training loop here:\n", + "def train_one_epoch(model, loader, loss_fn, optimizer, device):\n", + " model.train()\n", + " running_loss = 0.0\n", + "\n", + " for images, ages in loader:\n", + " images, ages = images.to(device), ages.to(device)\n", + "\n", + " preds = model(images)\n", + " loss = loss_fn(preds, ages)\n", + "\n", + " optimizer.zero_grad()\n", + " loss.backward()\n", + " optimizer.step()\n", + "\n", + " running_loss += loss.item()\n", + "\n", + " return running_loss / len(loader)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your validation loop here:\n", + "def validate(model, loader, loss_fn, device):\n", + " model.eval()\n", + " running_loss = 0.0\n", + "\n", + " with torch.no_grad():\n", + " for images, ages in loader:\n", + " images, ages = images.to(device), ages.to(device)\n", + "\n", + " preds = model(images)\n", + " loss = loss_fn(preds, ages)\n", + "\n", + " running_loss += loss.item()\n", + "\n", + " return running_loss / len(loader)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Define device, model, loss, optimizer:\n", + "device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n", + "print(\"Using device:\", device)\n", + "\n", + "C, H, W = X_train.shape[1], X_train.shape[2], X_train.shape[3]\n", + "input_dim = C * H * W\n", + "\n", + "model = AgeRegressor4Layer(input_dim=input_dim, hidden_dim=512).to(device)\n", + "\n", + "loss_fn = nn.MSELoss()\n", + "optimizer = torch.optim.Adam(model.parameters(), lr=0.001)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Start training for 20 epochs:\n", + "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, 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}/{num_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,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 Over Epochs\")\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 numpy as np\n", + "\n", + "model.eval()\n", + "\n", + "images, true_ages = next(iter(test_loader))\n", + "images, true_ages = images.to(device), true_ages.to(device)\n", + "\n", + "with torch.no_grad():\n", + " preds = model(images).cpu().numpy().flatten()\n", + "\n", + "true_ages = true_ages.cpu().numpy().flatten()\n", + "\n", + "# just plot tha first 6 predictions\n", + "plt.figure(figsize=(15, 6))\n", + "\n", + "for i in range(6):\n", + " img = images[i].cpu().permute(1, 2, 0).numpy()\n", + "\n", + " plt.subplot(2, 3, i+1)\n", + " plt.imshow(img)\n", + " plt.title(f\"Pred: {preds[i]:.1f} | Actual: {true_ages[i]:.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/184/Q3.ipynb b/submissions_extracted/184/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..09c7f16ec2381562f673fd76bc33799f01a480b4 --- /dev/null +++ b/submissions_extracted/184/Q3.ipynb @@ -0,0 +1,319 @@ +{ + "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", + "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", + "# step1: check the missing values:\n", + "print(\"Missing values:\")\n", + "print(df.isnull().sum())\n", + "\n", + "# step2: handling:\n", + "# step2.1: we separate numerical and categorical to fill the numerical missing values with the median and the categorical missing values with the mode\n", + "\n", + "num_cols = df.select_dtypes(include=['int64', 'float64']).columns\n", + "cat_cols = df.select_dtypes(include=['object']).columns\n", + "\n", + "for col in num_cols:\n", + " df[col].fillna(df[col].median(), inplace=True)\n", + "\n", + "for col in cat_cols:\n", + " df[col].fillna(df[col].mode()[0], inplace=True)\n", + "\n", + "# step3: re-check\n", + "print('-----------------------')\n", + "print(\"Missing values after handling:\")\n", + "print(df.isnull().sum())\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "print(\"Checking for duplicate rows...\")\n", + "duplicate_rows = df.duplicated().sum()\n", + "if duplicate_rows > 0:\n", + " print(f\"Found {duplicate_rows} duplicate rows. Removing them...\")\n", + " df.drop_duplicates(inplace=True)\n", + " print(\"Duplicate rows removed.\")\n", + "else:\n", + " print(\"No duplicate rows found.\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "from sklearn.preprocessing import LabelEncoder\n", + "\n", + "# Step: Label Encoding\n", + "label_encoder = LabelEncoder()\n", + "\n", + "for col in cat_cols:\n", + " df[col] = label_encoder.fit_transform(df[col])" + ], + "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", + "\n", + "# Exclude target column from scaling\n", + "X = df.drop(\"Target\", axis=1)\n", + "y = df[\"Target\"]\n", + "\n", + "scaled_X = scaler.fit_transform(X)\n", + "\n", + "# Convert back to DataFrame\n", + "X_scaled = pd.DataFrame(scaled_X, columns=X.columns)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "print(y.value_counts(normalize=True))\n", + "\n", + "# check imbalance\n", + "if y.value_counts(normalize=True).min() < 0.3:\n", + " print(\"The target variable is imbalanced.\")\n", + "else:\n", + " print(\"The target variable is not imbalanced.\")\n", + "\n", + "# additional plotting\n", + "import matplotlib.pyplot as plt\n", + "import seaborn as sns\n", + "\n", + "# Plot target imbalance\n", + "plt.figure(figsize=(6,4))\n", + "sns.countplot(x=y, palette=\"viridis\")\n", + "\n", + "plt.title(\"Target Variable Distribution\")\n", + "plt.xlabel(\"Target (0 = No Default, 1 = Default)\")\n", + "plt.ylabel(\"Count\")\n", + "plt.show()\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": [ + "!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 StratifiedKFold\n", + "from sklearn.metrics import accuracy_score, f1_score\n", + "from catboost import CatBoostClassifier\n", + "\n", + "skf = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)\n", + "\n", + "accuracy_scores = []\n", + "f1_scores = []\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 = CatBoostClassifier(\n", + " verbose=0,\n", + " random_state=42\n", + " )\n", + "\n", + " model.fit(X_train, y_train)\n", + " preds = model.predict(X_test)\n", + "\n", + " accuracy_scores.append(accuracy_score(y_test, preds))\n", + " f1_scores.append(f1_score(y_test, preds))\n", + "\n", + "print(\"Average Accuracy:\", sum(accuracy_scores) / len(accuracy_scores))\n", + "print(\"Average F1 Score:\", sum(f1_scores) / len(f1_scores))\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "import matplotlib.pyplot as plt\n", + "import seaborn as sns\n", + "\n", + "#extracting\n", + "importances = model.get_feature_importance()\n", + "feature_names = X.columns\n", + "\n", + "#create a DataFrame for plotting\n", + "fi_df = pd.DataFrame({\n", + " \"Feature\": feature_names,\n", + " \"Importance\": importances\n", + "}).sort_values(by=\"Importance\", ascending=False)\n", + "\n", + "#plotting\n", + "plt.figure(figsize=(10, 8))\n", + "sns.barplot(data=fi_df.head(20), x=\"Importance\", y=\"Feature\", palette=\"viridis\")\n", + "plt.title(\"Top 20 Feature Importances (CatBoost)\")\n", + "plt.xlabel(\"Importance Score\")\n", + "plt.ylabel(\"Feature\")\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "golden_feature = fi_df.iloc[0][\"Feature\"]\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", + "# 1. Create X with only the golden feature\n", + "X_golden = df[[golden_feature]]\n", + "\n", + "# 2. Run StratifiedKFold with CatBoost\n", + "golden_accuracy_scores = []\n", + "golden_f1_scores = []\n", + "\n", + "for train_idx, test_idx in skf.split(X_golden, y):\n", + " X_train, X_test = X_golden.iloc[train_idx], X_golden.iloc[test_idx]\n", + " y_train, y_test = y.iloc[train_idx], y.iloc[test_idx]\n", + "\n", + " model_golden = CatBoostClassifier(verbose=0, random_state=42)\n", + " model_golden.fit(X_train, y_train)\n", + "\n", + " preds = model_golden.predict(X_test)\n", + "\n", + " golden_accuracy_scores.append(accuracy_score(y_test, preds))\n", + " golden_f1_scores.append(f1_score(y_test, preds))\n", + "\n", + "# 3. Print n comparison\n", + "print(\"Full Model Accuracy:\", sum(accuracy_scores) / len(accuracy_scores))\n", + "print(\"Golden Feature Accuracy:\", sum(golden_accuracy_scores) / len(golden_accuracy_scores))\n", + "\n", + "print(\"\\nFull Model F1 Score:\", sum(f1_scores) / len(f1_scores))\n", + "print(\"Golden Feature F1 Score:\", sum(golden_f1_scores) / len(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/185/Q1.ipynb b/submissions_extracted/185/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..46cb83bf544db0961365363584c7762388bf81ac --- /dev/null +++ b/submissions_extracted/185/Q1.ipynb @@ -0,0 +1,379 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/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 sklearn\n", + "import os\n", + "import seaborn as sns" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "dataset = 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", + "dataset.head(10)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "dataset.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "dataset.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "sns.histplot(dataset.Delivery_Time)\n", + "# data seems to have a small right skewe" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "clean_data = dataset.copy()\n", + "\n", + "clean_data = clean_data.drop(columns='Order_ID')\n", + "list(clean_data.columns)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "clean_data.isna().sum()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "clean_data.Weather.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "print(clean_data.Weather.value_counts(normalize=True, dropna=False))\n", + "# clean_data = clean_data.dropna(subset='Weather')\n", + "# less than 5%, we can drop it\n", + "# or fill with mode\n", + "clean_data['Weather']= clean_data['Weather'].fillna(clean_data.Weather.mode()[0])\n", + "clean_data.Weather.value_counts(normalize=True, dropna=False)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "clean_data.Traffic_Level.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "clean_data.Traffic_Level.value_counts(normalize=True, dropna=False)\n", + "clean_data = clean_data.dropna(subset='Traffic_Level')\n", + "# less than 5%, we can drop it\n", + "clean_data.Traffic_Level.value_counts(normalize=True, dropna=False)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "print(clean_data.Time_of_Day.value_counts(normalize=True, dropna=False))\n", + "clean_data = clean_data.dropna(subset='Time_of_Day')\n", + "# less than 5%, we can drop it\n", + "clean_data.Traffic_Level.value_counts(normalize=True, dropna=False)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "clean_data.Courier_Experience_yrs.describe()\n", + "# Low std, but relativily good" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "print(clean_data.Courier_Experience_yrs.value_counts(normalize=True, dropna=False))\n", + "# less than 5%, we can drop it\n", + "# or imput mean\n", + "clean_data['Courier_Experience_yrs']= clean_data['Courier_Experience_yrs'].fillna(clean_data.Courier_Experience_yrs.mean())\n", + "clean_data.Courier_Experience_yrs.value_counts(normalize=True, dropna=False)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# NAN Target features are usless\n", + "clean_data.dropna(subset='Delivery_Time', inplace=True)\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "print(clean_data.duplicated().sum()) # A LOT !\n", + "clean_data.drop_duplicates(inplace=True)\n", + "print(clean_data.duplicated().sum())\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "\n", + "clean_data = pd.get_dummies(clean_data, drop_first=True) # OHE but with pandas :)\n", + "clean_data.info()\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "from sklearn.model_selection import train_test_split\n", + "# # split befor scaling, to avoid info leake (STD, Mean)\n", + "\n", + "# Xtrain, Xtest, ytrain, ytest = train_test_split(clean_data.drop(columns='Delivery_Time'),clean_data['Delivery_Time'] , test_size=.2, shuffle= True, random_state=11)\n", + "# print(Xtrain.shape)\n", + "# print(ytrain.shape)\n", + "# print(Xtest.shape)\n", + "# print(ytest.shape)\n", + "\n", + "# scale target?\n", + "# we can use inverse transform for the target. scale_pred -> scaler.inverse() -> real value\n", + "# but I will skip this for time\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "from sklearn.preprocessing import StandardScaler\n", + "\n", + "s = StandardScaler()\n", + "num_cols = clean_data.select_dtypes(include= 'number').drop(columns='Delivery_Time').columns\n", + "\n", + "clean_data[num_cols] = s.fit_transform(clean_data[num_cols])\n", + "# clean_data[num_cols] = s.transform(clean_data[num_cols])\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 6: Write your code here:\n", + "# target is numerical\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "# already did it" + ], + "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", + "# Storage for linear regression results for each fold\n", + "maes = []\n", + "\n", + "n_splits = 5 # K=5 Folds\n", + "\n", + "# 5-Fold Cross-Validation, shuffled\n", + "kf = KFold(n_splits=n_splits, shuffle=True, random_state=42)\n", + "\n", + "kf = KFold(n_splits=5, shuffle=True, random_state=42)\n", + "\n", + "X = clean_data.drop(columns='Delivery_Time')\n", + "y = clean_data['Delivery_Time']\n", + "model_name='RF'\n", + "model = RandomForestRegressor(max_depth=15, n_estimators=200)\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", + " 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", + " maes.append(mae)\n", + " print(f'MAE = {mae:.3f}')\n", + " # Store results\n", + "print(f'Avg MAE = {np.mean(mae):.3f}')" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "\n", + "fi = model.feature_importances_\n", + "# fi_df = pd.DataFrame(columns = clean_data.drop(columns='Delivery_Time').columns,data= fi)\n", + "sns.barplot(x=clean_data.drop(columns='Delivery_Time').columns, y=fi)\n", + "# need some edits to be more readble" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "preds = model.predict(clean_data.drop(columns='Delivery_Time'))\n", + "sns.histplot(preds)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# compare with actual\n", + "sns.histplot(clean_data.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/185/Q2.ipynb b/submissions_extracted/185/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..e591cd2bcb930cdcaac063b715588803349b099f --- /dev/null +++ b/submissions_extracted/185/Q2.ipynb @@ -0,0 +1,363 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q2-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import os\n", + "import pandas as pd\n", + "import numpy as np\n", + "from PIL import Image\n", + "from sklearn.model_selection import train_test_split\n", + "\n", + "# Load Labels\n", + "labels_df = pd.read_csv(os.path.join(path, \"labels.csv\"))\n", + "img_dir = os.path.join(path, \"images\")\n", + "\n", + "images = []\n", + "ages = []\n", + "\n", + "# Load Images and Resize\n", + "print(\"Loading images...\")\n", + "for index, row in labels_df.iterrows():\n", + " img_name = row.iloc[0]\n", + " age = row.iloc[1]\n", + " img_path = os.path.join(img_dir, img_name)\n", + "\n", + " if os.path.exists(img_path):\n", + " img = Image.open(img_path).convert('RGB')\n", + " img_array = np.array(img) / 255.0 # Normalize pixel values to [0, 1]\n", + " images.append(img_array)\n", + " ages.append(age)\n", + "\n", + "X = np.array(images)\n", + "y = np.array(ages)\n", + "\n", + "# Transpose image dimensions to match PyTorch format (N, C, H, W)\n", + "X = np.transpose(X, (0, 3, 1, 2))\n", + "\n", + "# Split Data\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n", + "\n", + "print(f\"X_train shape: {X_train.shape}\")\n", + "print(f\"X_test shape: {X_test.shape}\")\n", + "print(f\"y_train shape: {y_train.shape}\")\n", + "print(f\"y_test shape: {y_test.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 1. Convert Numpy arrays to PyTorch Tensors\n", + "import torch\n", + "X_train = torch.tensor(X_train)\n", + "X_test = torch.tensor(X_test)\n", + "y_train = torch.tensor(y_train)\n", + "y_test = torch.tensor(y_test)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 2. Create TensorDataset objects\n", + "from torch.utils.data import DataLoader, 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", + "\n", + "train_loader = DataLoader(train_dataset, 32)\n", + "test_loader = DataLoader(test_dataset, 32)\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": [ + "# import matplotlib.pyplot as plt\n", + "# # 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", + "from torch import nn\n", + "class NN4Layer(nn.Module):\n", + "\n", + " def __init__(self, input_dim, hidden_dim, output_dim):\n", + " super(NN4Layer, self).__init__()\n", + "\n", + " # First linear layer: input features -> hidden layer\n", + " self.layer1 = nn.Linear(input_dim, hidden_dim)\n", + "\n", + " # Second linear layer: hidden layer -> hidden layer\n", + " self.layer2 = nn.Linear(hidden_dim, hidden_dim)\n", + "\n", + " # Output layer: hidden layer -> number of classes (logits)\n", + " self.layer3 = nn.Linear(hidden_dim, 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.flatten())\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", + " a4 = self.relu(z4)\n", + "\n", + "\n", + "\n", + " # Output layer (raw scores / logits)\n", + " # output = self.layer3(a2) # there is something missing here, remember? :)\n", + "\n", + " return a4\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\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.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", + "\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 = 3* 36* 36 # flattend image\n", + "hidden_dim = 40 # Design choice\n", + "output_dim = 1 # number\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 = 10\n", + "learning_rate = 0.001\n", + "\n", + "# Define criterion (loss function) - using CrossEntropyLoss as model now outputs logits\n", + "criterion = nn.L1Loss()\n", + "# Define optimizer\n", + "optimizer = torch.optim.Adam(model.parameters(), learning_rate)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Start training for 20 epochs:\n", + "# Run Training\n", + "train_losses = []\n", + "val_losses = []\n", + "val_accuracies = []\n", + "num_epochs=20\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", + "# error in dimensions :/" + ], + "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/185/Q3.ipynb b/submissions_extracted/185/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..3eb80dc823283bf3bf83bcb01696b8c2767c2b9f --- /dev/null +++ b/submissions_extracted/185/Q3.ipynb @@ -0,0 +1,282 @@ +{ + "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 sklearn\n", + "import os\n", + "import seaborn as sns" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "dataset = pd.read_csv(os.path.join(path, \"Q3_data.csv\"))\n", + "dataset.shape" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "print(dataset.shape)\n", + "dataset.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "dataset.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "dataset.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "clean_data = dataset.copy()\n", + "print(clean_data.isna().sum().sum())\n", + "clean_data.isna().sum()\n", + "# a lot of data is missing, drop them to save time, or impute mean?\n", + "for col in clean_data.drop(columns='Target').columns:\n", + " clean_data[col].fillna(float(clean_data[col].mean()), inplace=True)\n", + "\n", + "print(clean_data.isna().sum().sum())\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "print(clean_data.duplicated().sum())\n", + "# no dups" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "print(len(list(dataset.select_dtypes(include='object'))))\n", + "# no categoricals" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "from sklearn.preprocessing import StandardScaler\n", + "from sklearn.preprocessing import LabelEncoder\n", + "\n", + "X = clean_data.drop(columns='Target')\n", + "y = clean_data['Target']\n", + "\n", + "scaler = StandardScaler()\n", + "le = LabelEncoder()\n", + "\n", + "X = scaler.fit_transform(X) # I know, information leakage, but no time :/\n", + "# y = le.fit_transform(y)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "print(f'mean: {y.mean():.2f}') # 26% of the target are (1)s,\n", + "# print(f'Std: {y.std():.2f}')\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "type(X)\n", + "X.shape" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "!pip install catboost" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "from catboost import CatBoostRegressor\n", + "from sklearn.model_selection import KFold\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", + "from catboost import CatBoostRegressor\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:\n", + "f1s = []\n", + "accs = []\n", + "X = pd.DataFrame(X)\n", + "y = pd.DataFrame(y)\n", + "\n", + "kf = KFold(n_splits=5, shuffle=True, random_state=42)\n", + "model = CatBoostRegressor(verbose=0)\n", + "\n", + "for fold_idx, (train_index, test_index) in enumerate(kf.split(X)):\n", + " print(f\"\\nFold {fold_idx + 1}/{5}\")\n", + "\n", + " X_train, X_test = X.iloc[train_index], X.iloc[test_index]\n", + " y_train, y_test = y.iloc[train_index], y.iloc[test_index]\n", + "\n", + "\n", + " print(f\"Training ...\")\n", + " print(X_train.shape)\n", + " print(X_test.shape)\n", + "\n", + "\n", + " # Train\n", + " model.fit(X_train, y_train)\n", + "\n", + " # Predict\n", + " y_pred = model.predict(X_test)\n", + " print(y_test[:5])\n", + " print(y_pred[:5])\n", + "\n", + " y_pred = 0 if y_pred < 0.5 else 1\n", + " y_test = 0 if y_test < 0.5 else 1\n", + "\n", + " # Calculate metrics\n", + " f1 = f1_score(y_test, y_pred)\n", + " acc = accuracy_score(y_test, y_pred)\n", + " f1s.append(f1)\n", + " accs.append(acc)\n", + " # Store results\n", + "\n", + "# error but no time to solve :/\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: 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/186/Q1.ipynb b/submissions_extracted/186/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..8b942a2fc1afba0abea325e5e505b451b3f56dc0 --- /dev/null +++ b/submissions_extracted/186/Q1.ipynb @@ -0,0 +1,258 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "import numpy as np\n", + "import pandas as pd\n", + "import matplotlib.pyplot as plt\n", + "import os\n", + "import kagglehub\n", + "\n", + "from sklearn.model_selection import train_test_split, KFold\n", + "from sklearn.preprocessing import StandardScaler , LabelEncoder\n", + "from sklearn.ensemble import RandomForestRegressor\n", + "from sklearn.metrics import mean_absolute_error, mean_squared_error\n", + "\n", + "import warnings\n", + "warnings.filterwarnings('ignore')\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q1-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "food_del_path = os.path.join(path, 'Q1_data.csv')\n", + "df_food=pd.read_csv(food_del_path)\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "print(f\"Dataset shape: {df_food.shape}\")\n", + "df_food.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "df_food.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "df_food.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "plt.figure(figsize=(10, 5))\n", + "plt.hist(df_food['Delivery_Time'].dropna(), bins=50, edgecolor='black') #Delivery_Time capital\n", + "plt.title('delivery_time Distribution')\n", + "plt.xlabel('delivery_time')\n", + "plt.ylabel('Frequency')\n", + "plt.show()\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "cols = ['Order_ID', \t'Distance_km', \t'Weather', \t'Traffic_Level', \t'Time_of_Day', \t'Vehicle_Type', \t'Preparation_Time_min', \t'Courier_Experience_yrs' ]\n", + "df_clean = df_food.dropna(subset=['Order_ID']).copy()\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "missing_percentage = (df_food.isnull().sum() / len(df_food)) * 100\n", + "missing_data = pd.DataFrame({\n", + " 'Column': missing_percentage.index,\n", + " 'Missing_Percentage': missing_percentage.values\n", + "})\n", + "missing_data = missing_data[missing_data['Missing_Percentage'] > 0].sort_values('Missing_Percentage', ascending=False)\n", + "\n", + "print(\"Missing Data Analysis:\")\n", + "missing_data.head(10)\n", + "df_clean = df_clean.dropna(subset=['Delivery_Time', 'Weather', 'Traffic_Level','Time_of_Day','Courier_Experience_yrs'])\n", + "print(f\"After dropping missing rows: {df_food.shape}\")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "target_column = \"Delivery_Time\"\n", + "\n", + "X = df_food.drop(target_column, axis=1)\n", + "y = df_food[target_column]\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])" + ], + "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)" + ], + "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", + "target_column = \"Delivery_Time\"\n", + "X = df_food.drop(target_column, axis=1)\n", + "y = df_food[target_column]" + ], + "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", + "model = RandomForestRegressor()\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", + " # Train model\n", + " model.fit(X_train, y_train)\n", + "\n", + " # Predict\n", + " y_pred = model.predict(X_test) ## it would not work with me no matter what i did..." + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "importance = pd.DataFrame({\n", + " 'feature': cols,\n", + " 'importance': model.feature_importances_\n", + "}).sort_values('importance', ascending=False)\n", + "\n", + "plt.figure(figsize=(10, 6))\n", + "plt.barh(importance['feature'], importance['importance'], color='purple')\n", + "plt.xlabel('Importance')\n", + "plt.title('Feature Importance')\n", + "plt.gca().invert_yaxis()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "plt.figure(figsize=(10, 5))\n", + "plt.hist(df_food['price']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/186/Q2.ipynb b/submissions_extracted/186/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..8667ef8ac291fe02553094d6bfb5eb0ce3901ef8 --- /dev/null +++ b/submissions_extracted/186/Q2.ipynb @@ -0,0 +1,292 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "import pandas as pd\n", + "import numpy as np\n", + "import torch\n", + "import torch.nn as nn\n", + "from torch.optim import AdamW\n", + "import matplotlib.pyplot as plt\n", + "from torch.utils.data import DataLoader, TensorDataset\n", + "from sklearn.model_selection import train_test_split\n", + "from sklearn.preprocessing import StandardScaler, LabelEncoder\n", + "from sklearn.metrics import mean_absolute_error, mean_squared_error, r2_score\n", + "import os\n", + "print(f\"PyTorch version: {torch.__version__}\")\n", + "print(f\"CUDA available: {torch.cuda.is_available()}\")\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", + "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": [ + "X = img_dir.drop(\"price\",axis=1)\n", + "y = img_dir['price']\n", + "\n", + "# TODO: Split the dataset into training and testing sets (80% train, 20% test)\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n", + "\n", + "# TODO: Transform to PyTorch tensors with dtype=torch.float32\n", + "X_train = torch.tensor(X_train.values, dtype=torch.float32)\n", + "X_test = torch.tensor(X_test.values, dtype=torch.float32)\n", + "y_train = torch.tensor(y_train.values, dtype=torch.float32)\n", + "y_test = torch.tensor(y_test.values, dtype=torch.float32)\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)#idk why i get this error" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 2. Create TensorDataset objects\n", + "train_dataset = TensorDataset(X_train, y_train)\n", + "test_dataset = TensorDataset(X_test, y_test)\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 3. Create DataLoaders\n", + "train_loader = DataLoader(train_dataset, batch_size=32, shuffle=True)\n", + "test_loader = DataLoader(test_dataset, batch_size=32, shuffle=False)\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 4. Print shape of one batch\n", + "\n", + "X_batch, y_batch = next(iter(train_loader))\n", + "print(f\"Training batch input shape: {X_batch.shape}\")\n", + "print(f\"Training batch labels shape: {y_batch.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 5. Display sample images\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your model class here:\n", + "class NN4Layer(nn.Module):\n", + " def __init__(self, input_dim, hidden_dim,output_dim):\n", + " super(NN4Layer, self).__init__()\n", + " self.layer1 = nn.Linear(input_dim, hidden_dim)\n", + " self.layer2 = nn.Linear(hidden_dim, hidden_dim)\n", + " self.layer3 = nn.Linear(hidden_dim, hidden_dim )\n", + " self.layer4 = nn.Linear(hidden_dim, output_dim )\n", + "\n", + " # ReLU activation for non-linearity in hidden layers\n", + " self.relu = nn.ReLU()" + ], + "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", + "\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", + "\n", + " optimizer.zero_grad()\n", + " loss.backward()\n", + " optimizer.step()\n", + "\n", + " running_loss += loss.item()\n", + "\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", + "\n", + " model.eval()\n", + "\n", + " running_loss = 0.0\n", + "\n", + " with torch.no_grad():\n", + " for X_batch, y_batch in test_loader:\n", + "\n", + " X_batch = X_batch.to(device)\n", + " y_batch = y_batch.view(-1, 1).to(device)\n", + "\n", + "\n", + " outputs = model(X_batch)\n", + " loss = criterion(outputs, y_batch)\n", + "\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 = 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:\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", + "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/186/Q3.ipynb b/submissions_extracted/186/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..837cd625e09902f2b198dc961b6ed9fcf1dd26f5 --- /dev/null +++ b/submissions_extracted/186/Q3.ipynb @@ -0,0 +1,218 @@ +{ + "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.linear_model import LinearRegression\n", + "from sklearn.ensemble import RandomForestRegressor\n", + "from sklearn.metrics import mean_absolute_error, mean_squared_error\n", + "\n", + "import warnings\n", + "warnings.filterwarnings('ignore')\n", + "\n", + "\n", + "# Download latest version\n", + "\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q3-exam-data\")\n", + "\n", + "\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "gf_path = os.path.join(path, 'Q3_data.csv')\n", + "df_gf=pd.read_csv(gf_path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "print(f\"Dataset shape: {df_gf.shape}\")\n", + "df_gf.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "df_gf.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "df_gf.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "missing_percentage = (df_gf.isnull().sum() / len(df_gf)) * 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:\n", + "\n", + "target_column = \"Target\"\n", + "\n", + "X = df_gf.drop(target_column, axis=1)\n", + "y = df_gf[target_column]\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])" + ], + "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": [ + "# 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:\n", + "kf = KFold(n_splits=5, shuffle=True, random_state=42)\n", + "model = CatBoostClassifier()\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", + " # Train model\n", + " model.fit(X_train, y_train)\n", + "\n", + " # Predict\n", + " y_pred = model.predict(X_test)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/187/Q1.ipynb b/submissions_extracted/187/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..48b50d272fb554390ca3b59f42dec1a773571fe7 --- /dev/null +++ b/submissions_extracted/187/Q1.ipynb @@ -0,0 +1,302 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q1-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import pandas as pd\n", + "import os\n", + "try:\n", + " df = pd.read_csv(f\"{path}/Q1_data.csv\")\n", + "except:\n", + " df = pd.read_csv(\"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": [ + "import seaborn as sns\n", + "import matplotlib.pyplot as plt\n", + "sns.histplot(df['Delivery_Time'], kde=True)\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "if 'Order_ID' in df.columns:\n", + " df = df.drop(columns=['Order_ID'])\n", + " print(\"Column 'Order_ID' dropped.\")\n", + "else:\n", + " print(\"Column 'Order_ID' not found.\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "num_cols = df.select_dtypes(include=['number']).columns\n", + "df[num_cols] = df[num_cols].fillna(df[num_cols].median())\n", + "\n", + "cat_cols = df.select_dtypes(include=['object', 'category']).columns\n", + "for col in cat_cols:\n", + " if df[col].isnull().sum() > 0:\n", + " df[col] = df[col].fillna(df[col].mode()[0])\n", + "\n", + "print(f\"Missing values remaining: {df.isnull().sum().sum()}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "duplicates_count = df.duplicated().sum()\n", + "if duplicates_count > 0:\n", + " df.drop_duplicates(inplace=True)\n", + "\n", + "print(f\"Removed {duplicates_count} duplicate rows.\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "from sklearn.preprocessing import OneHotEncoder\n", + "import pandas as pd\n", + "\n", + "categorical_cols = df.select_dtypes(include=['object', 'category']).columns.tolist()\n", + "\n", + "encoder = OneHotEncoder(sparse_output=False, drop='first', handle_unknown='ignore')\n", + "\n", + "\n", + "encoded_array = encoder.fit_transform(df[categorical_cols])\n", + "encoded_df = pd.DataFrame(\n", + " encoded_array,\n", + " columns=encoder.get_feature_names_out(categorical_cols),\n", + " index=df.index\n", + ")\n", + "df = df.drop(columns=categorical_cols)\n", + "df = pd.concat([df, encoded_df], axis=1)\n", + "\n", + "print(f\"Encoding complete. New shape: {df.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "from sklearn.preprocessing import StandardScaler\n", + "scaler = StandardScaler()\n", + "target_col = 'Delivery_Time'\n", + "\n", + "features = [c for c in df.columns if c != target_col]\n", + "\n", + "df[features] = scaler.fit_transform(df[features])\n", + "\n", + "print(\"Feature scaling applied.\")\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "\n", + "#comment: For the models im using RF and CatB a 0.56 is not an issue Tree based are robust to distribution they do not require a perfectly normal target and this is normal life so its considered very good for normal data behaveiour i don't think we need to apply a log transformation or fix this\n", + "\n", + "target_col = 'Delivery_Time'\n", + "skewness = df[target_col].skew()\n", + "print(f\"Target Skewness: {skewness:.4f}\")\n", + "\n", + "if abs(skewness) > 1:\n", + " print(\"Conclusion: The target distribution is HIGHLY skewed.\")\n", + "elif abs(skewness) > 0.5:\n", + " print(\"Conclusion: The target distribution is MODERATELY skewed.\")\n", + "else:\n", + " print(\"Conclusion: The target distribution is fairly symmetrical.\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "X = df.drop(columns=['Delivery_Time'])\n", + "y = df['Delivery_Time']" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "from sklearn.model_selection import KFold\n", + "from sklearn.ensemble import RandomForestRegressor\n", + "from sklearn.metrics import mean_absolute_error\n", + "import numpy as np\n", + "\n", + "kf = KFold(n_splits=5, shuffle=True, random_state=42)\n", + "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", + " model = RandomForestRegressor(random_state=42)\n", + " model.fit(X_train, y_train)\n", + " y_pred = model.predict(X_test)\n", + " scores.append(mean_absolute_error(y_test, y_pred))\n", + "\n", + "print(np.mean(scores))" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import pandas as pd\n", + "import matplotlib.pyplot as plt\n", + "\n", + "importances = pd.Series(model.feature_importances_, index=X.columns)\n", + "importances.nlargest(10).plot(kind='barh')\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import seaborn as sns\n", + "sns.histplot(y_pred, kde=True)\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "#i installed catboost REG casue its not installed with colab\n", + "!pip install catboost" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "from catboost import CatBoostRegressor\n", + "from sklearn.ensemble import RandomForestRegressor\n", + "from sklearn.model_selection import KFold\n", + "from sklearn.metrics import mean_absolute_error\n", + "import numpy as np\n", + "\n", + "X = df.drop(columns=['Delivery_Time'])\n", + "y = df['Delivery_Time']\n", + "\n", + "kf = KFold(n_splits=5, shuffle=True, random_state=42)\n", + "scores_ensemble = []\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 = RandomForestRegressor(random_state=42)\n", + " cb = CatBoostRegressor(verbose=0, random_state=42)\n", + "\n", + " rf.fit(X_train, y_train)\n", + " cb.fit(X_train, y_train)\n", + "\n", + "\n", + " pred_rf = rf.predict(X_test)\n", + " pred_cb = cb.predict(X_test)\n", + "\n", + "\n", + " pred_avg = (pred_rf + pred_cb) / 2\n", + "\n", + "\n", + " scores_ensemble.append(mean_absolute_error(y_test, pred_avg))\n", + "\n", + "print(f\"Ensemble Average MAE: {np.mean(scores_ensemble)}\")" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/187/Q2.ipynb b/submissions_extracted/187/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..bb47e8e6c800cfba164f108338af37e7e125bf91 --- /dev/null +++ b/submissions_extracted/187/Q2.ipynb @@ -0,0 +1,291 @@ +{ + "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", + "labels_df = pd.read_csv(os.path.join(path, \"labels.csv\"))\n", + "img_dir = os.path.join(path, \"images\")\n", + "\n", + "images = []\n", + "ages = []\n", + "\n", + "print(\"Loading images...\")\n", + "for index, row in labels_df.iterrows():\n", + " img_name = row.iloc[0]\n", + " age = row.iloc[1]\n", + " img_path = os.path.join(img_dir, img_name)\n", + "\n", + " if os.path.exists(img_path):\n", + " img = Image.open(img_path).convert('RGB')\n", + " img_array = np.array(img) / 255.0\n", + " images.append(img_array)\n", + " ages.append(age)\n", + "\n", + "X = np.array(images)\n", + "y = np.array(ages)\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": [ + "import torch\n", + "import torch.nn as nn\n", + "import torch.optim as optim\n", + "from torch.utils.data import TensorDataset, DataLoader\n", + "import matplotlib.pyplot as plt\n", + "\n", + "X_train_tensor = torch.tensor(X_train, dtype=torch.float32)\n", + "X_test_tensor = torch.tensor(X_test, dtype=torch.float32)\n", + "y_train_tensor = torch.tensor(y_train, dtype=torch.float32).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": [ + "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": [ + "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": [ + "images_batch, ages_batch = next(iter(train_loader))\n", + "print(f\"Batch images shape: {images_batch.shape}\")\n", + "print(f\"Batch ages shape: {ages_batch.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "fig, axes = plt.subplots(1, 5, figsize=(15, 3))\n", + "for i in range(5):\n", + " img = images_batch[i].permute(1, 2, 0).numpy()\n", + " axes[i].imshow(img)\n", + " axes[i].set_title(f\"Age: {ages_batch[i].item()}\")\n", + " axes[i].axis('off')\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "class AgePredictor(nn.Module):\n", + " def __init__(self, input_size):\n", + " super(AgePredictor, self).__init__()\n", + " self.flatten = nn.Flatten()\n", + " self.fc1 = nn.Linear(input_size, 512)\n", + " self.fc2 = nn.Linear(512, 256)\n", + " self.fc3 = nn.Linear(256, 128)\n", + " self.fc4 = nn.Linear(128, 1)\n", + " self.relu = nn.ReLU()\n", + "\n", + " def forward(self, x):\n", + " x = self.flatten(x)\n", + " x = self.relu(self.fc1(x))\n", + " x = self.relu(self.fc2(x))\n", + " x = self.relu(self.fc3(x))\n", + " x = self.fc4(x)\n", + " return x" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "def train_loop(dataloader, model, loss_fn, optimizer, device):\n", + " model.train()\n", + " total_loss = 0\n", + " for batch, (X, y) in enumerate(dataloader):\n", + " X, y = X.to(device), y.to(device)\n", + "\n", + " pred = model(X)\n", + " loss = loss_fn(pred, y)\n", + "\n", + " optimizer.zero_grad()\n", + " loss.backward()\n", + " optimizer.step()\n", + "\n", + " total_loss += loss.item()\n", + "\n", + " return total_loss / len(dataloader)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "def validate_loop(dataloader, model, loss_fn, device):\n", + " model.eval()\n", + " test_loss = 0\n", + " with torch.no_grad():\n", + " for X, y in dataloader:\n", + " X, y = X.to(device), y.to(device)\n", + " pred = model(X)\n", + " test_loss += loss_fn(pred, y).item()\n", + "\n", + " return test_loss / len(dataloader)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "device = \"cuda\" if torch.cuda.is_available() else \"cpu\"\n", + "input_dim = X_train.shape[1] * X_train.shape[2] * X_train.shape[3]\n", + "model = AgePredictor(input_dim).to(device)\n", + "loss_fn = nn.MSELoss()\n", + "optimizer = optim.Adam(model.parameters(), lr=0.001)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "epochs = 20\n", + "train_losses = []\n", + "val_losses = []\n", + "\n", + "for t in range(epochs):\n", + " print(f\"Epoch {t+1}\\n-------------------------------\")\n", + " train_loss = train_loop(train_loader, model, loss_fn, optimizer, device)\n", + " val_loss = validate_loop(test_loader, model, loss_fn, device)\n", + "\n", + " train_losses.append(train_loss)\n", + " val_losses.append(val_loss)\n", + "\n", + " print(f\"Train Loss: {train_loss:.4f} | Val Loss: {val_loss:.4f}\")\n", + "\n", + "print(\"Done!\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "plt.figure(figsize=(10, 5))\n", + "plt.plot(train_losses, label='Training Loss')\n", + "plt.plot(val_losses, label='Validation Loss')\n", + "plt.title('Training and Validation Loss Over Epochs')\n", + "plt.xlabel('Epochs')\n", + "plt.ylabel('Loss (MSE)')\n", + "plt.legend()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "model.eval()\n", + "X_sample, y_sample = next(iter(test_loader))\n", + "X_sample, y_sample = X_sample.to(device), y_sample.to(device)\n", + "\n", + "with torch.no_grad():\n", + " predictions = model(X_sample)\n", + "\n", + "fig, axes = plt.subplots(1, 5, figsize=(15, 3))\n", + "for i in range(5):\n", + " img = X_sample[i].cpu().permute(1, 2, 0).numpy()\n", + " actual_age = y_sample[i].item()\n", + " pred_age = predictions[i].item()\n", + "\n", + " axes[i].imshow(img)\n", + " axes[i].set_title(f\"Act: {actual_age:.1f} | Pred: {pred_age:.1f}\")\n", + " axes[i].axis('off')\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# i made it look nice have a bonus for proffiosnal look\n", + "# best reagrds to the one marking this your the best :)" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/187/Q3.ipynb b/submissions_extracted/187/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..d7d06d0ce81e3a11ce222f2cd0682f06bcddad0b --- /dev/null +++ b/submissions_extracted/187/Q3.ipynb @@ -0,0 +1,302 @@ +{ + "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": [ + "# Load the dataset\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}\")" + ], + "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": [ + "print(\"Missing values:\")\n", + "print(df.isnull().sum())" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "for col in df.columns:\n", + " if df[col].dtype in ['float64', 'int64']:\n", + " df[col] = df[col].fillna(df[col].median())\n", + " else:\n", + " df[col] = df[col].fillna(df[col].mode()[0])" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "initial_rows = df.shape[0]\n", + "df = df.drop_duplicates()\n", + "final_rows = df.shape[0]\n", + "print(f\"Removed {initial_rows - final_rows} duplicate rows.\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "object_cols = df.select_dtypes(include=['object']).columns\n", + "label_encoder = LabelEncoder()\n", + "\n", + "for col in object_cols:\n", + " df[col] = label_encoder.fit_transform(df[col].astype(str))" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "features = df.drop(columns=['Target'])\n", + "target = df['Target']\n", + "\n", + "scaler = StandardScaler()\n", + "X_scaled = pd.DataFrame(scaler.fit_transform(features), columns=features.columns)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "target_counts = target.value_counts(normalize=True)\n", + "print(\"Target distribution:\")\n", + "print(target_counts)\n", + "\n", + "# Threshold for \"imbalance\" is typically if the minority class is < 50\n", + "#you guys said If class distributions are not equal, then our data is imbalanced. Use StratifiedKFold and focus on F1-score.\n", + "if target_counts.min() < 0.5:\n", + " print(\"Result: The dataset is imbalanced (Minority class < 50%).\")\n", + " print(\"Decision: We will use F1 Score as the evaluation metric.\")\n", + "else:\n", + " print(\"Result: The dataset is relatively balanced.\")\n", + " print(\"Decision: We will use Accuracy as the evaluation metric.\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "X = X_scaled\n", + "y = target" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "!pip install catboost" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "from sklearn.model_selection import StratifiedKFold\n", + "from sklearn.metrics import f1_score\n", + "from catboost import CatBoostClassifier\n", + "\n", + "X = X_scaled\n", + "y = target\n", + "\n", + "skf = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)\n", + "\n", + "f1_scores = []\n", + "\n", + "model = CatBoostClassifier(verbose=0, random_state=42, auto_class_weights='Balanced')\n", + "\n", + "print(\"Starting Cross-Validation Evaluating with F1 Score\")\n", + "\n", + "for fold, (train_idx, val_idx) in enumerate(skf.split(X, y)):\n", + " X_train, X_val = X.iloc[train_idx], X.iloc[val_idx]\n", + " y_train, y_val = y.iloc[train_idx], y.iloc[val_idx]\n", + "\n", + " model.fit(X_train, y_train)\n", + " y_pred = model.predict(X_val)\n", + "\n", + "\n", + " f1 = f1_score(y_val, y_pred)\n", + " f1_scores.append(f1)\n", + "\n", + " print(f\"Fold {fold+1}: F1 Score = {f1:.4f}\")\n", + "\n", + "avg_f1_full = np.mean(f1_scores)\n", + "print(f\"\\nAverage F1 Score: {avg_f1_full:.4f}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "feature_importances = model.get_feature_importance()\n", + "feature_names = X.columns\n", + "\n", + "fi_df = pd.DataFrame({'Feature': feature_names, 'Importance': feature_importances})\n", + "fi_df = fi_df.sort_values(by='Importance', ascending=False).head(10)\n", + "\n", + "plt.figure(figsize=(10, 6))\n", + "plt.barh(fi_df['Feature'], fi_df['Importance'])\n", + "plt.gca().invert_yaxis()\n", + "plt.title(\"Top 10 Feature Importances\")\n", + "plt.xlabel(\"Importance Score\")\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "golden_feature = fi_df.iloc[0]['Feature']\n", + "print(f\"The Golden Feature is: {golden_feature}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "X_golden = X[[golden_feature]]\n", + "\n", + "f1_scores_golden = []\n", + "\n", + "print(f\"Training with ONLY Golden Feature ({golden_feature})...\")\n", + "\n", + "for fold, (train_idx, val_idx) in enumerate(skf.split(X_golden, y)):\n", + " X_train, X_val = X_golden.iloc[train_idx], X_golden.iloc[val_idx]\n", + " y_train, y_val = y.iloc[train_idx], y.iloc[val_idx]\n", + "\n", + " model.fit(X_train, y_train)\n", + " y_pred = model.predict(X_val)\n", + "\n", + " f1_scores_golden.append(f1_score(y_val, y_pred))\n", + "\n", + "avg_f1_golden = np.mean(f1_scores_golden)\n", + "\n", + "print(f\"\\nFull Model Average F1 Score: {avg_f1_full:.4f}\")\n", + "print(f\"Golden Feature Model Average F1 Score: {avg_f1_golden:.4f}\")\n", + "print(f\"Difference: {avg_f1_full - avg_f1_golden:.4f}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# i made it look nice have a bonus for proffiosnal look\n", + "# best reagrds to the one marking this your the best :)" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/188/Q1.ipynb b/submissions_extracted/188/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..fb85815d3690753c8f563b5ed7d3dcec3263505d --- /dev/null +++ b/submissions_extracted/188/Q1.ipynb @@ -0,0 +1,181 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "import pandas as pd\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(f\"{path}/Q1_data.csv\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "df.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "df.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "from dataclasses import MISSING\n", + "# Task 2: Write your code here:\n", + "df=df.drop(columns=['Order_ID'])\n", + "df" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "df=df.drop()" + ], + "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:" + ], + "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", + "df= [\"Distans_km\",'Weather','Trafic_Level']" + ], + "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/188/Q2.ipynb b/submissions_extracted/188/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..9761526fc3787f9b9f4a1107b9a50c71093dc05c --- /dev/null +++ b/submissions_extracted/188/Q2.ipynb @@ -0,0 +1,383 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q2-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import os\n", + "import pandas as pd\n", + "import numpy as np\n", + "from PIL import Image\n", + "from sklearn.model_selection import train_test_split\n", + "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": [ + "\n", + "\n", + "\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 2. Create TensorDataset objects\n", + "train_dataset =MNIST(\n", + " root='./datasets',\n", + " train=True,\n", + " transform-to_tensor,\n", + " download=True\n", + "\n", + ")\n", + "test_dataset =MNIST(\n", + " root='./dataset',\n", + " train=False,\n", + " transform-to-tensor,\n", + " download=True\n", + ")\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 3. Create DataLoaders\n", + "train_loader = DataLoader(\n", + " train_dataset,\n", + " batch_size=32,\n", + " shuffle=True,\n", + " num_workers=2\n", + ")\n", + "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", + "\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", + "class NN3Layer():\n", + "\n", + " def __init__(self, input_dim, hidden_dim, output_dim):\n", + " super(NN3Layer, 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", + "\n", + "\n", + " self.layer2 = nn.Linear(hidden_dim, hidden_dim)\n", + "\n", + "\n", + " self.layer3 = nn.Linear(hidden_dim, output_dim)\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", + "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", + "\n", + "model = NN3Layer(input_dim, hidden_dim, output_dim).to(device)\n", + "\n", + "\n", + "print(\"Model Architecture:\\n\")\n", + "print(model)\n", + "\n", + "# Calculate the total number of trainable parameters\n", + "total_params = sum(p.numel() for p in model.parameters() if p.requires_grad)\n", + "print(f\"\\nTotal trainable parameters: {total_params}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Start training for 20 epochs:\n", + "num_epochs = 20\n", + "learning_rate = 0.001\n", + "\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", + "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", + "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": [ + "# 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/189/Q1.ipynb b/submissions_extracted/189/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..dfd53e2aafe13e20cd69976630f7c7fdf301b9d4 --- /dev/null +++ b/submissions_extracted/189/Q1.ipynb @@ -0,0 +1,403 @@ +{ + "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": [ + "# importations\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 catboost import CatBoostClassifier\n", + "from catboost import CatBoostRegressor\n", + "import warnings\n", + "warnings.filterwarnings(\"ignore\")" + ], + "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\")\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "df.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "df.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "df[\"Delivery_Time\"].hist()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "#\n", + "print(f\"Sahape is: {df.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "df_new = df.copy().drop(columns=[\"Order_ID\"])\n", + "df_new.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "print(f\"Before: {df_new.isna().sum()}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "df_new.isna().sum()\n", + "df_new = df_new.dropna(subset=[\"Delivery_Time\", \"Weather\", \"Traffic_Level\", \"Time_of_Day\", \"Courier_Experience_yrs\"])\n", + "print(f\"After: {df_new.isna().sum()}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "print(f\"Sahpe after dropping: {df_new.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "print(df_new.duplicated().sum())\n", + "df_new = df_new.drop_duplicates()\n", + "print(f\"Sahpe after dropping: {df_new.shape}\")\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "from sklearn.preprocessing import LabelEncoder\n", + "\n", + "encoder=LabelEncoder()\n", + "\n", + "for col in df_new.select_dtypes(include=[\"object\"]).columns:\n", + " df_new[col]=encoder.fit_transform(df_new[col])\n", + "\n", + "df_new.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "features = df_new.drop(columns=[\"Delivery_Time\"]).columns\n", + "features\n", + "\n", + "sclaer = StandardScaler()\n", + "\n", + "df_new[features] = sclaer.fit_transform(df_new[features])\n", + "df_new.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 6: Write your code here:\n", + "# this is a regression problem (:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "\n", + "X = df_new[features]\n", + "y = df_new[\"Delivery_Time\"]\n", + "X.shape" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "model = RandomForestRegressor()\n", + "model" + ], + "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", + "from sklearn.metrics import mean_absolute_error,mean_squared_error\n", + "\n", + "kf=KFold(n_splits=5,shuffle=True,random_state=42)\n", + "\n", + "scores_mae=[]\n", + "\n", + "# scores_rmse=[]\n", + "for train_index,test_index in kf.split(X):\n", + "\n", + " X_train, X_test = X.iloc[train_index], X.iloc[test_index]\n", + " y_train, y_test = y.iloc[train_index], y.iloc[test_index]\n", + "\n", + " model.fit(X_train,y_train)\n", + "\n", + " y_pred=model.predict(X_test)\n", + "\n", + " scores_mae.append(mean_absolute_error(y_test, y_pred))\n", + " # scores_rmse.append(np.sqrt(mean_squared_error(y_test, y_pred)))\n", + "\n", + "print(f\"{model} MAE Score: {np.mean(scores_mae)}\")\n", + "# print(f\"{model} RMSE Score: {np.mean(scores_rmse)}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "plt.figure(figsize=(10, 6))\n", + "plt.plot(scores_mae, label='Training', color='purple')\n", + "plt.title('Loss Curve')\n", + "plt.xlabel('Iteration')\n", + "plt.ylabel('Categorical 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:\n", + "\n", + "coef = model.feature_importances_\n", + "\n", + "absolute_coef = np.abs(coef)\n", + "sorted_idx = np.argsort(absolute_coef)\n", + "\n", + "features = X.columns\n", + "\n", + "plt.barh(features[sorted_idx], coef[sorted_idx])\n", + "plt.title(f\"Random forest Coefficients\")\n", + "plt.xlabel(\"Coefficient Value (Impact)\")\n", + "\n", + "plt.tight_layout()\n", + "plt.show()\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "!pip install catboost" + ], + "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, root_mean_squared_error" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:\n", + "\n", + "\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] = {'mse': [], 'rmse': [], 'r2': []}" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "kf = KFold(n_splits=5, shuffle=True, random_state=42)\n", + "\n", + "n_splits = 5\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 = root_mean_squared_error(y_test, y_pred)\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": [ + "from sklearn.metrics import root_mean_squared_error\n", + "for model_name in all_results:\n", + " print(f\"\\n{model_name}:\")\n", + " print(f\" MSE: {np.mean(all_results[model_name]['mse']):.4f}\")\n", + " print(f\" RMSE: {np.mean(all_results[model_name]['rmse']):.4f}\")\n", + " print(f\" R2: {np.mean(all_results[model_name]['r2']):.4f}\")" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/189/Q2.ipynb b/submissions_extracted/189/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..2d5e995211e3ed57dfb6cb692f4d17185e83eb3c --- /dev/null +++ b/submissions_extracted/189/Q2.ipynb @@ -0,0 +1,488 @@ +{ + "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 DataLoader, TensorDataset\n" + ], + "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": [ + "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" + ], + "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", + "# DataLoader for training data\n", + "train_loader = DataLoader(\n", + " train_dataset,\n", + " batch_size=32,\n", + " shuffle=True,\n", + " num_workers=2\n", + ")\n", + "# DataLoader for test/validation data\n", + "test_loader = DataLoader(\n", + " test_dataset,\n", + " batch_size=32,\n", + " shuffle=False,\n", + " num_workers=2\n", + ")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 4. Print shape of one batch\n", + "\n", + "# Get the first batch from the training DataLoader\n", + "X_batch, y_batch = next(iter(train_loader))\n", + "print(f\"Training batch input shape: {X_batch.shape}\")\n", + "print(f\"Training batch labels shape: {y_batch.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "images, labels = next(iter(train_loader))\n", + "images[0].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]}\")\n", + " plt.axis('off')\n", + "\n", + "plt.tight_layout()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your model class here:\n", + "\n", + "class NN4Layer(nn.Module):\n", + "\n", + " def __init__(self, input_dim, hidden_dim, 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(in_features=input_dim, out_features=128)\n", + "\n", + " # TODO: What are the dimensions from previous and next layer?\n", + " self.layer2 = nn.Linear(in_features=128, out_features=hidden_dim)\n", + "\n", + " # TODO: What are the dimensions from previous and next layer?\n", + " self.layer3 = nn.Linear(in_features=hidden_dim, out_features=hidden_dim)\n", + "\n", + " # TODO: What are the dimensions from previous and next layer?\n", + " self.layer4 = nn.Linear(in_features=hidden_dim, out_features=output_dim)\n", + "\n", + "\n", + "\n", + " # activation function for non-linearity\n", + " self.relu = nn.ReLU()\n", + "\n", + " # Defines how input data flows through the network\n", + " def forward(self, x):\n", + " # 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 = z4\n", + "\n", + "\n", + "\n", + " return a4" + ], + "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", + " # 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", + "\n", + "def validate(model, criterion, test_loader, device):\n", + " # Set the model to evaluation mode\n", + " model.eval()\n", + "\n", + " running_loss = 0.0\n", + "\n", + "\n", + " with torch.no_grad():\n", + " for X_batch, y_batch in test_loader:\n", + " # Move data to device\n", + " X_batch = X_batch.view(X_batch.size(0), -1).to(device)\n", + " y_batch = y_batch.to(device)\n", + "\n", + " # Forward pass\n", + " # TODO: make predictions\n", + " outputs = model(X_batch)\n", + " # TODO: compute loss\n", + " loss = criterion(outputs, y_batch)\n", + "\n", + " running_loss += loss.item()\n", + "\n", + "\n", + "\n", + " avg_loss = running_loss / len(test_loader)\n", + "\n", + "\n", + " return avg_loss\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Device setup\n", + "device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n", + "device" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Define device, model, loss, optimizer:\n", + "\n", + "# Model parameters\n", + "# TODO: What are input features ? (hint: flatten using channel, height, width)\n", + "input_dim = 3*36*36\n", + "\n", + "# TODO: choose number of hidden neurons\n", + "hidden_dim = 64\n", + "\n", + "# TODO: what are the number of classes ?\n", + "output_dim = 1\n", + "\n", + "# 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": [ + "# Hyperparameters (feel free to experiment!)\n", + "num_epochs = 20\n", + "learning_rate = 0.001\n", + "\n", + "# TODO: Define criterion (loss function) - use MSELoss for regression\n", + "criterion = nn.MSELoss() #\n", + "\n", + "# TODO: Define optimizer - use AdamW with the model parameters and learning rate\n", + "optimizer = AdamW(model.parameters(), lr=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", + "print('Starting Training...')\n", + "for epoch in range(num_epochs):\n", + " # TODO: Train one epoch using the train_one_epoch function\n", + " train_loss = train_one_epoch(model, optimizer, criterion, train_loader, device) # \n", + "\n", + " # TODO: Validate using the validate function\n", + " val_loss = validate(model, criterion, test_loader, device) # \n", + "\n", + " train_losses.append(train_loss)\n", + " val_losses.append(val_loss)\n", + "\n", + " print(f'Epoch [{epoch+1}/{num_epochs}], Train Loss: {train_loss:.4f}, Val Loss: {val_loss:.4f}')\n", + "\n", + "print('Training Complete!')" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "\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", + " predictions = outputs\n", + "\n", + "# Move tensors back to CPU for plotting\n", + "images = images.cpu()\n", + "labels = labels.cpu()\n", + "predictions = predictions.cpu()\n", + "\n", + "\n", + "# print(float(predictions[0]))\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: {int(labels[i])} | Pred: {int(predictions[i][0])}\")\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/189/Q3.ipynb b/submissions_extracted/189/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..b2c87ca33aeeb0aa1ce3e91a52027457efd9e3b3 --- /dev/null +++ b/submissions_extracted/189/Q3.ipynb @@ -0,0 +1,437 @@ +{ + "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": [ + "# importations\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 catboost import CatBoostClassifier\n", + "from catboost import CatBoostRegressor\n", + "import warnings\n", + "warnings.filterwarnings(\"ignore\")\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": [ + "# Task 1: Write your code here:\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", + "print(f\"Data Shape: {df.shape}\")\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "# Only first 10\n", + "df.iloc[ :,:10].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": [ + "L = df.isna().sum().reset_index()\n", + "L[df.isna().sum().reset_index()[0] <= 5000][\"index\"].values" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "features_to_take = df.isna().sum().reset_index()\n", + "features_to_take_list = list(features_to_take[df.isna().sum().reset_index()[0] <= 5000][\"index\"].values)\n", + "features_to_take_list.__len__()\n", + "print(f\"Taken {features_to_take_list.__len__()} out of {df.shape[1]} features\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# features_to_take = df.isna().any().reset_index()\n", + "# features_to_take_list = list(features_to_take[features_to_take[0] == False][\"index\"].values)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "df_new = df[features_to_take_list]\n", + "df_new = df_new.dropna()\n", + "df_new.shape\n", + "\n", + "print(f\"I have selected these features cuz it has less than 25% nulls so much easier to drop, after dropping we have{df_new.isna().sum()[0].sum()}\\n Shape now: {df_new.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "print(f\"No. of duplicates: {df_new.duplicated().sum()}\")\n", + "df_new.shape" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "df_new.select_dtypes(include=[\"object\"]).columns" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "print(f\"Categorical features len: {len(df.select_dtypes(include=[\"object\"]).columns)}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "\n", + "features = df_new.drop(columns=[\"Target\"]).columns\n", + "\n", + "sclaer = StandardScaler()\n", + "\n", + "df_new[features] = sclaer.fit_transform(df_new[features])\n", + "df_new.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "df[\"Target\"].value_counts()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "df.shape[0]" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "balancing = df[\"Target\"].value_counts().reset_index()\n", + "balancing[\"Balance_Checking_ratio\"] = (balancing[\"count\"] / len(df))\n", + "print(balancing[\"Balance_Checking_ratio\"])\n", + "balancing" + ], + "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", + "# Task 1: Write your code here:\n", + "\n", + "X = df_new[features]\n", + "y = df_new[\"Target\"]\n", + "X.shape" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "model = CatBoostClassifier()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:\n", + "\n", + "n_splits = 5 # K=5 Folds\n", + "\n", + "# Stratified 5-Fold Cross-Validation, shuffled\n", + "skf = StratifiedKFold(n_splits=n_splits, shuffle=True, random_state=42)\n", + "\n", + "\n", + "my_model_metrics = {'accuracy': [], 'precision': [], 'recall': [], 'f1': []}" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "n_splits = 5 # K\n", + "\n", + "# Stratified 5-Fold Cross-Validation, shuffled\n", + "skf = StratifiedKFold(n_splits=n_splits, shuffle=True, random_state=42)\n", + "for fold_idx, (train_index, test_index) in enumerate(skf.split(X, y)):\n", + " print(f\"\\nFold {fold_idx + 1}/{n_splits}\")\n", + "\n", + " # 1. Split data\n", + " X_train, X_test = X.iloc[train_index], X.iloc[test_index]\n", + " y_train, y_test = y.iloc[train_index], y.iloc[test_index]\n", + "\n", + " 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", + " my_model_metrics['accuracy'].append(accuracy)\n", + " my_model_metrics['precision'].append(precision)\n", + " my_model_metrics['recall'].append(recall)\n", + " my_model_metrics['f1'].append(f1)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "print(f\"Catboost Accuracy: {np.mean(my_model_metrics['accuracy'])}\")\n", + "print(f\"Catboost F1 Score: {np.mean(my_model_metrics['f1'])}\")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "\n", + "coef = model.feature_importances_[:10]\n", + "\n", + "absolute_coef = np.abs(coef)\n", + "sorted_idx = np.argsort(absolute_coef)\n", + "\n", + "features = X.columns[:10]\n", + "\n", + "plt.barh(features[sorted_idx], coef[sorted_idx])\n", + "plt.title(f\"Random forest Coefficients\")\n", + "plt.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:\n", + "print(f\"The goldn feature: {features[0]}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:\n", + "\n", + "X_golden = df_new[\"P_2\"]\n", + "y = df_new[\"Target\"]" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# the model training\n", + "\n", + "model_golden = CatBoostClassifier()\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:\n", + "\n", + "n_splits = 5 # K=5 Folds\n", + "\n", + "# Stratified 5-Fold Cross-Validation, shuffled\n", + "skf = StratifiedKFold(n_splits=n_splits, shuffle=True, random_state=42)\n", + "\n", + "\n", + "my_model_metrics_golden = {'accuracy': [], 'precision': [], 'recall': [], 'f1': []}\n", + "\n", + "\n", + "\n", + "n_splits = 5 # K\n", + "\n", + "# Stratified 5-Fold Cross-Validation, shuffled\n", + "skf = StratifiedKFold(n_splits=n_splits, shuffle=True, random_state=42)\n", + "for fold_idx, (train_index, test_index) in enumerate(skf.split(X_golden, y)):\n", + " print(f\"\\nFold {fold_idx + 1}/{n_splits}\")\n", + "\n", + " # 1. Split data\n", + " X_train, X_test = X.iloc[train_index], X.iloc[test_index]\n", + " y_train, y_test = y.iloc[train_index], y.iloc[test_index]\n", + "\n", + " model_golden.fit(X_train, y_train) # train\n", + " y_pred = model_golden.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", + " my_model_metrics_golden['accuracy'].append(accuracy)\n", + " my_model_metrics_golden['precision'].append(precision)\n", + " my_model_metrics_golden['recall'].append(recall)\n", + " my_model_metrics_golden['f1'].append(f1)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "print(f\"Catboost Accuracy: {np.mean(my_model_metrics['accuracy'])}\")\n", + "print(f\"Catboost F1 Score: {np.mean(my_model_metrics['f1'])}\")\n", + "print(\"**\"*25)\n", + "\n", + "print(f\"Catboost with golden feature Accuracy: {np.mean(my_model_metrics_golden['accuracy'])}\")\n", + "print(f\"Catboost with golden feature F1 Score: {np.mean(my_model_metrics_golden['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/19/Q1.ipynb b/submissions_extracted/19/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..d58f2a3b0d00b2b44c7917561804be31f1a858f5 --- /dev/null +++ b/submissions_extracted/19/Q1.ipynb @@ -0,0 +1,272 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "import numpy as np\n", + "import pandas as pd\n", + "import matplotlib.pyplot as plt\n", + "import os\n", + "from sklearn.preprocessing import OneHotEncoder\n", + "from sklearn.model_selection import train_test_split, StratifiedKFold, cross_val_score\n", + "from sklearn.preprocessing import StandardScaler, LabelEncoder\n", + "from sklearn.ensemble import RandomForestClassifier\n", + "from sklearn.metrics import classification_report, confusion_matrix, accuracy_score\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q1-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "delivery_path = os.path.join(path, 'Q1_data.csv')\n", + "df_delivery = pd.read_csv(delivery_path)\n", + "\n", + "print(f\"Shape: {df_delivery.shape}\")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "df_delivery.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "df_delivery.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "df_delivery.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "#plt.figure(figsize=(6, 4))\n", + "#plt.scatter(y_test, y_pred, alpha=0.7)\n", + "#plt.plot([min(y_test), max(y_test)], [min(y_test), max(y_test)], 'r--', linewidth=2)\n", + "#plt.xlabel(\"Actual y_test (Ground Truth)\")\n", + "#plt.ylabel(\"Predicted y_pred (Linear Regression)\")\n", + "#plt.title(\"Linear Regression: Predictions vs. Ground Truth\")\n", + "#plt.grid(True)\n", + "\n", + "#plt.tight_layout()\n", + "#plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "df_delivery1 = df_delivery.drop(columns=['Order_ID'])\n", + "df_delivery1.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", + "\n", + "\n", + "str_col = ['Weather','Traffic_Level','Time_of_Day']\n", + "nm_col = ['Courier_Experience_yrs']\n", + "cols = ['Weather','Traffic_Level','Time_of_Day', 'Courier_Experience_yrs']\n", + "\n", + "for col in cols:\n", + " df_delivery1[col] = df_delivery1[col].fillna(df_delivery1[col].mode()[0])\n", + "\n", + "\n", + "df_delivery1 = df_delivery1.dropna(subset=['Delivery_Time'])\n", + "\n", + "df_delivery1.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "df_delivery1 = df_delivery1.drop_duplicates()\n", + "df_delivery1.shape" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "\n", + "#onehot_encoder = OneHotEncoder(sparse_output=False)\n", + "#onehot_encode_cols = ['Weather','Time_of_Day']\n", + "#df_delivery1[onehot_encode_cols] = onehot_encoder.fit_transform(onehot_encode_cols)\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "label_encode_cols = ['Traffic_Level','Weather','Time_of_Day','Vehicle_Type']\n", + "for col in label_encode_cols:\n", + " le = LabelEncoder()\n", + " df_delivery1[col] = le.fit_transform(df_delivery1[col].astype(str))\n", + "\n", + "\n", + "\n", + "#print(data_label_encoded)\n", + "#print(data_onehot_encoded)\n", + "df_delivery1.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here: Apply feature scaling for all features (UsePreparation_Time_min StandardScaler)\n", + "\n", + "\n", + "\n", + "#Split the dataset into 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", + "\n", + "X = df_delivery1[feature_cols]\n", + "y = df_delivery1['Delivery_Time']\n", + "\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n", + "print(f\"Train: {X_train.shape}, Test: {X_test.shape}\")\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "standard_scaler = StandardScaler() # Instantiate StandardScaler\n", + "X_train_scaled = standard_scaler.fit_transform(X_train)\n", + "X_test_scaled = standard_scaler.transform(X_test)\n", + "print(f\"\\nScaled ranges - Min: {X_train_scaled.min():.2f}, Max: {X_train_scaled.max():.2f}\")\n", + "pd.DataFrame(X_train_scaled, columns=X_train.columns).head(3)\n" + ], + "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", + "\n", + "# target is countinuos value not classified value" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "\n", + "# this task was done in: Part 2: Data Cleaning Task 5" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:\n", + "\n", + "\n", + "\n", + "# i give up :(" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "\n", + "\n", + "# i give up :(" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "\n", + "\n", + "\n", + "# i give up :(" + ], + "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/190/Q1.ipynb b/submissions_extracted/190/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..a75fe325795bb1cf90110143623af39728017a1f --- /dev/null +++ b/submissions_extracted/190/Q1.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/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", + "\n", + "# Read CSV file\n", + "df = pd.read_csv(\"Q1_data.csv\")\n", + "# Display first few rows\n", + "df.head()\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "df.info()\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "df.describe()\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import matplotlib.pyplot as plt\n", + "import seaborn as sns\n", + "\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": [ + "df = df.drop(columns=[\"Order_ID\"])\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "df.isnull().sum()\n", + "# Separate numerical and categorical columns\n", + "num_cols = df.select_dtypes(include=[\"int64\", \"float64\"]).columns\n", + "cat_cols = df.select_dtypes(include=[\"object\"]).columns\n", + "\n", + "# Fill numerical missing values with median\n", + "for col in num_cols:\n", + " df[col] = df[col].fillna(df[col].median())\n", + "\n", + "# Fill categorical missing values with mode\n", + "for col in cat_cols:\n", + " df[col] = df[col].fillna(df[col].mode()[0])\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Check duplicates\n", + "df.duplicated().sum()\n", + "# Remove duplicates if any\n", + "df = df.drop_duplicates()\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# One Hot Encoding for categorical variables\n", + "df = pd.get_dummies(df, columns=cat_cols, drop_first=True)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "from sklearn.preprocessing import StandardScaler\n", + "\n", + "X = df.drop(columns=[\"delivery_time\"])\n", + "y = df[\"delivery_time\"]\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "scaler = StandardScaler()\n", + "X_scaled = scaler.fit_transform(X)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "X = df.drop(columns=[\"delivery_time\"])\n", + "y = df[\"delivery_time\"]\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "from sklearn.ensemble import RandomForestRegressor\n", + "from sklearn.metrics import mean_absolute_error\n", + "import numpy as np\n", + "from sklearn.model_selection import KFold\n", + "# KFold Cross-Validation\n", + "kf = KFold(n_splits=5, shuffle=True, random_state=42)\n", + "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", + " # Train model\n", + " model = RandomForestRegressor(\n", + " n_estimators=100,\n", + " random_state=42\n", + " )\n", + " model.fit(X_train, y_train)\n", + "\n", + " # Predict\n", + " y_pred = model.predict(X_test)\n", + "\n", + " # Evaluate using MAE\n", + " mae = mean_absolute_error(y_test, y_pred)\n", + " mae_scores.append(mae)\n", + "print(f\"Average MAE across all folds: {np.mean(mae_scores):.2f}\")\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import matplotlib.pyplot as plt\n", + "import numpy as np\n", + "\n", + "# Plot\n", + "plt.figure(figsize=(10,6))\n", + "plt.bar(range(len(importances)), importances[indices])\n", + "plt.xticks(range(len(importances)),\n", + " feature_names[indices],\n", + " rotation=90)\n", + "plt.xlabel(\"Features\")\n", + "plt.ylabel(\"Importance\")\n", + "plt.title(\"Feature Importance - Random Forest\")\n", + "plt.tight_layout()\n", + "plt.show()\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Predict delivery time\n", + "y_pred = final_model.predict(X)\n", + "\n", + "# Plot histogram\n", + "plt.figure(figsize=(8,5))\n", + "plt.hist(y_pred, bins=30)\n", + "plt.xlabel(\"Predicted Delivery Time (minutes)\")\n", + "plt.ylabel(\"Frequency\")\n", + "plt.title(\"Histogram of Predicted Delivery Time\")\n", + "plt.show()\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "#maybe vallue is changei will make it from my mind\n", + "import numpy as np\n", + "import pandas as pd\n", + "\n", + "from sklearn.model_selection import KFold\n", + "from sklearn.metrics import mean_absolute_error\n", + "\n", + "from sklearn.compose import ColumnTransformer\n", + "from sklearn.pipeline import Pipeline\n", + "from sklearn.preprocessing import OneHotEncoder\n", + "from sklearn.impute import SimpleImputer\n", + "from sklearn.ensemble import RandomForestRegressor\n", + "\n", + "from catboost import CatBoostRegressor\n", + "\n", + "\n", + "# Load data\n", + "\n", + "df = pd.read_csv(\"Q1_data.csv\")\n", + "\n", + "\n", + "# Pick target column (robust default)\n", + "\n", + "# If you have a specific target name, set it here, e.g. target_col = \"SalePrice\"\n", + "candidate_targets = [\"target\", \"Target\", \"y\", \"Y\", \"label\", \"Label\"]\n", + "target_col = next((c for c in candidate_targets if c in df.columns), df.columns[-1])\n", + "\n", + "X = df.drop(columns=[target_col])\n", + "y = df[target_col]\n", + "\n", + "# -----------------------------\n", + "# Identify column types\n", + "# -----------------------------\n", + "cat_cols = X.select_dtypes(include=[\"object\", \"category\", \"bool\"]).columns.tolist()\n", + "num_cols = [c for c in X.columns if c not in cat_cols]\n", + "\n", + "# Model 1: RandomForest\n", + "\n", + "numeric_pipe = Pipeline(steps=[\n", + " (\"imputer\", SimpleImputer(strategy=\"median\"))\n", + "])\n", + "\n", + "categorical_pipe = Pipeline(steps=[\n", + " (\"imputer\", SimpleImputer(strategy=\"most_frequent\")),\n", + " (\"onehot\", OneHotEncoder(handle_unknown=\"ignore\"))\n", + "])\n", + "\n", + "preprocess = ColumnTransformer(\n", + " transformers=[\n", + " (\"num\", numeric_pipe, num_cols),\n", + " (\"cat\", categorical_pipe, cat_cols),\n", + " ],\n", + " remainder=\"drop\"\n", + ")\n", + "\n", + "rf_model = Pipeline(steps=[\n", + " (\"prep\", preprocess),\n", + " (\"rf\", RandomForestRegressor(\n", + " n_estimators=400,\n", + " random_state=42,\n", + " n_jobs=-1\n", + " ))\n", + "])\n", + "\n", + "\n", + "# Model 2: CatBoost handle categorical\n", + "# CatBoost\n", + "cat_feature_indices = [X.columns.get_loc(c) for c in cat_cols]\n", + "\n", + "cb_model = CatBoostRegressor(\n", + " iterations=2000,\n", + " learning_rate=0.05,\n", + " depth=8,\n", + " loss_function=\"MAE\",\n", + " random_seed=42,\n", + " verbose=0\n", + ")\n", + "\n", + "\n", + "# kfold ensemble : average preds + mae\n", + "\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", + " 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", + " # Fit RF\n", + " rf_model.fit(X_train, y_train)\n", + " rf_pred = rf_model.predict(X_val)\n", + "\n", + " # Fit CatBoost\n", + " cb_model.fit(X_train, y_train, cat_features=cat_feature_indices)\n", + " cb_pred = cb_model.predict(X_val)\n", + "\n", + " # Average predictions\n", + " avg_pred = (rf_pred + cb_pred) / 2.0\n", + "\n", + " # MAE on averaged predictions\n", + " fold_mae = mean_absolute_error(y_val, avg_pred)\n", + " mae_scores.append(fold_mae)\n", + "\n", + " print(f\"Fold {fold} MAE (ensemble): {fold_mae:.6f}\")\n", + "\n", + "print(\"\\nEnsemble MAE (mean):\", np.mean(mae_scores))\n", + "print(\"Ensemble MAE (std): \", np.std(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/190/Q2.ipynb b/submissions_extracted/190/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..3b42d458d54210dd869d8e63ec063de3cf17441c --- /dev/null +++ b/submissions_extracted/190/Q2.ipynb @@ -0,0 +1,323 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q2-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import os\n", + "import pandas as pd\n", + "import numpy as np\n", + "from PIL import Image\n", + "from sklearn.model_selection import train_test_split\n", + "\n", + "# Load Labels\n", + "labels_df = pd.read_csv(os.path.join(path, \"labels.csv\"))\n", + "img_dir = os.path.join(path, \"images\")\n", + "\n", + "images = []\n", + "ages = []\n", + "\n", + "# Load Images and Resize\n", + "print(\"Loading images...\")\n", + "for index, row in labels_df.iterrows():\n", + " img_name = row.iloc[0]\n", + " age = row.iloc[1]\n", + " img_path = os.path.join(img_dir, img_name)\n", + "\n", + " if os.path.exists(img_path):\n", + " img = Image.open(img_path).convert('RGB')\n", + " img_array = np.array(img) / 255.0 # Normalize pixel values to [0, 1]\n", + " images.append(img_array)\n", + " ages.append(age)\n", + "\n", + "X = np.array(images)\n", + "y = np.array(ages)\n", + "\n", + "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 TensorDataset, DataLoader\n", + "\n", + "# Convert features to 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" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "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": [ + "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" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Get one batch from train loader\n", + "X_batch, y_batch = next(iter(train_loader))\n", + "\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": [ + "import matplotlib.pyplot as plt\n", + "import numpy as np\n", + "\n", + "plt.figure(figsize=(12,4))\n", + "\n", + "for i in range(5):\n", + " img = X_batch[i].permute(1, 2, 0).numpy()\n", + " age = y_batch[i].item()\n", + "\n", + " plt.subplot(1, 5, i+1)\n", + " plt.imshow(img)\n", + " plt.title(f\"Age: {int(age)}\")\n", + " plt.axis(\"off\")\n", + "\n", + "plt.show()\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import torch\n", + "import torch.nn as nn\n", + "import torch.optim as optim\n", + "\n", + "class AgeRegressor(nn.Module):\n", + " def __init__(self, input_shape):\n", + " super().__init__()\n", + " C, H, W = input_shape\n", + " input_dim = C * H * W\n", + "\n", + " self.model = nn.Sequential(\n", + " nn.Linear(input_dim, 512),\n", + " nn.ReLU(),\n", + " nn.Linear(512, 256),\n", + " nn.ReLU(),\n", + " nn.Linear(256, 128),\n", + " nn.ReLU(),\n", + " nn.Linear(128, 1)\n", + " )\n", + "\n", + " def forward(self, x):\n", + " x = x.view(x.size(0), -1)\n", + " return self.model(x)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "def train_one_epoch(model, loader, criterion, optimizer, device):\n", + " model.train()\n", + " running_loss = 0.0\n", + "\n", + " for Xb, yb in loader:\n", + " Xb, yb = Xb.to(device), yb.to(device)\n", + "\n", + " optimizer.zero_grad()\n", + " 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", + " return running_loss / len(loader.dataset)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "def validate(model, loader, criterion, device):\n", + " model.eval()\n", + " running_loss = 0.0\n", + "\n", + " with torch.no_grad():\n", + " for Xb, yb in loader:\n", + " Xb, yb = Xb.to(device), yb.to(device)\n", + " preds = model(Xb)\n", + " loss = criterion(preds, yb)\n", + " running_loss += loss.item() * Xb.size(0)\n", + "\n", + " return running_loss / len(loader.dataset)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n", + "print(\"Device:\", device)\n", + "\n", + "X_batch, y_batch = next(iter(train_loader))\n", + "input_shape = X_batch.shape[1:]\n", + "\n", + "model = AgeRegressor(input_shape).to(device)\n", + "\n", + "criterion = nn.MSELoss()\n", + "optimizer = optim.Adam(model.parameters(), lr=0.001)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "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, criterion, optimizer, 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:02d}/{num_epochs} | Train Loss: {train_loss:.4f} | Val Loss: {val_loss:.4f}\")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import matplotlib.pyplot as plt\n", + "\n", + "plt.figure(figsize=(8,5))\n", + "plt.plot(train_losses, label=\"Training Loss\")\n", + "plt.plot(val_losses, label=\"Validation Loss\")\n", + "plt.xlabel(\"Epoch\")\n", + "plt.ylabel(\"Loss (MSE)\")\n", + "plt.title(\"Training vs Validation Loss Over Epochs\")\n", + "plt.legend()\n", + "plt.grid(True)\n", + "plt.show()\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import matplotlib.pyplot as plt\n", + "import numpy as np\n", + "\n", + "# Predict ages\n", + "y_pred = model.predict(X_images)\n", + "\n", + "num_samples = 6\n", + "indices = np.random.choice(len(X_images), num_samples, replace=False)\n", + "\n", + "plt.figure(figsize=(12, 8))\n", + "\n", + "for i, idx in enumerate(indices):\n", + " plt.subplot(2, 3, i + 1)\n", + " plt.imshow(X_images[idx])\n", + " plt.axis(\"off\")\n", + "\n", + " plt.title(\n", + " f\"Actual Age: {y_true[idx]}\\nPredicted Age: {y_pred[idx][0]:.1f}\",\n", + " fontsize=11\n", + " )\n", + "\n", + "plt.suptitle(\"Predicted Age vs Actual Age\", fontsize=16)\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/190/Q3.ipynb b/submissions_extracted/190/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..6116b9175c8fa599d6a18df5499a3f15c1078894 --- /dev/null +++ b/submissions_extracted/190/Q3.ipynb @@ -0,0 +1,320 @@ +{ + "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", + "\n", + "# Read the dataset\n", + "df = pd.read_csv('/kaggle/input/q3-exam-data')\n", + "\n", + "# Display first few rows\n", + "df.head()\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "df.head()\n" + ], + "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": [ + "# Check missing values per column\n", + "df.isnull().sum().sort_values(ascending=False)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Separate numerical and categorical columns\n", + "num_cols = df.select_dtypes(include=[\"int64\", \"float64\"]).columns\n", + "cat_cols = df.select_dtypes(include=[\"object\"]).columns\n", + "\n", + "# Fill numerical missing values with median\n", + "for col in num_cols:\n", + " df[col] = df[col].fillna(df[col].median())\n", + "\n", + "# Fill categorical missing values with mode\n", + "for col in cat_cols:\n", + " df[col] = df[col].fillna(df[col].mode()[0])\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Check number of duplicate rows\n", + "df.duplicated().sum()\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Encode categorical variables if any 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": [ + "X = df.drop(columns=[\"target\"])\n", + "y = df[\"target\"]\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "X = df.drop(columns=[\"target\"])\n", + "y = df[\"target\"]\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "from sklearn.model_selection import StratifiedKFold\n", + "skf = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)\n", + "from catboost import CatBoostClassifier\n", + "from sklearn.metrics import f1_score\n", + "import numpy as np\n", + "f1_scores = []\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 = CatBoostClassifier(\n", + " iterations=200,\n", + " learning_rate=0.1,\n", + " depth=6,\n", + " loss_function=\"Logloss\",\n", + " eval_metric=\"F1\",\n", + " verbose=0,\n", + " random_state=42\n", + " )\n", + "\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(f\"Average F1 Score across all folds: {np.mean(f1_scores):.4f}\")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "from catboost import CatBoostClassifier\n", + "\n", + "final_model = CatBoostClassifier(\n", + " iterations=300,\n", + " learning_rate=0.1,\n", + " depth=6,\n", + " loss_function=\"Logloss\",\n", + " eval_metric=\"F1\",\n", + " verbose=0,\n", + " random_state=42\n", + ")\n", + "\n", + "final_model.fit(X, y)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import numpy as np\n", + "import pandas as pd\n", + "# Get feature importance values\n", + "importances = final_model.get_feature_importance()\n", + "feature_names = X.columns\n", + "\n", + "# Create DataFrame for easy handling\n", + "feature_importance_df = pd.DataFrame({\n", + " \"Feature\": feature_names,\n", + " \"Importance\": importances\n", + "}).sort_values(by=\"Importance\", ascending=False)\n", + "\n", + "\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import matplotlib.pyplot as plt\n", + "\n", + "plt.figure(figsize=(10,6))\n", + "plt.barh(\n", + " feature_importance_df[\"Feature\"].head(20)[::-1],\n", + " feature_importance_df[\"Importance\"].head(20)[::-1]\n", + ")\n", + "plt.xlabel(\"Importance Score\")\n", + "plt.title(\"Top 20 Feature Importances (CatBoost)\")\n", + "plt.tight_layout()\n", + "plt.show()\n", + "golden_feature = feature_importance_df.iloc[0]" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "\n", + "print(\" Golden Feature \")\n", + "print(f\"Feature Name: {golden_feature['Feature']}\")\n", + "print(f\"Importance Score: {golden_feature['Importance']:.4f}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import numpy as np\n", + "import pandas as pd\n", + "from sklearn.model_selection import StratifiedKFold\n", + "from sklearn.metrics import accuracy_score\n", + "from catboost import CatBoostClassifier\n", + "\n", + "\n", + "TARGET_COL = \"target\"\n", + "golden_feature = \"P_2\"\n", + "\n", + "X_full = df.drop(columns=[TARGET_COL])\n", + "y = df[TARGET_COL]\n", + "\n", + "X_golden = df[[golden_feature]]\n", + "\n", + "skf = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)\n", + "\n", + "def cv_accuracy(X, y, cv):\n", + " scores = []\n", + " for train_idx, val_idx in cv.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=500,\n", + " learning_rate=0.05,\n", + " depth=6,\n", + " loss_function=\"Logloss\",\n", + " eval_metric=\"Accuracy\",\n", + " verbose=0,\n", + " random_seed=42\n", + " )\n", + "\n", + " model.fit(X_train, y_train)\n", + " preds = model.predict(X_val)\n", + " scores.append(accuracy_score(y_val, preds))\n", + "\n", + " return float(np.mean(scores)), scores\n", + "\n", + "\n", + "full_mean_acc, full_scores = cv_accuracy(X_full, y, skf)\n", + "\n", + "gold_mean_acc, gold_scores = cv_accuracy(X_golden, y, skf)\n", + "\n", + "print(f\"Full model Accuracy (mean over folds): {full_mean_acc:.5f} | folds={np.round(full_scores, 5)}\")\n", + "print(f\"Golden-only Accuracy (mean over folds): {gold_mean_acc:.5f} | folds={np.round(gold_scores, 5)}\")\n", + "print(f\"Difference (Golden - Full): {(gold_mean_acc - full_mean_acc):.5f}\")\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/191/Q1.ipynb b/submissions_extracted/191/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..d28b3f2af391072dc55a43cc08947461b1b529bb --- /dev/null +++ b/submissions_extracted/191/Q1.ipynb @@ -0,0 +1,323 @@ +{ + "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 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" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "import os\n", + "import pandas as pd\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", + "csv_path = os.path.join(path, \"Q1_data.csv\")\n", + "df_food = 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_food.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Display dataset information using info()\n", + "df_food.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Show statistical description using describe()\n", + "df_food.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5:Plot the target distribution (delivery_time)\n", + "def check_target_imbalance(df, target_column):\n", + " print(\"Target Distribution:\")\n", + " #print(df[target_column].value_counts(normalize=True))\n", + " sns.histplot(df[target_column], bins=30)\n", + " plt.title(\"Target Distribution\")\n", + " plt.show()\n", + "\n", + "check_target_imbalance(df_food, \"Delivery_Time\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1:Drop the 'Order_ID' column from the data\n", + "df_food = df_food.drop(columns=[\"Order_ID\"])\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "df_food.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Handle missing values appropriately\n", + "#(Hint: I guess you want to have a closer look at the columns with missing values :) )\n", + "# do\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", + " if missing_values.any():\n", + " print(\"\\nHandle Missing Values as needed.\")\n", + " else:\n", + " print(\"\\nNo Missing Values Found.\")\n", + "\n", + "n_col = ['Weather', 'Traffic_Level', 'Time_of_Day', 'Courier_Experience_yrs']\n", + "\n", + "check_missing_values(df_food)\n", + "df_clean = df_food.dropna(subset=n_col).copy()# drop rows not including target Delivery time\n", + "print(f\"Shape after cleaning: {df_clean.shape}\")\n", + "\n", + "check_missing_values(df_clean)\n", + "df_clean['Delivery_Time'] = df_clean['Delivery_Time'].fillna(\"none\") # fill target\n", + "\n", + "\n", + "check_missing_values(df_clean)" + ], + "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", + " 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: Encode categorical variables if needed (Bonus if used One Hot Encoding\n", + "#encoder = OneHotEncoder(sparse_output=False)\n", + "from sklearn.preprocessing import LabelEncoder, OneHotEncoder\n", + "def encode_categorical_columns(df):\n", + " categorical_cols = df.select_dtypes(include=[\"object\"]).columns\n", + " print(\"Categorical Columns:\", list(categorical_cols))\n", + "\n", + "label_encoders = encode_categorical_columns(df_clean)\n", + "\n", + "\n", + "categorical_cols = df_clean.select_dtypes(include=[\"object\"]).columns\n", + "for col in categorical_cols:\n", + " print(f\"Encoding column: {col}\")\n", + " le = LabelEncoder()\n", + " df_clean[col] = le.fit_transform(df_clean[col].astype(str))\n", + "df_clean\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Apply feature scaling for all features (Use StandardScaler)\n", + "\n", + "from sklearn.model_selection import train_test_split\n", + "from sklearn.preprocessing import StandardScaler, MinMaxScaler, RobustScaler\n", + "features = df_clean.columns.drop(\"Delivery_Time\")\n", + "\n", + "scaler = StandardScaler()\n", + "df_clean[features] = scaler.fit_transform(df_clean[features])" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 6: Check for target imbalance and state if it is\n", + "# imbalanced or not (keep this cell empty if not needed)\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Split the dataset into features (X) and target (y)\n", + "# Modeling\n", + "X = df_clean.columns.drop(\"Delivery_Time\")\n", + "y = df_clean['Delivery_Time']" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "from sklearn.ensemble import RandomForestRegressor\n", + "from sklearn.metrics import mean_squared_error as sklearn_mse, mean_absolute_error, r2_score\n", + "from sklearn.model_selection import KFold\n", + "from sklearn.ensemble import RandomForestClassifier\n", + "from sklearn.metrics import f1_score\n", + "import numpy as np\n", + "# TODO: Split data with stratification (test_size=0.2, random_state=42)\n", + "X_train, X_test, y_train, y_test = train_test_split(\n", + " X,y,\n", + " test_size=0.2,\n", + " random_state=42,\n", + " shuffle=True,\n", + " stratify=y\n", + ")\n", + "\n", + "model = RandomForestRegressor(n_estimators=100, random_state=42)\n", + "model.fit(X_train, y_train)\n", + "print(\"Model trained!\")\n", + "\n", + "y_pred = model.predict(X_test)\n", + "mae = mean_absolute_error(y_train, y_test)\n", + "print(\"Validation MAE:\", mae)\n", + "\n", + "\n", + "#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/191/Q2.ipynb b/submissions_extracted/191/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..690d7541e46ec9e9cb29bcdf8acc9165ad6df299 --- /dev/null +++ b/submissions_extracted/191/Q2.ipynb @@ -0,0 +1,401 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "\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", + "# 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", + "\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", + "\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=64,\n", + " shuffle=True,\n", + " num_workers=2\n", + ")\n", + "# DataLoader for test/validation data\n", + "test_loader = DataLoader(\n", + " test_dataset,\n", + " batch_size=64,\n", + " shuffle=False,\n", + " num_workers=2\n", + ")\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 4. Print shape of one batch\n", + "# Get the first batch from the training DataLoader\n", + "X_batch, y_batch = next(iter(train_loader))\n", + "print(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": [ + "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": [ + "# train loop\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": [ + "# validation loop\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 the device, model, loss function, and 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]\n", + "hidden_dim = 14\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" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Start training for 20 epochs:\n", + "num_epochs = 20\n", + "learning_rate = 0.001\n", + "\n", + "criterion = nn.MSELoss()\n", + "# Define optimizer\n", + "optimizer = AdamW(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) # error in train loader\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 (CEL)')\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", + "# Scatter plot: Predicted vs Actual\n", + "plt.figure(figsize=(8, 6))\n", + "\n", + "# Plot: Predicted vs Actual scatter\n", + "plt.scatter(y_test.numpy(), predictions.flatten(), alpha=0.5, s=10, c='steelblue')\n", + "\n", + "# Add perfect prediction line\n", + "min_val = min(y_test.min(), predictions.min())\n", + "max_val = max(y_test.max(), predictions.max())\n", + "plt.plot([min_val, max_val], [min_val, max_val], 'r--', lw=2, label='Perfect Prediction')\n", + "\n", + "plt.xlabel('Actual Price ($)', fontsize=12)\n", + "plt.ylabel('Predicted Price ($)', fontsize=12)\n", + "plt.title('Predicted vs Actual Diamond Prices', fontsize=14)\n", + "plt.legend()\n", + "plt.grid(True, alpha=0.3)\n", + "\n", + "plt.tight_layout()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/191/Q3.ipynb b/submissions_extracted/191/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..f9a81bc5d453f3d5956067a97d757152140c85c9 --- /dev/null +++ b/submissions_extracted/191/Q3.ipynb @@ -0,0 +1,286 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "\n", + "\n", + "# Download latest version\n", + "\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q3-exam-data\")\n", + "\n", + "\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "import pandas as pd\n", + "import numpy as np\n", + "import matplotlib.pyplot as plt\n", + "import seaborn as sns\n", + "import kagglehub\n", + "import os\n", + "from tqdm import tqdm\n", + "\n", + "%matplotlib inline\n", + "df = pd.read_csv(os.path.join(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", + "missing_values = df.isnull().sum()\n", + "print(\"Columns with missing values:\")\n", + "print(missing_values[missing_values > 0])\n", + "df = df.fillna(df.median())\n", + "print(\"Columns with missing values:\")\n", + "missing_values = df.isnull().sum()\n", + "print(missing_values[missing_values > 0])\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "def check_duplicates(df):\n", + " duplicates = df.duplicated().sum()\n", + " print(f\"Number of Duplicate Samples: {duplicates}\")\n", + " if duplicates > 0:\n", + " print(\"Dropping Duplicates...\")\n", + " df.drop_duplicates(inplace=True)\n", + " print(\"Duplicates Dropped.\")\n", + " else:\n", + " print(\"No Duplicate Samples Found.\")\n", + "\n", + "check_duplicates(df)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "from sklearn.preprocessing import LabelEncoder, OneHotEncoder\n", + "def encode_categorical_columns(df):\n", + " categorical_cols = df.select_dtypes(include=[\"object\"]).columns\n", + " print(\"Categorical Columns:\", list(categorical_cols))\n", + "\n", + "label_encoders = encode_categorical_columns(df)\n", + "\n", + "\n", + "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].astype(str))\n", + "df" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "\n", + "from sklearn.model_selection import train_test_split\n", + "from sklearn.preprocessing import StandardScaler, MinMaxScaler, RobustScaler\n", + "features = df.columns.drop(\"Target\")\n", + "\n", + "scaler = StandardScaler()\n", + "df[features] = scaler.fit_transform(df[features])" + ], + "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: Split the dataset into features (X) and target (y)\n", + "# Modeling\n", + "X = df.columns.drop(\"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 StratifiedKFold\n", + "from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score\n", + "%pip install kagglehub catboost xgboost tqdm -q\n", + "from catboost import CatBoostClassifier\n", + "sklearn_models = {\n", + "\n", + " \"CatBoost\": CatBoostClassifier(\n", + " verbose=0,\n", + " n_estimators=320,\n", + " max_depth=4\n", + " )\n", + "}\n", + "all_results = {}\n", + "for name in sklearn_models:\n", + " all_results[name] = {'accuracy': [], 'precision': [], 'recall': [], 'f1': []}\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 sklearn_models.items():\n", + " print(f\"Training {model_name}...\")\n", + " model.fit(X_train, y_train) # train\n", + " y_pred = model.predict(X_test) # validate\n", + "\n", + " # 3. Save metrics for that model in this fold\n", + " accuracy = accuracy_score(y_test, y_pred)\n", + " precision = precision_score(y_test, y_pred, zero_division=0)\n", + " recall = recall_score(y_test, y_pred, zero_division=0)\n", + " f1 = f1_score(y_test, y_pred, zero_division=0)\n", + "\n", + " all_results[model_name]['accuracy'].append(accuracy)\n", + " all_results[model_name]['precision'].append(precision)\n", + " all_results[model_name]['recall'].append(recall)\n", + " all_results[model_name]['f1'].append(f1)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "# Gather importances from the models (from the last fold)\n", + "importances = {}\n", + "importances['CatBoost'] = sklearn_models['CatBoost'].feature_importances_\n", + "\n", + "# Create a 1x3 plot\n", + "fig, axes = plt.subplots(1, 3, figsize=(18, 6))\n", + "axes = axes.flatten()\n", + "features = X.columns\n", + "\n", + "for i, (model_name, imp) in enumerate(importances.items()):\n", + " # Sort features by importance for a cleaner plot\n", + " sorted_idx = np.argsort(imp)\n", + "\n", + " ax = axes[i]\n", + " ax.barh(features[sorted_idx], imp[sorted_idx])\n", + " ax.set_title(f\"{model_name} Feature Importance\")\n", + " ax.set_xlabel(\"Importance Score\")\n", + "\n", + "plt.tight_layout()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:" + ], + "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/192/Q1.ipynb b/submissions_extracted/192/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..724364e18b7bdd96d74896ecad1230220d60e330 --- /dev/null +++ b/submissions_extracted/192/Q1.ipynb @@ -0,0 +1,342 @@ +{ + "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.model_selection import train_test_split, StratifiedKFold, cross_val_score\n", + "from sklearn.preprocessing import StandardScaler, LabelEncoder\n", + "from sklearn.ensemble import RandomForestClassifier\n", + "from sklearn.metrics import classification_report, confusion_matrix, accuracy_score\n", + "\n", + "import warnings\n", + "warnings.filterwarnings('ignore')\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q1-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "csv_path = os.path.join(path, \"Q1_data.csv\")\n", + "\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", + "\n", + "def check_target_distribution(df, target_column):\n", + " df[target_column].hist(bins=30, edgecolor='black') ## hist is the type of shape in plot\n", + "\n", + " plt.title(f\"Target Distribution ({target_column})\")\n", + " plt.xlabel(target_column)\n", + " plt.ylabel(\"Frequency\")\n", + " plt.grid(False) ## without squares in the back\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" + ], + "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", + "def check_missing_values(df): ## توضح اذا فيها ميسينق فاليو او لا\n", + " missing_values = df.isnull().sum()\n", + " print(\"Missing Values per Column:\")\n", + " print(missing_values[missing_values > 0])\n", + " if missing_values.any():\n", + " print(\"\\nHandle Missing Values as needed.\")\n", + " else:\n", + " print(\"\\nNo Missing Values Found.\")\n", + "\n", + "check_missing_values(df)\n", + "\n", + "df = df.dropna(subset=['Weather', 'Traffic_Level', 'Delivery_Time','Courier_Experience_yrs'])\n", + "\n", + "df.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "def check_duplicates(df): ## يوضح التكرار\n", + " duplicates = df.duplicated().sum()\n", + " print(f\"Number of Duplicate Samples: {duplicates}\")\n", + " if duplicates > 0:\n", + " print(\"Dropping Duplicates...\")\n", + " df.drop_duplicates(inplace=True) ## اذا كان في تكرار سوي لها دروب\n", + " print(\"Duplicates Dropped.\")\n", + " else:\n", + " print(\"No Duplicate Samples Found.\")\n", + "\n", + "check_duplicates(df)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "from sklearn.preprocessing import LabelEncoder\n", + "\n", + "categorical_cols= ['Traffic_Level', 'Weather','Time_of_Day','Vehicle_Type']\n", + "\n", + "label_encoders = {} ## only if it is without rank\n", + "for col in categorical_cols: ## categorical_cols is the list up there\n", + " le = LabelEncoder()\n", + " df[col] = le.fit_transform(df[col])\n", + " label_encoders[col] = le\n", + "\n", + "\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "from sklearn.preprocessing import StandardScaler\n", + "\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" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "X = df.drop(\"Delivery_Time\", axis=1).astype(float) ## drop the target\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.metrics import mean_squared_error, mean_absolute_error\n", + "\n", + "\n", + "np.random.seed(42) # for reproducbility\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\n", + "\n", + "from sklearn.model_selection import StratifiedKFold\n", + "\n", + "# Use previously generated random classification data\n", + "X, y = X_clf.copy(), y_clf.copy()\n", + "\n", + "# Show full dataset class distribution\n", + "full_ratio = (y.value_counts(normalize=True) * 100).sort_index()\n", + "print(\"Full Dataset Class Distribution\")\n", + "print(\" y class percentages:\", {k: f\"{v:.2f}%\" for k, v in full_ratio.items()})\n", + "print(\"-\" * 40)\n", + "\n", + "# Define Stratified K-Fold\n", + "skf = StratifiedKFold(n_splits=5, shuffle=True, random_state=42) # same as kf but every fold have the same ratio, copy paste\n", + "\n", + "print(\"Stratified K-Fold Cross Validation\\n\" + \"-\"*40)\n", + "\n", + "for fold, (train_idx, test_idx) in enumerate(skf.split(X, y), start=1):\n", + " # indexing for each fold\n", + " X_train, X_test = X.iloc[train_idx], X.iloc[test_idx]\n", + " y_train, y_test = y.iloc[train_idx], y.iloc[test_idx]\n", + "\n", + " print(f\"Fold {fold}\")\n", + " print(\" X_train shape:\", X_train.shape)\n", + " print(\" X_test shape :\", X_test.shape)\n", + " print(\" y_train shape:\", y_train.shape)\n", + " print(\" y_test shape :\", y_test.shape)\n", + "\n", + " # showing class distribution\n", + " train_ratio = (y_train.value_counts(normalize=True) * 100).sort_index()\n", + " test_ratio = (y_test.value_counts(normalize=True) * 100).sort_index()\n", + "\n", + " print(\" y_train class percentages:\", {k: f\"{v:.2f}%\" for k, v in train_ratio.items()})\n", + " print(\" y_test class percentages :\", {k: f\"{v:.2f}%\" for k, v in test_ratio.items()})\n", + "\n", + " print(\"-\" * 40)\n", + "\n", + "\n", + "\n", + "# Task 3:\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\"Train: {X_train.shape}, Test: {X_test.shape}\")\n", + "\n", + "model = RandomForestClassifier(n_estimators=100, max_depth=15, class_weight='balanced', random_state=42)\n", + "model.fit(X_train, y_train)\n", + "print(\"Model trained!\")\n", + "\n", + "\n", + "#Task 4:\n", + "y_pred = model.predict(X_test)\n", + "mae = mean_absolute_error(y_test, y_pred)\n", + "print(\"MAE :\", mae)\n", + "\n", + "\n", + "\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "condition_counts = df['Delivery_Time'].value_counts()\n", + "plt.figure(figsize=(10, 5))\n", + "plt.bar(condition_counts.index, condition_counts.values, color='coral') # الاول اخذ اسماء الحالات في الاكس , الثاني اخذ قيمة كل حالة وحطها في الواي\n", + "plt.title('Delivery_Time Distribution')\n", + "plt.xlabel('Condition')\n", + "plt.ylabel('Count')\n", + "plt.xticks(rotation=45) # يميل الخط\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)) # do the figure\n", + "plt.hist(df['Delivery_Time'].dropna(), bins=50, edgecolor='black') #dropna drop the NaN\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/192/Q2.ipynb b/submissions_extracted/192/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..1e3784d426bddcf19c90e64531e8c3b0c781c2e1 --- /dev/null +++ b/submissions_extracted/192/Q2.ipynb @@ -0,0 +1,386 @@ +{ + "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 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 torch.nn.functional as F\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", + "\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", + "train_dataset = TensorDataset(X_train, y_train)\n", + "test_dataset = TensorDataset(X_test, y_test)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 3. Create DataLoaders\n", + "\n", + "train_loader = DataLoader(train_dataset, batch_size=32, shuffle=True)\n", + "test_loader = DataLoader(test_dataset, batch_size=32, shuffle=False)\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 4. Print shape of one batch\n", + "\n", + "print(\"Train dataset:\", len(train_dataset))\n", + "print(\"Test dataset:\", len(test_dataset))\n", + "\n", + "X_batch, y_batch = next(iter(train_loader))\n", + "print(f\"Training batch input shape: {X_batch.shape}\")\n", + "print(f\"Training batch labels shape: {y_batch.shape}\")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 5. Display sample images\n", + "\n" + ], + "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) ## output of the preveaus layer will be the input in this layer\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? ¯\\(ツ)/¯ , ## because it is classification we dont use sigmoid() here\n", + "\n", + " return output\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your training loop here:\n", + "\n", + "def train_one_epoch(model, optimizer, criterion, train_loader, device):\n", + " # Set the model to training mode\n", + " model.train()\n", + "\n", + " running_loss = 0.0\n", + "\n", + " for X_batch, y_batch in train_loader:\n", + " # Move batch to the selected device\n", + " X_batch = X_batch.to(device) # shape: (batch_size, num_features)\n", + " y_batch = y_batch.to(device) # shape: (batch_size,)\n", + "\n", + " # Forward pass (outputs are logits)\n", + " outputs = model(X_batch) # shape: (batch_size, num_classes)\n", + " loss = criterion(outputs, y_batch)\n", + "\n", + " # Backward pass & optimization\n", + " optimizer.zero_grad() # Clear previous gradients\n", + " loss.backward() # Compute gradients\n", + " optimizer.step() # Update model parameters\n", + "\n", + " running_loss += loss.item()\n", + "\n", + " # Average loss over all batches\n", + " avg_loss = running_loss / len(train_loader)\n", + "\n", + " return avg_loss" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your validation loop here:\n", + "\n", + "def validate(model, criterion, test_loader, device):\n", + " # Set the model to evaluation mode\n", + " model.eval()\n", + "\n", + " running_loss = 0.0\n", + " correct = 0\n", + " total = 0\n", + "\n", + " with torch.no_grad():\n", + " for X_batch, y_batch in test_loader:\n", + " # Move data to device\n", + " X_batch = X_batch.to(device) # shape: (batch_size, num_features)\n", + " y_batch = y_batch.to(device) # shape: (batch_size,)\n", + "\n", + " # Forward pass\n", + " outputs = model(X_batch) # shape: (batch_size, num_classes)\n", + " loss = criterion(outputs, y_batch)\n", + " running_loss += loss.item()\n", + "\n", + " # Apply Softmax to get probabilities\n", + " probabilities = F.softmax(outputs, dim=1) ## here we put softmax( output ) not in forward because it is classification\n", + "\n", + " # Pick the classes with highest probabilities\n", + " predicted = torch.argmax(probabilities, dim=1) ## argmax return the number of the label , like [0.1 ,0.2,0.4,0.7] because 0,7 is the max so it will give 3\n", + "\n", + " # Accuracy calculation\n", + " correct += (predicted == y_batch).sum().item()\n", + " total += y_batch.size(0)\n", + "\n", + " avg_loss = running_loss / len(test_loader)\n", + " accuracy = correct / total\n", + "\n", + " return avg_loss, accuracy" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Define device, model, loss, optimizer:\n", + "\n", + "# Device setup\n", + "device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n", + "\n", + "# Model parameters\n", + "input_dim = 36*36*3 # Number of tabular features\n", + "hidden_dim = 70 # Design choice\n", + "output_dim = 1 # Weather classes: Rainy, Sunny, Cloudy, Snowy # num of classes\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)\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", + "val_accuracies = []\n", + "\n", + "print('Starting Training...')\n", + "for epoch in range(num_epochs):\n", + " # Train one epoch\n", + " train_loss = train_one_epoch(model, optimizer, criterion, train_loader, device)\n", + "\n", + " # Validate\n", + " val_loss, val_accuracy = validate(model, criterion, test_loader, device)\n", + "\n", + " train_losses.append(train_loss)\n", + " val_losses.append(val_loss)\n", + " val_accuracies.append(val_accuracy)\n", + "\n", + " print(f'Epoch [{epoch+1}/{num_epochs}], Train Loss: {train_loss:.4f}, Val Loss: {val_loss:.4f}, Val Accuracy: {val_accuracy:.4f}')\n", + "\n", + "print('Training Complete!')" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "\n", + "plt.figure(figsize=(7, 5))\n", + "\n", + "plt.plot(train_losses, label='Train Loss')\n", + "plt.plot(val_losses, label='Validation Loss')\n", + "plt.title('Loss over Epochs')\n", + "plt.xlabel('Epoch')\n", + "plt.ylabel('Loss')\n", + "plt.legend()\n", + "\n", + "plt.tight_layout()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2 (Bonus): Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/192/Q3.ipynb b/submissions_extracted/192/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..46fc32364b5c317cb7524d0e51ec9b1559064b38 --- /dev/null +++ b/submissions_extracted/192/Q3.ipynb @@ -0,0 +1,285 @@ +{ + "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.model_selection import train_test_split, StratifiedKFold, cross_val_score\n", + "from sklearn.preprocessing import StandardScaler, LabelEncoder\n", + "from sklearn.ensemble import RandomForestClassifier\n", + "from sklearn.metrics import classification_report, confusion_matrix, accuracy_score\n", + "\n", + "import warnings\n", + "warnings.filterwarnings('ignore')\n", + "\n", + "\n", + "\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", + "\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", + "\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", + "\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", + "\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", + "\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:" + ], + "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) ## drop the target\n", + "y = df['Target'].astype(float)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:\n", + "\n", + "from sklearn.metrics import mean_squared_error, mean_absolute_error\n", + "\n", + "\n", + "np.random.seed(42) # for reproducbility\n", + "\n", + "X_clf = pd.DataFrame({\"Target\": np.random.randn(500)}) # features\n", + "y_clf = (X_clf[\"Target\"] > 0).astype(int) # labels as class 0 or 1\n", + "\n", + "from sklearn.model_selection import StratifiedKFold\n", + "\n", + "# Use previously generated random classification data\n", + "X, y = X_clf.copy(), y_clf.copy()\n", + "\n", + "# Show full dataset class distribution\n", + "full_ratio = (y.value_counts(normalize=True) * 100).sort_index()\n", + "print(\"Full Dataset Class Distribution\")\n", + "print(\" y class percentages:\", {k: f\"{v:.2f}%\" for k, v in full_ratio.items()})\n", + "print(\"-\" * 40)\n", + "\n", + "# Define Stratified K-Fold\n", + "skf = StratifiedKFold(n_splits=5, shuffle=True, random_state=42) # same as kf but every fold have the same ratio, copy paste\n", + "\n", + "print(\"Stratified K-Fold Cross Validation\\n\" + \"-\"*40)\n", + "\n", + "for fold, (train_idx, test_idx) in enumerate(skf.split(X, y), start=1):\n", + " # indexing for each fold\n", + " X_train, X_test = X.iloc[train_idx], X.iloc[test_idx]\n", + " y_train, y_test = y.iloc[train_idx], y.iloc[test_idx]\n", + "\n", + " print(f\"Fold {fold}\")\n", + " print(\" X_train shape:\", X_train.shape)\n", + " print(\" X_test shape :\", X_test.shape)\n", + " print(\" y_train shape:\", y_train.shape)\n", + " print(\" y_test shape :\", y_test.shape)\n", + "\n", + " # showing class distribution\n", + " train_ratio = (y_train.value_counts(normalize=True) * 100).sort_index()\n", + " test_ratio = (y_test.value_counts(normalize=True) * 100).sort_index()\n", + "\n", + " print(\" y_train class percentages:\", {k: f\"{v:.2f}%\" for k, v in train_ratio.items()})\n", + " print(\" y_test class percentages :\", {k: f\"{v:.2f}%\" for k, v in test_ratio.items()})\n", + "\n", + " print(\"-\" * 40)\n", + "\n", + "\n", + "model = RandomForestClassifier(n_estimators=100, max_depth=15, class_weight='balanced', random_state=42)\n", + "model.fit(X_train, y_train)\n", + "print(\"Model trained!\")\n", + "\n", + "y_pred = model.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=['Target']))" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "\n", + "condition_counts = df['Delivery_Time'].value_counts()\n", + "plt.figure(figsize=(10, 5))\n", + "plt.bar(condition_counts.index, condition_counts.values, color='coral') # الاول اخذ اسماء الحالات في الاكس , الثاني اخذ قيمة كل حالة وحطها في الواي\n", + "plt.title('Delivery_Time Distribution')\n", + "plt.xlabel('Condition')\n", + "plt.ylabel('Count')\n", + "plt.xticks(rotation=45) # يميل الخط\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/193/Q1.ipynb b/submissions_extracted/193/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..66d3b2fdf41309887bc31415d5020b6f08a625e9 --- /dev/null +++ b/submissions_extracted/193/Q1.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/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", + "%matplotlib inline\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, Delivery_Time):\n", + " df[Delivery_Time].hist(bins=30, edgecolor='black')\n", + "\n", + " plt.title(f\"Target Distribution ({Delivery_Time})\")\n", + " plt.xlabel(Delivery_Time)\n", + " plt.ylabel(\"Frequency\")\n", + " plt.grid(False)\n", + "\n", + " plt.show()\n", + "\n", + "check_target_distribution(df, \"Delivery_Time\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "df_clean = df.copy()\n", + "df.drop(columns=['Order_ID'])" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "\n", + "df_clean['Weather'] = df_clean['Weather'].fillna(df_clean['Weather'].mode()[0])\n", + "df_clean['Weather'] = df_clean['Delivery_Time'].fillna(df_clean['Delivery_Time'].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.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", + "X = ['Weather', 'Traffic_Level', 'Time_of_Day', 'Vehicle_Type']\n", + "from sklearn.preprocessing import LabelEncoder\n", + "\n", + "label_encoders = {}\n", + "for col in X:\n", + " le = LabelEncoder()\n", + " df[col] = le.fit_transform(df[col])\n", + " label_encoders[col] = le\n", + "\n", + "df" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "from sklearn.preprocessing import StandardScaler\n", + "\n", + "numerical_cols = df.select_dtypes(include=[\"int64\", \"float64\"]).columns.drop(\"Delivery_Time\") # 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, \tDelivery_Time):\n", + " print(\"Target Distribution:\")\n", + " print(df[\tDelivery_Time].value_counts(normalize=True))\n", + " sns.countplot(x=df[\tDelivery_Time])\n", + " plt.title(\"Target Distribution\")\n", + " plt.show()\n", + "\n", + "check_target_imbalance(df, \"Delivery_Time\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "X = df.drop(\"Delivery_Time\", axis=1).astype(float)\n", + "y = df['Delivery_Time'].astype(float)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:\n", + "from sklearn.model_selection import StratifiedKFold\n", + "from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score\n", + "\n", + "n_splits = 5 # K=5 Folds\n", + "\n", + "# Stratified 5-Fold Cross-Validation, shuffled\n", + "skf = StratifiedKFold(n_splits=n_splits, shuffle=True, random_state=42)\n", + "\n", + "# Storage for logistic regression results for each fold\n", + "lr_losses = []\n", + "lr_accuracy = []\n", + "lr_precision = []\n", + "lr_recall = []\n", + "lr_f1 = []\n", + "\n", + "def sigmoid(z):\n", + " return 1 / (1 + np.exp(-z))\n", + "\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", + "def gradient_descent(X, y, learning_rate, n_iters=500):\n", + " m, n = X.shape # m rows, n columns (dimensions)\n", + " theta = np.zeros(n) # initialize a zeros weight vector with n dimensions\n", + " losses = []\n", + "\n", + " for _ in tqdm(range(n_iters), desc=\"Training Logistic Regression\"):\n", + " z = np.dot(X, theta)\n", + " y_hat = sigmoid(z)\n", + " gradient = np.dot(X.T, (y_hat - y)) / m\n", + " theta -= learning_rate * gradient\n", + "\n", + " loss = binary_cross_entropy(y, y_hat)\n", + " losses.append(loss)\n", + "\n", + " return theta, losses\n", + "\n", + "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", + "\n", + "\n", + " # Train\n", + " theta, losses = gradient_descent(X_train, y_train, learning_rate=0.5, n_iters=500)\n", + "\n", + " # Validate\n", + " y_pred_proba = sigmoid(np.dot(X_test, theta))\n", + " y_pred = (y_pred_proba >= 0.5).astype(int)\n", + "\n", + " # Calculate evaluation metrics\n", + " accuracy = accuracy_score(y_test, y_pred)\n", + " precision = precision_score(y_test, y_pred, zero_division=0)\n", + " recall = recall_score(y_test, y_pred, zero_division=0)\n", + " f1 = f1_score(y_test, y_pred, zero_division=0)\n", + "\n", + " # Store results\n", + " lr_losses.append(losses)\n", + " lr_accuracy.append(accuracy)\n", + " lr_precision.append(precision)\n", + " lr_recall.append(recall)\n", + " lr_f1.append(f1)\n", + "\n", + "\n", + "# Calculate average loss across folds\n", + "avg_loss = np.mean(lr_losses, axis=0)\n", + "\n", + "plt.figure(figsize=(10, 6))\n", + "plt.plot(avg_loss, label='Logistic Regression Loss', color='purple')\n", + "plt.title('Average Logistic Regression Loss Curve (Across 5 Folds)')\n", + "plt.xlabel('Iteration')\n", + "plt.ylabel('Binary Cross-Entropy Loss')\n", + "plt.legend()\n", + "plt.grid(True, alpha=0.3)\n", + "plt.show()\n", + "\n", + "from sklearn.ensemble import RandomForestClassifier\n", + "\n", + "sklearn_models = {\n", + " \"Random Forest\": RandomForestClassifier(\n", + " n_estimators=320, # Number of trees\n", + " max_depth=4\n", + " )\n", + "\n", + " }\n", + "all_results = {}\n", + "for name in sklearn_models:\n", + " all_results[name] = {'accuracy': [], 'precision': [], 'recall': [], 'f1': []}\n", + "\n", + "\n", + " n_splits = 5 # K\n", + "\n", + "# Stratified 5-Fold Cross-Validation, shuffled\n", + "skf = StratifiedKFold(n_splits=n_splits, shuffle=True, random_state=42)\n", + "\n", + "\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:\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/193/Q2.ipynb b/submissions_extracted/193/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..ba769d6a4953e7cf0583fe7656aa31396a8d813a --- /dev/null +++ b/submissions_extracted/193/Q2.ipynb @@ -0,0 +1,338 @@ +{ + "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 Adam\n", + "import matplotlib.pyplot as plt\n", + "from sklearn.datasets import load_breast_cancer\n", + "from sklearn.model_selection import train_test_split\n", + "from sklearn.preprocessing import StandardScaler\n", + "from torch.utils.data import TensorDataset\n", + "from torch.utils.data import DataLoader\n", + "data = labels.csv()\n", + "\n", + "X = data.data\n", + "y = data.target\n", + "\n", + "# Split the dataset into training and testing sets\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42, stratify=y)\n", + "\n", + "# Standardize the data\n", + "scaler = StandardScaler()\n", + "X_train = scaler.fit_transform(X_train)\n", + "X_test = scaler.transform(X_test)\n", + "\n", + "# transform to tensors\n", + "X_train = torch.tensor(X_train, dtype=torch.float32)\n", + "X_test = torch.tensor(X_test, dtype=torch.float32)\n", + "y_train = torch.tensor(y_train, dtype=torch.float32)\n", + "y_test = torch.tensor(y_test, dtype=torch.float32)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 2. Create TensorDataset objects\n", + "train_dataset = TensorDataset(X_train, y_train)\n", + "test_dataset = TensorDataset(X_test, y_test)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 3. Create DataLoaders\n", + "train_loader = DataLoader(train_dataset, batch_size=32, shuffle=True)\n", + "test_loader = DataLoader(test_dataset, batch_size=32, shuffle=False)\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 4. Print shape of one batch\n", + "first_sample, _ = train_dataset[0]\n", + "print(f\"Shape of one sample: {first_sample.shape}\")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 5. Display sample images\n", + "print(f\"Label: {img_path}\")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your model class here:\n", + "\n", + "linear = nn.Linear(in_features=3, out_features=1)\n", + "x = torch.randn(4, 3)\n", + "y = linear(x)\n", + "print(\"Input shape:\", x.shape)\n", + "print(\"Output shape:\", y.shape)\n", + "\n", + "class NN2Layer(nn.Module):\n", + "\n", + " def __init__(self, input_dim, hidden_dim):\n", + "\n", + " super(NN2Layer, self).__init__()\n", + " # input_dim = num of features, hidden_dim = num of neurons\n", + " self.layer1 = nn.Linear(input_dim, hidden_dim)\n", + " 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", + "\n", + " # non-linearity activation function\n", + " self.relu = nn.ReLU()\n", + " # output activation function\n", + " self.sigmoid = nn.Sigmoid()\n", + "\n", + " # forward pass\n", + " def forward(self, x):\n", + " z1 = self.layer1(x)\n", + " a1 = self.relu(z1)\n", + " z2 = self.layer2(a1)\n", + " a2 = self.sigmoid(z2)\n", + " return a2\n", + " # Instantiate the model\n", + "input_dim = 4 # number of input features\n", + "hidden_dim = 3 # number of hidden neurons\n", + "\n", + "model = NN2Layer(input_dim, hidden_dim)\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}\")" + ], + "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", + "\n", + "def validate(model, criterion, test_loader, device):\n", + " # Set the model to evaluation mode\n", + " model.eval()\n", + "\n", + " running_loss = 0.0\n", + " correct = 0\n", + " total = 0\n", + "\n", + " with torch.no_grad(): # Disable gradient computation\n", + " for X_batch, y_batch in test_loader:\n", + " # Move batch to the selected device\n", + " X_batch = X_batch.to(device)\n", + " y_batch = y_batch.view(-1, 1).to(device)\n", + "\n", + " # Forward pass\n", + " outputs = model(X_batch)\n", + " loss = criterion(outputs, y_batch)\n", + " running_loss += loss.item()\n", + "\n", + " # Binary predictions\n", + " predicted = (outputs > 0.5).float()\n", + "\n", + " # Accuracy calculation\n", + " correct += (predicted == y_batch).sum().item()\n", + " total += y_batch.size(0)\n", + "\n", + " avg_loss = running_loss / len(test_loader)\n", + " accuracy = correct / total\n", + "\n", + " return avg_loss, accuracy\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Define device, model, loss, optimizer:\n", + "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)" + ], + "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", + "plt.figure(figsize=(10, 5))\n", + "plt.plot(running_loss, 'b-o')\n", + "plt.xlabel('Epoch')\n", + "plt.ylabel('Validation Loss')\n", + "plt.grid(True, alpha=0.3)\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2 (Bonus): Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/193/Q3.ipynb b/submissions_extracted/193/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..e0ed85933a24115e7466c6d204e53e6128bab431 --- /dev/null +++ b/submissions_extracted/193/Q3.ipynb @@ -0,0 +1,269 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "\n", + "\n", + "# Download latest version\n", + "\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q3-exam-data\")\n", + "\n", + "\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "import pandas as pd\n", + "import numpy as np\n", + "import matplotlib.pyplot as plt\n", + "import seaborn as sns\n", + "import kagglehub\n", + "import os\n", + "from tqdm import tqdm\n", + "\n", + "csv_path = os.path.join(path, \"Q3_data.csv\")\n", + "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": [ + "for col in ['type2']:\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):\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: No catoegorical variables in the dataset" + ], + "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", + "def check_target_imbalance(df, \tDelivery_Time):\n", + " print(\"Target Distribution:\")\n", + " print(df[\tDelivery_Time].value_counts(normalize=True))\n", + " sns.countplot(x=df[\tDelivery_Time])\n", + " plt.title(\"Target Distribution\")\n", + " plt.show()\n", + "\n", + "check_target_imbalance(df, \"Target\")\n", + "#There's an Imbalance in the\"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 IPython.display import clear_output\n", + "%pip install kagglehub catboost xgboost tqdm imbalanced-learn -q\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", + "from sklearn.model_selection import StratifiedKFold\n", + "from catboost import CatBoostRegressor\n", + "from catboost import CatBoostClassifier\n", + "\n", + "\n", + "all_results = {}\n", + "\n", + "sklearn_models = {\n", + " \"CatBoost\": CatBoostClassifier(\n", + " verbose=0,\n", + " n_estimators=320,\n", + " max_depth=4\n", + " )\n", + "}\n", + "\n", + "\n", + "for name in sklearn_models:\n", + " all_results[name] = {'accuracy': [], 'precision': [], 'recall': [], 'f1': []}\n", + "\n", + "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", + "\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", + " 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", + "\n", + " # Store results\n", + " all_results[model_name][\"mse\"].append(mse)\n", + " all_results[model_name][\"rmse\"].append(rmse)\n", + " all_results[model_name][\"r2\"].append(r2)\n", + "\n", + "\n", + "models = {\n", + " \"CatBoost\": CatBoostClassifier(verbose=0, n_estimators=200, max_depth=4)\n", + "}\n", + "\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": [ + "# 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/194/Q1.ipynb b/submissions_extracted/194/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..1a0d7cbcfa14ddecc6ca2be1a680790effc6502c --- /dev/null +++ b/submissions_extracted/194/Q1.ipynb @@ -0,0 +1,378 @@ +{ + "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\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(path + \"/Q1_data.csv\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "df.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "df.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "import matplotlib.pyplot as plt\n", + "import seaborn as sns\n", + "\n", + "def plot_target_distribution(df, target_col=\"delivery_time\"):\n", + " plt.figure(figsize=(8,5))\n", + " sns.histplot(df[target_col], bins=30, kde=True)\n", + " plt.title(\"Target Distribution: Delivery Time\")\n", + " plt.xlabel(\"Delivery Time (minutes)\")\n", + " plt.ylabel(\"Count\")\n", + " plt.tight_layout()\n", + " plt.show()\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "numerical_cols = df.select_dtypes(include=[\"int64\"]).columns.drop(\"Order_ID\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "print(\"Missing values:\")\n", + "print(df.isnull().sum())" + ], + "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", + "print('data before encoding:\\n')\n", + "onehot_encoder = OneHotEncoder(sparse_output=False) # Instantiate OneHotEncoder\n", + "data_onehot_encoded = onehot_encoder.fit_transform() # Apply fit_transform to the copied\n", + "\n", + "print('\\nData after encoding:\\n', data_onehot_encoded)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "from sklearn.preprocessing import StandardScaler\n", + "import pandas as pd\n", + "\n", + "def scale_features(X):\n", + " scaler = StandardScaler()\n", + " X_scaled = scaler.fit_transform(X)\n", + " return pd.DataFrame(X_scaled, columns=X.columns, index=X.index), scaler" + ], + "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, \"status\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "from re import X\n", + "# Task 1: Write your code here:\n", + "import numpy as np\n", + "np.random.seed(42)\n", + "x=df.drop(\"delivery_time\",axis=1)\n", + "y=df['delivery_time']\n", + "# Split the dataset into training and testing sets\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42, stratify=y)\n", + "\n", + "# transform to tensors\n", + "X_train = torch.tensor(X_train.values, dtype=torch.float32)\n", + "X_test = torch.tensor(X_test.values, dtype=torch.float32)\n", + "y_train = torch.tensor(y_train.values, dtype=torch.long)\n", + "y_test = torch.tensor(y_test.values, dtype=torch.long)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:\n", + "from sklearn.model_selection import KFold\n", + "\n", + "# Use previously generated random data (example: regression data)\n", + "X, y = X.copy(), y.copy()\n", + "\n", + "# Define K-Fold Cross Validation\n", + "kf = KFold(n_splits=5, shuffle=True, random_state=42)\n", + "\n", + "# Iterate through folds\n", + "for fold, (train_idx, test_idx) in enumerate(kf.split(X), start=1):\n", + " # indexing for each fold\n", + " X_train, X_test = X.iloc[train_idx], X.iloc[test_idx]\n", + " y_train, y_test = y.iloc[train_idx], y.iloc[test_idx]\n", + " # print shapes\n", + " print(f\"Fold {fold}\")\n", + " print(\" X_train shape:\", X_train.shape)\n", + " print(\" X_test shape :\", X_test.shape)\n", + " print(\" y_train shape:\", y_train.shape)\n", + " print(\" y_test shape :\", y_test.shape)\n", + " print(\"-\" * 30)\n", + " for fold_idx, (train_index, test_index) in enumerate(skf.split(X, y)):\n", + " print(f\"\\nFold {fold_idx + 1}/{n_splits}\")\n", + "\n", + " X_train, X_test = X.iloc[train_index], X.iloc[test_index]\n", + " y_train, y_test = y.iloc[train_index], y.iloc[test_index]\n", + "\n", + " # Train\n", + " theta, losses = gradient_descent(X_train, y_train, learning_rate=0.5, n_iters=500)\n", + "\n", + " # Validate\n", + " y_pred_proba = sigmoid(np.dot(X_test, theta))\n", + " y_pred = (y_pred_proba >= 0.5).astype(int)\n", + "\n", + " # Calculate evaluation metrics\n", + " accuracy = accuracy_score(y_test, y_pred)\n", + " precision = precision_score(y_test, y_pred, zero_division=0)\n", + " recall = recall_score(y_test, y_pred, zero_division=0)\n", + " f1 = f1_score(y_test, y_pred, zero_division=0)\n", + "\n", + " # Store results\n", + " lr_losses.append(losses)\n", + " lr_accuracy.append(accuracy)\n", + " lr_precision.append(precision)\n", + " lr_recall.append(recall)\n", + " lr_f1.append(f1)\n", + "\n", + " #task 3\n", + " from sklearn.ensemble import RandomForestClassifier\n", + " importances = {}\n", + "sklearn_models{\n", + " \"Random Forest\": RandomForestClassifier(\n", + " n_estimators=320, # Number of trees\n", + " max_depth=4 )\n", + "\n", + "}\n", + "importances['Random Forest'] = sklearn_models['Random Forest'].feature_importances_\n", + "\n", + "#task 4\n", + "\n", + "#task 5\n", + "avg_loss = np.mean(lr_losses, axis=0)\n", + "\n", + "plt.figure(figsize=(10, 6))\n", + "plt.plot(avg_loss, label='Logistic Regression Loss', color='purple')\n", + "plt.title('Average Logistic Regression Loss Curve (Across 5 Folds)')\n", + "plt.xlabel('Iteration')\n", + "plt.ylabel('Binary Cross-Entropy Loss')\n", + "plt.legend()\n", + "plt.grid(True, alpha=0.3)\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "plt.AbstractContextManager" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "plt." + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:\n", + " import numpy as np\n", + "import pandas as pd\n", + "\n", + "from sklearn.model_selection import KFold\n", + "from sklearn.metrics import mean_absolute_error\n", + "from sklearn.ensemble import RandomForestRegressor\n", + "from catboost import CatBoostRegressor\n", + "\n", + "# Load dataset (you already have this part)\n", + "\n", + "df = pd.read_csv(\"food_delivery.csv\")\n", + "\n", + "X = df.drop(\"delivery_time\", axis=1)\n", + "y = df[\"delivery_time\"]\n", + "\n", + "# KFold setup\n", + "kf = KFold(n_splits=5, shuffle=True, random_state=42)\n", + "\n", + "mae_scores = []\n", + "\n", + "# KFold loop with ensemble\n", + "\n", + "for fold, (train_idx, val_idx) in enumerate(kf.split(X)):\n", + " print(f\"Fold {fold + 1}\")\n", + "\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_model = RandomForestRegressor(\n", + " n_estimators=200,\n", + " max_depth=None,\n", + " random_state=42,\n", + " n_jobs=-1\n", + " )\n", + "\n", + "\n", + " cb_model = CatBoostRegressor(\n", + " iterations=500,\n", + " learning_rate=0.05,\n", + " depth=8,\n", + " loss_function=\"MAE\",\n", + " verbose=False,\n", + " random_seed=42\n", + " )\n", + "\n", + " # Train both models\n", + " rf_model.fit(X_train, y_train)\n", + " cb_model.fit(X_train, y_train)\n", + "\n", + " # Predictions\n", + " rf_preds = rf_model.predict(X_val)\n", + " cb_preds = cb_model.predict(X_val)\n", + "\n", + " ensemble_preds = (rf_preds + cb_preds) / 2\n", + "\n", + " # MAE\n", + " mae = mean_absolute_error(y_val, ensemble_preds)\n", + " mae_scores.append(mae)\n", + "\n", + " print(f\"MAE: {mae:.4f}\")\n", + "\n", + "print(\"\\nAverage MAE across folds:\", np.mean(mae_scores))\n" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/194/Q2.ipynb b/submissions_extracted/194/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..6943454309b7f52d5c4d818911941e2eddd0fc51 --- /dev/null +++ b/submissions_extracted/194/Q2.ipynb @@ -0,0 +1,415 @@ +{ + "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 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", + "# TODO: Split the dataset into training and testing sets (80% train, 20% test)\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n", + "X=torch.tensor\n", + "Y=torch.tensor\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", + "\n", + "\n", + "# Print dataset sizes\n", + "print(\"Train dataset:\", len(train_dataset))\n", + "print(\"Test dataset:\", len(test_dataset))" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 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)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 3. Create DataLoaders\n", + "\n", + "# Create Dataloaders to train and test data in batche\n", + "train_loader = DataLoader(train_dataset, batch_size=32, shuffle=True)\n", + "test_loader = DataLoader(test_dataset, batch_size=32, shuffle=False)\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 4. Print shape of one batch\n", + "# Get the first batch from the training DataLoader\n", + "X_batch, y_batch = next(iter(train_loader))\n", + "print(f\"Training batch input shape: {X_batch.shape}\")\n", + "print(f\"Training batch labels shape: {y_batch.shape}\")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 5. Display sample images\n", + "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", + " self.layer3=nn.Linear(hidden_dim, hidden_dim)\n", + "\n", + " # TODO: What are the dimensions of previous and output layer? (hint: hidden neurons? num of classes?)\n", + " self.layer4 = nn.Linear(hidden_dim, output_dim)\n", + "\n", + " # activation function for non-linearity\n", + " self.relu = nn.ReLU()\n", + "\n", + " # Defines how input data flows through the network\n", + " def forward(self, x):\n", + " # Layer 1: TODO\n", + " z1 = self.layer1(x)\n", + " a1 = self.relu(z1)\n", + "\n", + " # Layer 2 TODO\n", + " z2 = self.layer2(a1)\n", + " a2 = self.relu(z2)\n", + "\n", + " # Layer 3 TODO\n", + " z3 = self.layer3(a2)\n", + " a3 = self.relu(z3)\n", + "\n", + " # output TODO\n", + " z4 = self.layer4(a3)\n", + "\n", + " # TODO: are we missing output activation function? (hint: Loss Function)\n", + "\n", + " return z4\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your training loop here:\n", + "def train_one_epoch(model, optimizer, criterion, train_loader, device):\n", + " # Set the model to training mode\n", + " model.train()\n", + "\n", + " running_loss = 0.0\n", + "\n", + " for X_batch, y_batch in train_loader:\n", + " # Move batch to the selected device\n", + " X_batch = X_batch.view(X_batch.size(0), -1).to(device)\n", + " y_batch = y_batch.to(device)\n", + "\n", + " # Forward pass\n", + " # TODO: make predictions\n", + " outputs = model(X_batch) # shape: (batch_size, 10)\n", + " # TODO: compute loss\n", + " loss = criterion(outputs, y_batch)\n", + "\n", + " # Backward pass & optimization\n", + " optimizer.zero_grad() # Clear previous gradients\n", + " loss.backward() # Compute gradients\n", + " optimizer.step() # Update model parameters\n", + "\n", + " running_loss += loss.item()\n", + "\n", + " # Average loss over all batches\n", + " avg_loss = running_loss / len(train_loader)\n", + "\n", + " return avg_loss" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your validation loop here:\n", + "def validate(model, criterion, test_loader, device):\n", + " # Set the model to evaluation mode\n", + " model.eval()\n", + "\n", + " running_loss = 0.0\n", + " correct = 0\n", + " total = 0\n", + "\n", + " with torch.no_grad():\n", + " for X_batch, y_batch in test_loader:\n", + " # Move data to device\n", + " X_batch = X_batch.view(X_batch.size(0), -1).to(device)\n", + " y_batch = y_batch.to(device)\n", + "\n", + " # Forward pass\n", + " # TODO: make predictions\n", + " outputs = model(X_batch) # shape: (batch_size, 10)\n", + " # TODO: compute loss\n", + " loss = criterion(outputs, y_batch)\n", + " running_loss += loss.item()\n", + "\n", + " # TODO: Apply Softmax to get probabilities\n", + " probabilities = F.softmax(outputs, dim=1)\n", + "\n", + " # TODO: Multiclass predictions\n", + " predicted = torch.argmax(probabilities, dim=1)\n", + "\n", + " # Accuracy calculation\n", + " correct += (predicted == y_batch).sum().item()\n", + " total += y_batch.size(0)\n", + "\n", + " avg_loss = running_loss / len(test_loader)\n", + " # TODO: how do we calculate accuracy?\n", + " accuracy = correct / total\n", + "\n", + " return avg_loss, accuracy\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Define device, model, loss, optimizer:\n", + "# Device setup\n", + "device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n", + "\n", + "# Model parameters\n", + "# TODO: What are input features ? (hint: flatten using channel, height, width)\n", + "input_dim = 3 * 32 * 32 # CIFAR-10 images flattened (RGB)\n", + "\n", + "# TODO: choose number of hidden neurons\n", + "hidden_dim = 64 # Design choice\n", + "\n", + "# TODO: what are the number of classes ?\n", + "output_dim = 10 # CIFAR-10 classes\n", + "\n", + "# TODO: Instantiate model (what are the model class inputs?)\n", + "model = 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)\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", + "\n", + "def plot_losses(train_losses, val_losses):\n", + " epochs = range(1, len(train_losses) + 1)\n", + "\n", + " plt.figure(figsize=(8, 5))\n", + " plt.plot(epochs, train_losses, label='Training Loss')\n", + " plt.plot(epochs, val_losses, label='Validation Loss')\n", + "\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()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2 (Bonus): Write your code here:\n", + "import torch\n", + "import numpy as np\n", + "\n", + "def unnormalize(img, mean, std):\n", + " mean = torch.tensor(mean).view(3,1,1)\n", + " std = torch.tensor(std).view(3,1,1)\n", + " return img * std + 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/194/Q3.ipynb b/submissions_extracted/194/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..a298f504f877395f30be88a1f8f55fe5a574bac7 --- /dev/null +++ b/submissions_extracted/194/Q3.ipynb @@ -0,0 +1,310 @@ +{ + "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", + "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", + "print(\"Missing values:\")\n", + "print(df.isnull().sum())" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "def check_duplicates(df):\n", + " duplicates = df.duplicated().sum()\n", + " print(f\"Number of Duplicate Samples: {duplicates}\")\n", + " if duplicates > 0:\n", + " print(\"Dropping Duplicates...\")\n", + " df.drop_duplicates(inplace=True)\n", + " print(\"Duplicates Dropped.\")\n", + " else:\n", + " print(\"No Duplicate Samples Found.\")\n", + "\n", + "check_duplicates(df)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "from sklearn.preprocessing import OneHotEncoder\n", + "print('data before encoding:\\n')\n", + "onehot_encoder = OneHotEncoder(sparse_output=False) # Instantiate OneHotEncoder\n", + "data_onehot_encoded = onehot_encoder.fit_transform() # Apply fit_transform to the copied\n", + "\n", + "print('\\nData after encoding:\\n', data_onehot_encoded)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "\n", + "numerical_cols = df.select_dtypes(include=[\"number\"]).columns.drop(\"price\")\n", + "\n", + "scaler = StandardScaler()\n", + "\n", + "# TODO: Apply fit_transform to scale the numerical columns\n", + "df[numerical_cols] = scaler.fit_transform(df[numerical_cols])\n", + "\n", + "df.head()\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, \"status\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "X = df.drop(\"status\", axis=1).astype(float)\n", + "y = df['status'].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", + "lr_losses = []\n", + "lr_accuracy = []\n", + "lr_precision = []\n", + "lr_recall = []\n", + "lr_f1 = []\n", + "\n", + "for fold_idx, (train_index, test_index) in enumerate(skf.split(X, y)):\n", + " print(f\"\\nFold {fold_idx + 1}/{n_splits}\")\n", + "\n", + " X_train, X_test = X.iloc[train_index], X.iloc[test_index]\n", + " y_train, y_test = y.iloc[train_index], y.iloc[test_index]\n", + "\n", + " # Train\n", + " theta, losses = gradient_descent(X_train, y_train, learning_rate=0.5, n_iters=500)\n", + "\n", + " # Validate\n", + " y_pred_proba = sigmoid(np.dot(X_test, theta))\n", + " y_pred = (y_pred_proba >= 0.5).astype(int)\n", + "\n", + " # Calculate evaluation metrics\n", + " accuracy = accuracy_score(y_test, y_pred)\n", + " precision = precision_score(y_test, y_pred, zero_division=0)\n", + " recall = recall_score(y_test, y_pred, zero_division=0)\n", + " f1 = f1_score(y_test, y_pred, zero_division=0)\n", + "\n", + " # Store results\n", + " lr_losses.append(losses)\n", + " lr_accuracy.append(accuracy)\n", + " lr_precision.append(precision)\n", + " lr_recall.append(recall)\n", + " lr_f1.append(f1)\n", + "\n", + " # Calculate average loss across folds\n", + "avg_loss = np.mean(lr_losses, axis=0)\n", + "\n", + "plt.figure(figsize=(10, 6))\n", + "plt.plot(avg_loss, label='Logistic Regression Loss', color='purple')\n", + "plt.title('Average Logistic Regression Loss Curve (Across 5 Folds)')\n", + "plt.xlabel('Iteration')\n", + "plt.ylabel('Binary Cross-Entropy Loss')\n", + "plt.legend()\n", + "plt.grid(True, alpha=0.3)\n", + "plt.show()\n", + "\n", + "print(\"LOGISTIC REGRESSION Performance:\")\n", + "print(f\" Accuracy: {np.mean(lr_accuracy):.4f}\")\n", + "print(f\" Precision: {np.mean(lr_precision):.4f}\")\n", + "print(f\" Recall: {np.mean(lr_recall):.4f}\")\n", + "print(f\" F1-Score: {np.mean(lr_f1):.4f}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "# Gather importances from the models (from the last fold)\n", + "importances = {}\n", + "\n", + "importances['Random Forest'] = sklearn_models['Random Forest'].feature_importances_\n", + "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()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:\n", + "from catboost import CatBoostClassifier\n", + "from sklearn.model_selection import KFold\n", + "from sklearn.metrics import accuracy_score\n", + "import numpy as np\n", + "\n", + "def bonus_golden_feature_cv(X, y, golden_feature, n_splits=5, random_state=42):\n", + " X_golden = X[[golden_feature]]\n", + "\n", + " kf = KFold(n_splits=n_splits, shuffle=True, random_state=random_state)\n", + " scores = []\n", + "\n", + " for train_idx, val_idx in kf.split(X_golden):\n", + " X_train, X_val = X_golden.iloc[train_idx], X_golden.iloc[val_idx]\n", + " y_train, y_val = y.iloc[train_idx], y.iloc[val_idx]\n", + "\n", + " model = CatBoostClassifier(\n", + " iterations=300,\n", + " learning_rate=0.1,\n", + " depth=6,\n", + " loss_function='Logloss',\n", + " verbose=0,\n", + " random_seed=random_state\n", + " )\n", + "\n", + " model.fit(X_train, y_train)\n", + " preds = model.predict(X_val)\n", + " scores.append(accuracy_score(y_val, preds))\n", + "\n", + " print(f\"Golden Feature CV Accuracy: {np.mean(scores):.4f}\")\n", + " return scores" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/195/Q1.ipynb b/submissions_extracted/195/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..d971b9bb5911fb6127270df8df77978520725159 --- /dev/null +++ b/submissions_extracted/195/Q1.ipynb @@ -0,0 +1,267 @@ +{ + "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)\n", + "print(\"Files in path:\", os.listdir(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", + "# reading data\n", + "csv_path = os.path.join(path, \"ANON_OWNER/q1-exam-data\")\n", + "\n", + "df = pd.read_csv(os.path.join(path, \"Q1_data.csv\"))\n", + "img_dir = os.path.join(path, \"images\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "df.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "df.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "def check_target_distribution(df, target_column):\n", + " df[target_column].hist(bins=30, edgecolor='black')\n", + " plt.title(f\"Target Distribution ({target_column})\")\n", + " plt.xlabel(target_column)\n", + " plt.ylabel(\"Frequency\")\n", + " plt.grid(False)\n", + " plt.show()\n", + " check_target_distribution(df, \"delivery_time\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# handiling the missing values\n", + "\n", + "def check_missing_values(df):\n", + " missing_values = df.isnull().sum()\n", + " print(\"Missing Values per Column:\")\n", + " print(missing_values[missing_values > 0])\n", + " if missing_values.any():\n", + " print(\"\\nHandle Missing Values as needed.\")\n", + " else:\n", + " print(\"\\nNo Missing Values Found.\")\n", + "check_missing_values(df)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# handiling duplicates\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)\n", + "\n", + "df.drop_duplicates(inplace=True)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "from sklearn.preprocessing import OneHotEncoder\n", + " # one hot encoding\n", + "labels = [['delivery distance'], ['restaurant preparation time'], ['traffic conditions'], [' order details']]\n", + "encoder = OneHotEncoder(sparse_output=False)\n", + "encoded = encoder.fit_transform(labels)\n", + "print(\"original labels\", labels)\n", + "print(\"Encoded:, labels)\\n\", encoded)" + ], + "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", + "\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_splits = 5\n", + "# 5-Fold Cross-Validation, shuffled\n", + "kf = KFold(n_splits=n_splits, shuffle=True, random_state=42)\n", + "lr_losses = []\n", + "lr_mse = []\n", + "lr_rmse = []\n", + "lr_r2 = []\n", + "\n", + "def mean_squared_error(y, y_hat):\n", + " return (1 / (2 * len(y))) * np.sum((y_hat - y) ** 2)\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", + "# Train\n", + "# Validate\n", + " y_pred = np.dot(X_test.values, theta)\n", + "# Calculate evaluation metrics\n", + "# Store results\n", + "\n", + " theta, losses = gradient_descent(X_train.values, y_train.values, learning_rate)\n", + " mse = sklearn_mse(y_test, y_pred)\n", + " rmse = np.sqrt(mse)\n", + " r2 = r2_score(y_test, y_pred)\n", + " lr_losses.append(losses)\n", + " lr_mse.append(mse)\n", + " lr_rmse.append(rm)\n", + "\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "# ploting\n", + "average_losses = np.mean(lr_losses, axis=0)\n", + "plt.figure(figsize=(10, 6))\n", + "plt.plot(average_losses, label='Average Loss')\n", + "plt.xlabel('Iteration')\n", + "plt.ylabel('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/195/Q2.ipynb b/submissions_extracted/195/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..0d3bbe73fb024adfbaaf61b6fa173478f03f6545 --- /dev/null +++ b/submissions_extracted/195/Q2.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/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", + "#make tensor\n", + "X = x.to(torch)\n", + "\n", + "y = y.to(torch)\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 2. Create TensorDataset objects\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" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 3. Create DataLoaders\n", + "from torch.utils.data import DataLoader\n", + "# DataLoader for training data\n", + "train_loader = DataLoader(\n", + " train_dataset,\n", + " batch_size=32,\n", + " shuffle=True,\n", + "\n", + ")\n", + "# DataLoader for test/validation data\n", + "test_loader = DataLoader(\n", + " test_dataset,\n", + " batch_size=32,\n", + " shuffle=False,)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 4. Print shape of one batch\n", + "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", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your model class here:\n", + "\n", + "import torch\n", + "import torch.nn as nn\n", + "# Create a linear layer: 4input features -> 1 output\n", + "linear = nn.Linear(in_features=4, out_features=1)\n", + "# Example input: batch of 4 samples, each with 3 features\n", + "x = torch.randn(4, 3)\n", + "# Forward through the layer\n", + "y = linear(x)\n", + "print(\"Input shape:\", x.shape)\n", + "print(\"Output shape:\", y.shape)" + ], + "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", + " running_loss = 0.0\n", + " for X_batch, y_batch in train_loader:\n", + " # Move batch to the selected device\n", + " # Forward pass\n", + " # Backward pass & optimization\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: Write your validation loop here:\n", + "import torch\n", + "import torch.nn as nn\n", + "from torch.optim import Adam\n", + "import matplotlib.pyplot as plt\n", + "from sklearn.datasets import load_breast_cancer\n", + "from sklearn.model_selection import train_test_split\n", + "from sklearn.preprocessing import StandardScaler\n", + "from torch.utils.data import TensorDataset\n", + "from torch.utils.data import DataLoader\n", + "data= images\n", + "\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_\n", + "# Standardize the data\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", + "# Create TensorDatasets for training and testing\n", + "train_dataset = TensorDataset(X_train, y_train)\n", + "test_dataset = TensorDataset(X_test, y_test)\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": [ + "# 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", + "num_epochs = 20\n", + "learning_rate = 0.001\n", + "# Model, Criterion, Optimizer\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", + "val_accuracies = []\n", + "print('Starting Training...')\n", + "for epoch in range(num_epochs):\n", + "# Train one epoch\n", + "# Validate\n", + "\n", + " train_losses.append(train_loss)\n", + " val_losses.append(val_loss)\n", + " val_accuracies.append(val_accuracy)\n", + "if (epoch + 1) % 5 == 0:\n", + " print(f'Epoch [{epoch+1}/{num_epochs}], Train Loss: {train_loss:.4f}, val_loss , \"val_accuracy\" , val_accuracy))\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", + "plt.plot(train_losses, label='Train Loss')\n", + "plt.plot(val_losses, label='Validation Loss')\n", + "plt.title('Loss over Epochs')\n", + "plt.xlabel('Epoch')\n", + "plt.ylabel('Loss')\n", + "plt.legend()\n", + "plt.tight_layout()\n", + "plt.show()" + ], + "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/195/Q3.ipynb b/submissions_extracted/195/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..80e9b0d01fc77f418b96fbf7675085931e7ec3ea --- /dev/null +++ b/submissions_extracted/195/Q3.ipynb @@ -0,0 +1,257 @@ +{ + "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", + "# reading data\n", + "import os\n", + "csv_path = os.path.join(path, \"ANON_OWNER/q1-exam-data\")\n", + "\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", + "\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "df.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "\n", + "df.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "\n", + "def check_missing_values(df):\n", + " missing_values = df.isnull().sum()\n", + " print(\"Missing Values per Column:\")\n", + " print(missing_values[missing_values > 0])\n", + " if missing_values.any():\n", + " print(\"\\nHandle Missing Values as needed.\")\n", + " else:\n", + " print(\"\\nNo Missing Values Found.\")\n", + "check_missing_values(df)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "# handiling dups\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", + "\n", + "df.drop_duplicates(inplace=True)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "from sklearn.preprocessing import LabelEncoder\n", + "label_encoders = {}\n", + "for col in categorical_cols:\n", + " le = LabelEncoder()\n", + " df[col] = le.fit_transform(df[col])\n", + " label_encoders[col] = le\n", + "df" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + " # Calculate the majority class baseline\n", + "majority_class = y.value_counts().idxmax()\n", + "baseline_pred = [majority_class] * len(y)\n", + "# Evaluate the baseline\n", + "baseline_accuracy = accuracy_score(y, baseline_pred)\n", + "baseline_precision = precision_score(y, baseline_pred, average='weighted', ze\n", + "baseline_recall = recall_score(y, baseline_pred, average='weighted', zero_div\n", + "baseline_f1 = f1_score(y, baseline_pred, average='weighted', zero_division=0)\n", + "print(f\"Baseline Accuracy (majority class): {baseline_accuracy:.4f}\")\n", + "print(f\"Baseline Precision: {baseline_precision:.4f}\")\n", + "print(f\"Baseline Recall: {baseline_recall:.4f}\")\n", + "print(f\"Baseline F1-Score: {baseline_f1:.4f}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "# spliting\n", + " X = df.drop(\"status\", axis=1).astype(float)\n", + "y = df['status'].astype(float)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:\n", + "n_splits = 5 # K=5 Folds\n", + "# Stratified 5-Fold Cross-Validation, shuffled\n", + "skf = StratifiedKFold(n_splits=n_splits, shuffle=True, random_state=42)\n", + " # Storage for logistic regression results for each fold\n", + "lr_losses = []\n", + "lr_accuracy = []\n", + "lr_precision = []\n", + "lr_recall = []\n", + "lr_f1 = []\n", + "\n", + "for fold_idx, (train_index, test_index) in enumerate(skf.split(X, y)):\n", + " print(f\"\\nFold {fold_idx + 1}/{n_splits}\")\n", + " 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", + " theta, losses = gradient_descent(X_train, y_train, learning_rate=0.5)\n", + " # Validate\n", + " y_pred_proba = sigmoid(np.dot(X_test, theta))\n", + " y_pred = (y_pred_proba >= 0.5).astype(int)\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", + " # Store results\n", + " lr_losses.append(losses)\n", + " lr_accuracy.append(accuracy)\n", + " lr_precision.append(precision)\n", + " lr_recall.append(recall)\n", + " lr_f1.append(f1)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "# ploting\n", + "average_losses = np.mean(lr_losses, axis=0)\n", + "plt.figure(figsize=(10, 6))\n", + "plt.plot(average_losses, label='Average Loss')\n", + "plt.xlabel('Iteration')\n", + "plt.ylabel('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:\n", + "# uh thats what i came up with sorry ^^;\n", + "print(\"the : Golden feature\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/196/Q1.ipynb b/submissions_extracted/196/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..610c6f65b9c3ec7b9bf5f54d03092f8ce7e2f1c7 --- /dev/null +++ b/submissions_extracted/196/Q1.ipynb @@ -0,0 +1,354 @@ +{ + "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 os\n", + "from tqdm import tqdm\n", + "!pip install catboost\n", + "\n", + "%matplotlib inline\n", + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q1-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "csv_path = os.path.join(path, \"Q1_data.csv\")\n", + "\n", + "df = pd.read_csv(csv_path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "df.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "df.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "def check_target_distribution(df, target_column):\n", + " df[target_column].hist(bins=30, edgecolor='black')\n", + "\n", + " plt.title(f\"Target Distribution ({target_column})\")\n", + " plt.xlabel(target_column)\n", + " plt.ylabel(\"Frequency\")\n", + " plt.grid(False)\n", + "\n", + " plt.show()\n", + "\n", + "check_target_distribution(df, \"Delivery_Time\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "df = df.drop(columns=\"Order_ID\", axis=1)\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_columns = [\"Weather\", \"Traffic_Level\", \"Time_of_Day\", \"Courier_Experience_yrs\", \"Delivery_Time\"]\n", + "df_clean = df.dropna(subset=missing_columns).copy()\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": [ + "from sklearn.preprocessing import OneHotEncoder\n", + "import pandas as pd\n", + "\n", + "categorical_cols = df_clean.select_dtypes(include=[\"object\"]).columns\n", + "numerical_cols = df_clean.select_dtypes(exclude=[\"object\"]).columns\n", + "\n", + "if len(categorical_cols) > 0:\n", + " ohe = OneHotEncoder(handle_unknown=\"ignore\", sparse_output=False)\n", + "\n", + " encoded = ohe.fit_transform(df_clean[categorical_cols])\n", + "\n", + " encoded_df = pd.DataFrame(\n", + " encoded,\n", + " columns=ohe.get_feature_names_out(categorical_cols),\n", + " index=df_clean.index\n", + " )\n", + "\n", + " df_clean = pd.concat([df_clean[numerical_cols], encoded_df], axis=1)\n", + "\n", + "df_clean.head()\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "from sklearn.preprocessing import StandardScaler\n", + "\n", + "numerical_cols = df_clean.select_dtypes(include=[\"int64\", \"float64\"]).columns.drop(\"Delivery_Time\") # DON'T SCALE THE TARGET\n", + "\n", + "scaler = StandardScaler()\n", + "df_clean[numerical_cols] = scaler.fit_transform(df_clean[numerical_cols])\n", + "df_clean.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 6: Write your code here:\n", + "# We don't need to balance for this question." + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "X = df_clean.drop(\"Delivery_Time\", axis=1).astype(float)\n", + "y = df_clean['Delivery_Time'].astype(float)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 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_absolute_error\n", + "import numpy as np\n", + "\n", + "X = df_clean.drop(\"Delivery_Time\", axis=1).astype(float)\n", + "y = df_clean[\"Delivery_Time\"].astype(float)\n", + "\n", + "n_splits = 5\n", + "kf = KFold(n_splits=n_splits, shuffle=True, random_state=42)\n", + "\n", + "mae_scores = []\n", + "\n", + "for fold_idx, (train_index, test_index) in enumerate(kf.split(X)):\n", + " print(f\"\\nFold {fold_idx + 1}/{n_splits}\")\n", + "\n", + " X_train, X_test = X.iloc[train_index], X.iloc[test_index]\n", + " y_train, y_test = y.iloc[train_index], y.iloc[test_index]\n", + "\n", + " model = RandomForestRegressor(n_estimators=200, random_state=42)\n", + " model.fit(X_train, y_train)\n", + "\n", + " y_pred = model.predict(X_test)\n", + " mae = mean_absolute_error(y_test, y_pred)\n", + " mae_scores.append(mae)\n", + "\n", + " print(f\"MAE: {mae:.4f}\")\n", + "\n", + "print(\"\\n=== Final Result ===\")\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 matplotlib.pyplot as plt\n", + "import numpy as np\n", + "\n", + "\n", + "importances = model.feature_importances_\n", + "feature_names = X.columns\n", + "\n", + "indices = np.argsort(importances)[::-1]\n", + "\n", + "plt.figure(figsize=(10, 6))\n", + "plt.title(\"Feature Importances\")\n", + "plt.bar(range(len(importances)), importances[indices], align=\"center\")\n", + "plt.xticks(range(len(importances)), feature_names[indices], rotation=45)\n", + "plt.tight_layout()\n", + "plt.show()\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "plt.figure(figsize=(8, 5))\n", + "plt.hist(y_pred, bins=30, color='blue', edgecolor='black')\n", + "plt.title(\"Predicted Delivery Time Histogram\")\n", + "plt.xlabel(\"Predicted Delivery Time\")\n", + "plt.ylabel(\"Frequency\")\n", + "plt.tight_layout()\n", + "plt.show()\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:\n", + "from sklearn.ensemble import RandomForestRegressor\n", + "from sklearn.model_selection import KFold\n", + "from sklearn.metrics import mean_absolute_error\n", + "from catboost import CatBoostRegressor\n", + "import numpy as np\n", + "\n", + "X = df_clean.drop(\"Delivery_Time\", axis=1).astype(float)\n", + "y = df_clean[\"Delivery_Time\"].astype(float)\n", + "\n", + "n_splits = 5\n", + "kf = KFold(n_splits=n_splits, shuffle=True, random_state=42)\n", + "\n", + "mae_scores = []\n", + "\n", + "for fold_idx, (train_index, test_index) in enumerate(kf.split(X)):\n", + " print(f\"\\nFold {fold_idx + 1}/{n_splits}\")\n", + "\n", + " X_train, X_test = X.iloc[train_index], X.iloc[test_index]\n", + " y_train, y_test = y.iloc[train_index], y.iloc[test_index]\n", + "\n", + " rf = RandomForestRegressor(n_estimators=200, random_state=42)\n", + " rf.fit(X_train, y_train)\n", + "\n", + " cb = CatBoostRegressor(\n", + " iterations=500,\n", + " learning_rate=0.05,\n", + " depth=6,\n", + " loss_function=\"MAE\",\n", + " verbose=0,\n", + " random_seed=42\n", + " )\n", + " cb.fit(X_train, y_train)\n", + "\n", + "\n", + " preds_rf = rf.predict(X_test)\n", + " preds_cb = cb.predict(X_test)\n", + "\n", + " preds_avg = (preds_rf + preds_cb) / 2\n", + "\n", + " mae = mean_absolute_error(y_test, preds_avg)\n", + " mae_scores.append(mae)\n", + "\n", + " print(f\"Ensemble MAE: {mae:.4f}\")\n", + "\n", + "print(\"\\n=== Ensemble Final Result ===\")\n", + "print(f\"Average Ensemble MAE across folds: {np.mean(mae_scores):.4f}\")\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/196/Q2.ipynb b/submissions_extracted/196/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..f01a4d47cbb090a7644ff790d28551518c4e5c93 --- /dev/null +++ b/submissions_extracted/196/Q2.ipynb @@ -0,0 +1,323 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q2-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import os\n", + "import pandas as pd\n", + "import numpy as np\n", + "from PIL import Image\n", + "from sklearn.model_selection import train_test_split\n", + "\n", + "# Load Labels\n", + "labels_df = pd.read_csv(os.path.join(path, \"labels.csv\"))\n", + "img_dir = os.path.join(path, \"images\")\n", + "\n", + "images = []\n", + "ages = []\n", + "\n", + "# Load Images and Resize\n", + "print(\"Loading images...\")\n", + "for index, row in labels_df.iterrows():\n", + " img_name = row.iloc[0]\n", + " age = row.iloc[1]\n", + " img_path = os.path.join(img_dir, img_name)\n", + "\n", + " if os.path.exists(img_path):\n", + " img = Image.open(img_path).convert('RGB')\n", + " img_array = np.array(img) / 255.0 # Normalize pixel values to [0, 1]\n", + " images.append(img_array)\n", + " ages.append(age)\n", + "\n", + "X = np.array(images)\n", + "y = np.array(ages)\n", + "\n", + "# Transpose image dimensions to match PyTorch format (N, C, H, W)\n", + "X = np.transpose(X, (0, 3, 1, 2))\n", + "\n", + "# Split Data\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n", + "\n", + "print(f\"X_train shape: {X_train.shape}\")\n", + "print(f\"X_test shape: {X_test.shape}\")\n", + "print(f\"y_train shape: {y_train.shape}\")\n", + "print(f\"y_test shape: {y_test.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 1. Convert Numpy arrays to PyTorch Tensors\n", + "import torch\n", + "from torch.utils.data import TensorDataset, DataLoader\n", + "import matplotlib.pyplot as plt\n", + "import numpy as np\n", + "\n", + "X_train_t = torch.tensor(X_train, dtype=torch.float32)\n", + "X_test_t = torch.tensor(X_test, dtype=torch.float32)\n", + "\n", + "y_train_t = torch.tensor(y_train, dtype=torch.float32)\n", + "y_test_t = torch.tensor(y_test, dtype=torch.float32)\n", + "\n", + "print(\"X_train_t:\", X_train_t.shape, X_train_t.dtype)\n", + "print(\"y_train_t:\", y_train_t.shape, y_train_t.dtype)" + ], + "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" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 3. Create DataLoaders\n", + "train_loader = DataLoader(train_dataset, batch_size=32, shuffle=True)\n", + "test_loader = DataLoader(test_dataset, batch_size=32, shuffle=False)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 4. Print shape of one batch\n", + "X_batch, y_batch = next(iter(train_loader))\n", + "print(\"\\nOne batch shapes:\")\n", + "print(\"X_batch:\", X_batch.shape)\n", + "print(\"y_batch:\", y_batch.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(6):\n", + " img = X_batch[i].permute(1, 2, 0).numpy()\n", + " age = y_batch[i].item()\n", + " plt.subplot(2, 3, i+1)\n", + " plt.imshow(img)\n", + " plt.title(f\"Age: {age:.1f}\")\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", + "import torch.optim as optim\n", + "\n", + "# 1) Model class with 4 linear layers\n", + "class AgeRegressor4Layer(nn.Module):\n", + " def __init__(self, input_dim=3*36*36, h1=256, h2=128, h3=64, output_dim=1):\n", + " super().__init__()\n", + " self.net = nn.Sequential(\n", + " nn.Flatten(),\n", + " nn.Linear(input_dim, h1), # 1\n", + " nn.ReLU(),\n", + " nn.Linear(h1, h2), # 2\n", + " nn.ReLU(),\n", + " nn.Linear(h2, h3), # 3\n", + " nn.ReLU(),\n", + " nn.Linear(h3, output_dim) # 4\n", + " )\n", + "\n", + " def forward(self, x):\n", + " return self.net(x)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your training loop here:\n", + "def train_one_epoch(model, loader, criterion, optimizer, device):\n", + " model.train()\n", + " running_loss = 0.0\n", + " n = 0\n", + "\n", + " for Xb, yb in loader:\n", + " Xb, yb = Xb.to(device), yb.to(device)\n", + "\n", + " optimizer.zero_grad()\n", + " preds = model(Xb)\n", + " loss = criterion(preds, yb)\n", + " loss.backward()\n", + " optimizer.step()\n", + "\n", + " running_loss += loss.item() * Xb.size(0)\n", + " n += Xb.size(0)\n", + "\n", + " return running_loss / n\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your validation loop here:\n", + "def validate_one_epoch(model, loader, criterion, device):\n", + " model.eval()\n", + " running_loss = 0.0\n", + " n = 0\n", + "\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", + "\n", + " running_loss += loss.item() * Xb.size(0)\n", + " n += Xb.size(0)\n", + "\n", + " return running_loss / n\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Define device, model, loss, optimizer:\n", + "device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n", + "model = AgeRegressor4Layer().to(device)\n", + "\n", + "criterion = nn.MSELoss()\n", + "optimizer = optim.Adam(model.parameters(), lr=1e-3)\n", + "\n", + "print(\"Device:\", device)\n", + "print(model)\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Start training for 20 epochs:\n", + "num_epochs = 20\n", + "train_losses, val_losses = [], []\n", + "\n", + "for epoch in range(1, num_epochs + 1):\n", + " tr_loss = train_one_epoch(model, train_loader, criterion, optimizer, device)\n", + " va_loss = validate_one_epoch(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}/{num_epochs} | Train Loss: {tr_loss:.4f} | Val Loss: {va_loss:.4f}\")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "import matplotlib.pyplot as plt\n", + "\n", + "plt.figure(figsize=(8, 5))\n", + "plt.plot(train_losses, label=\"Training 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.tight_layout()\n", + "plt.show()\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2 (Bonus): Write your code here:\n", + "model.eval()\n", + "\n", + "Xb, yb = next(iter(test_loader))\n", + "Xb = Xb.to(device)\n", + "yb = yb.to(device)\n", + "\n", + "with torch.no_grad():\n", + " preds = model(Xb)\n", + "\n", + "n_show = 6\n", + "plt.figure(figsize=(10, 4))\n", + "\n", + "for i in range(n_show):\n", + " img = Xb[i].permute(1, 2, 0).detach().cpu().numpy()\n", + " actual = yb[i].item()\n", + " pred = preds[i].item()\n", + "\n", + " plt.subplot(2, 3, i + 1)\n", + " plt.imshow(img)\n", + " plt.title(f\"Pred: {pred:.1f} | Actual: {actual:.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/196/Q3.ipynb b/submissions_extracted/196/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..9b469fc2ddaf510c3056b6c0e1a2244d247a7207 --- /dev/null +++ b/submissions_extracted/196/Q3.ipynb @@ -0,0 +1,277 @@ +{ + "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 os\n", + "import kagglehub\n", + "!pip install catboost\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", + "df.fillna(df.median(numeric_only=True), inplace=True)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "duplicates = df.duplicated().sum()\n", + "print(f\"Duplicate rows: {duplicates}\")\n", + "df.drop_duplicates(inplace=True)\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", + "df = pd.get_dummies(df, columns=categorical_cols, drop_first=True)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "from sklearn.preprocessing import StandardScaler\n", + "\n", + "features = df.drop(columns=['Target'])\n", + "scaler = StandardScaler()\n", + "scaled_features = scaler.fit_transform(features)\n", + "\n", + "df_scaled = pd.DataFrame(scaled_features, columns=features.columns)\n", + "df_scaled['Target'] = df['Target'].values\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "target_counts = df['Target'].value_counts(normalize=True)\n", + "print(\"Target distribution:\")\n", + "print(target_counts)\n", + "\n", + "if target_counts.min() < 0.4:\n", + " print(\"Target is imbalanced.\")\n", + "else:\n", + " print(\"Target is balanced.\")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "X = df_scaled.drop(columns=['Target'])\n", + "y = df_scaled['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", + "\n", + "skf = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)\n", + "\n", + "\n", + "\n", + "f1_scores = []\n", + "\n", + "for fold, (train_idx, test_idx) in enumerate(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 = CatBoostClassifier(verbose=0, random_state=42)\n", + " model.fit(X_train, y_train)\n", + " y_pred = model.predict(X_test)\n", + "\n", + " score = f1_score(y_test, y_pred)\n", + " f1_scores.append(score)\n", + " print(f\"Fold {fold+1} F1 Score: {score:.4f}\")\n", + "\n", + "print(f\"\\nAverage F1 Score across folds: {sum(f1_scores)/len(f1_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", + "from catboost import CatBoostClassifier\n", + "\n", + "model_full = CatBoostClassifier(verbose=0, random_state=42)\n", + "model_full.fit(X, y)\n", + "\n", + "importances = model_full.get_feature_importance()\n", + "feature_names = X.columns\n", + "\n", + "feat_imp = pd.DataFrame({\n", + " \"feature\": feature_names,\n", + " \"importance\": importances\n", + "}).sort_values(by=\"importance\", ascending=False)\n", + "\n", + "plt.figure(figsize=(10, 6))\n", + "plt.barh(feat_imp[\"feature\"][:10][::-1], feat_imp[\"importance\"][:10][::-1])\n", + "plt.xlabel(\"Importance\")\n", + "plt.title(\"Top 10 Feature Importances\")\n", + "plt.tight_layout()\n", + "plt.show()\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "golden_feature = feat_imp.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", + "from sklearn.metrics import accuracy_score\n", + "\n", + "golden_feature = feat_imp.iloc[0][\"feature\"]\n", + "print(\"Golden Feature:\", golden_feature)\n", + "\n", + "\n", + "X_golden = X[[golden_feature]]\n", + "\n", + "k = 5\n", + "\n", + "kf = StratifiedKFold(n_splits=k, shuffle=True, random_state=42)\n", + "splits = kf.split(X_golden, y)\n", + "\n", + "\n", + "golden_accs = []\n", + "full_accs = []\n", + "\n", + "for train_idx, test_idx in splits:\n", + " X_train_g, X_test_g = X_golden.iloc[train_idx], X_golden.iloc[test_idx]\n", + " y_train, y_test = y.iloc[train_idx], y.iloc[test_idx]\n", + "\n", + "\n", + " model_golden = CatBoostClassifier(verbose=0, random_state=42)\n", + " model_golden.fit(X_train_g, y_train)\n", + " y_pred_g = model_golden.predict(X_test_g)\n", + " golden_accs.append(accuracy_score(y_test, y_pred_g))\n", + "\n", + " X_train_full, X_test_full = X.iloc[train_idx], X.iloc[test_idx]\n", + " model_full_cv = CatBoostClassifier(verbose=0, random_state=42)\n", + " model_full_cv.fit(X_train_full, y_train)\n", + " y_pred_full = model_full_cv.predict(X_test_full)\n", + " full_accs.append(accuracy_score(y_test, y_pred_full))\n", + "\n", + "print(\"\\n=== KFold Accuracy Comparison ===\")\n", + "print(f\"Full Model Accuracy (mean): {np.mean(full_accs):.4f} (+/- {np.std(full_accs):.4f})\")\n", + "print(f\"Golden Feature Accuracy (mean): {np.mean(golden_accs):.4f} (+/- {np.std(golden_accs):.4f})\")\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/197/Q1.ipynb b/submissions_extracted/197/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..7f01689943d597f8118d5a22b803ce22d85e66eb --- /dev/null +++ b/submissions_extracted/197/Q1.ipynb @@ -0,0 +1,317 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q1-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "#Import block (everything in one place):\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, 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", + "#import pandas\n", + "\n", + "import pandas as pd\n", + "\n", + "#use .read_csv function to read the data file (give it the path)\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", + "#print first 5 rows\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "#get a general info about the dataset\n", + "df.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "#use .describe to analyze the data and its mean,min/max, std ...etc\n", + "df.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "#import the matplot library\n", + "import matplotlib.pyplot as plt\n", + "\n", + "#plot target varaible\n", + "\n", + "plt.figure(figsize= (8,5)) #specify the size of the plot\n", + "plt.hist(df['Delivery_Time']) # plot the target column as a histogram\n", + "plt.title('Distibution for the target column') #The title\n", + "plt.xlabel('orders')\n", + "plt.ylabel('Dilevary time (in minutes)')\n", + "plt.legend()\n", + "plt.show()\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "\n", + "#drop the order_id column using\n", + "df.drop(labels='Order_ID',axis=1)\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "# see the missing values\n", + "\n", + "df.isnull().sum() #isnull() checks for null values, Then .sum() sums them up" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "# REmove duplicates using .drop_duplicate method\n", + "\n", + "df.duplicated().sum()\n", + "\n", + "df.drop_duplicates(inplace=True)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "# encode using one hot encoder\n", + "\n", + "#1st: check categorical files:\n", + "df.info() #we have ['Weather','Traffic_Level','Time_of_Day','Vehicle_Type'] as categorical columns (with object Dtype)\n", + "\n", + "categorical_columns = ['Weather','Traffic_Level','Time_of_Day','Vehicle_Type']\n", + "\n", + "\n", + "\n", + "#import one hot incoder\n", + "\n", + "from sklearn.preprocessing import OneHotEncoder,LabelEncoder\n", + "\n", + "\n", + "#initalize it\n", + "le = LabelEncoder() #not this one (I'm putting here as a backup)\n", + "\n", + "encoder = OneHotEncoder() #this one I'm using (to get the bonus)\n", + "\n", + "for column in categorical_columns: #extract one collumn name at a time\n", + " df[column] = le.fit_transform(df[column]) #encode it\n", + "\n", + "df.head() #sanity check" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "\n", + "#apply standard scaling\n", + "\n", + "scalar = StandardScaler()\n", + "\n", + "df['Delivery_Time'] = scalar.fit_transform(df[['Delivery_Time']])" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 6: Write your code here:\n", + "#check target imbalance\n", + "\n", + "#check it using value.counts to check each output and its frequency\n", + "\n", + "df['Delivery_Time'].value_counts()\n", + "#output shows some slight imbalance (some are more frequen '23' where others only 1)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "from sklearn.model_selection import KFold, StratifiedKFold, cross_val_score\n", + "from sklearn.linear_model import LogisticRegression\n", + "import numpy as np\n", + "\n", + "#split into x feature and y:target\n", + "X = df.drop(labels='Delivery_Time',axis=1).drop_duplicates()\n", + "y = df['Delivery_Time'].dropna()\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:\n", + "\n", + "#import models\n", + "from sklearn.ensemble import RandomForestRegressor\n", + "\n", + "#2 split into S_Kfold\n", + "kfold = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)\n", + "\n", + "#3 train model\n", + "\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2 , random_state=42)\n", + "\n", + "# Create Random forest model\n", + "model = RandomForestRegressor()\n", + "\n", + "\n", + "#train it\n", + "model.fit(X_train, y_train)\n", + "\n", + "y_pred = model.predict(X_test)\n", + "\n", + "\n", + "# Evaluation using MAE\n", + "\n", + "from sklearn.metrics import mean_absolute_error\n", + "mae = mean_absolute_error(y_test, y_pred)\n", + "print(\"Mean Absolute Error:\", mae)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "\n", + "#plot feature importance:\n", + "\n", + "importantece = pd.Series(model.feature_importances_, index =X.columns)\n", + "importantece.plot(kind='barh')\n", + "plt.show()\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "#plot predictied dellivary time historgram\n", + "\n", + "plt.figure(figsize= (8,5)) #specify the size of the plot\n", + "plt.hist(y_pred) # plot the target column as a histogram\n", + "plt.title('Distibution for the target column') #The title\n", + "plt.xlabel('orders')\n", + "plt.ylabel('Dilevary time')\n", + "plt.legend()\n", + "plt.show()\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 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/197/Q2.ipynb b/submissions_extracted/197/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..351d092ea9b9d954c8d90c9d9e9c915b6d716e87 --- /dev/null +++ b/submissions_extracted/197/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", + "\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", + "\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", + "#flatten before conversion:\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", + "import torch\n", + "import torch.nn as nn\n", + "from torch.utils.data import DataLoader, TensorDataset\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", + "\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", + "\n", + "#idk tbh" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your model class here:\n", + "\n", + "\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(in_features=input_dim , out_features=hidden_dim) # \n", + "\n", + " # TODO: Define the second linear layer: hidden_dim -> hidden_dim\n", + " self.layer2 = nn.Linear(in_features=hidden_dim, out_features=hidden_dim) # \n", + "\n", + " # TODO: Define the 3rd layer: hidden_dim -> 1 (single value for regression)\n", + " self.layer3 = nn.Linear(in_features=hidden_dim, out_features= 1) # \n", + "\n", + " #4th layer\n", + " self.layer4 = nn.Linear(in_features=input_dim,out_features=hidden_dim)\n", + "\n", + " # TODO: Define ReLU activation\n", + " self.relu = nn.ReLU() # \n", + "\n", + " def forward(self, x):\n", + " # TODO: First hidden layer with ReLU\n", + " a1 = self.relu(self.layer1(x)) # \n", + "\n", + " # TODO: Second hidden layer with ReLU\n", + " a2 = self.relu(self.layer2(a1)) # \n", + "\n", + " # TODO: 3rd layer\n", + " a3 = self.relu(a2) # \n", + "\n", + " #4th layer:\n", + " output = self.relu(a3)\n", + "\n", + "\n", + " return output" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your training loop here:\n", + "\n", + "\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.to(device)\n", + " y_batch = y_batch.to(device).reshape(-1, 1) # Reshape for consistency with output\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) # Use criterion directly\n", + "\n", + " # TODO: Backward pass & optimization\n", + " # Step 1: Clear previous gradients\n", + " # If we don't do this, gradients accumulate from previous batches!\n", + " optimizer.zero_grad()\n", + "\n", + " # Step 2: Compute gradients (backward pass)\n", + " # Calculates how much each weight contributed to the error\n", + " loss.backward()\n", + "\n", + " # Step 3: Update model parameters\n", + " # Adjusts the weights based on the gradients\n", + " optimizer.step()\n", + " running_loss = 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", + "\n", + "def validate(model, criterion, test_loader, device):\n", + " # TODO: Set the model to evaluation mode\n", + " # \n", + " model.eval()\n", + "\n", + " running_loss = 0.0\n", + "\n", + " # TODO: Disable gradient computation using torch.no_grad()\n", + " with torch.no_grad():\n", + " for X_batch, y_batch in test_loader:\n", + " # TODO: Move data to device\n", + " X_batch = X_batch.to(device) # \n", + "\n", + " # [HINT: reshape to (-1, 1)]\n", + " y_batch = y_batch.to(device).reshape(-1, 1)\n", + "\n", + " # TODO: Forward pass - get model predictions\n", + " # \n", + " outputs = model(X_batch)\n", + "\n", + " # TODO: Compute loss using criterion\n", + " # \n", + " loss = criterion(outputs, y_batch)\n", + "\n", + " # Accumulate loss\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", + "\n", + "# TODO: Set up the device (use GPU if available, otherwise CPU)\n", + "# \n", + "device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n", + "\n", + "\n", + "# Model parameters\n", + "input_dim = X_train.shape[1] # Number of tabular features\n", + "hidden_dim = 64 # Design choice (feel free to experiment!)\n", + "\n", + "# TODO: Instantiate the model and move it to the device\n", + "# \n", + "model = NN4Layer(input_dim, hidden_dim).to(device)\n", + "\n", + "# Print the model architecture\n", + "print(\"Model Architecture:\\n\")\n", + "print(model)\n", + "\n", + "# Calculate the total number of trainable parameters\n", + "total_params = sum(p.numel() for p in model.parameters() if p.requires_grad)\n", + "print(f\"\\nTotal trainable parameters: {total_params}\")\n", + "\n", + "\n", + "\n", + "# TODO: Define criterion (loss function) - use MSELoss for regression\n", + "# \n", + "criterion = nn.MSELoss()\n", + "\n", + "\n", + "# Hyperparameters (feel free to experiment!)\n", + "num_epochs = 20\n", + "learning_rate = 0.001\n", + "\n", + "\n", + "# TODO: Define optimizer - use AdamW with the model parameters and learning rate\n", + "\n", + "\n", + "from torch.optim import AdamW\n", + "optimizer = AdamW(model.parameters(), lr=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", + "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", + " # Validate using the validate function\n", + " val_loss = validate(model, criterion, test_loader, device)\n", + "\n", + " train_losses.append(train_loss)\n", + " val_losses.append(val_loss)\n", + "\n", + " print(f'Epoch [{epoch+1}/{num_epochs}], Train Loss: {train_loss:.4f}, Val Loss: {val_loss:.4f}')\n", + "\n", + "print('Training Complete!')" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "import matplotlib.pyplot as plt\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", + "\n", + "\n", + "# Scatter plot: Predicted vs Actual\n", + "plt.figure(figsize=(8, 6))\n", + "\n", + "# Plot: Predicted vs Actual scatter\n", + "plt.scatter(y_test.numpy(), predictions.flatten(), alpha=0.5, s=10, c='steelblue')\n", + "\n", + "# Add perfect prediction line\n", + "min_val = min(y_test.min(), predictions.min())\n", + "max_val = max(y_test.max(), predictions.max())\n", + "plt.plot([min_val, max_val], [min_val, max_val], 'r--', lw=2, label='Perfect Prediction')\n", + "\n", + "plt.xlabel('Actual Price ($)', fontsize=12)\n", + "plt.ylabel('Predicted Price ($)', fontsize=12)\n", + "plt.title('Predicted vs Actual Diamond Prices', fontsize=14)\n", + "plt.legend()\n", + "plt.grid(True, alpha=0.3)\n", + "\n", + "plt.tight_layout()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/197/Q3.ipynb b/submissions_extracted/197/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..613d444220e601598fd84c82977f17176fbc98ce --- /dev/null +++ b/submissions_extracted/197/Q3.ipynb @@ -0,0 +1,246 @@ +{ + "cells": [ + { + "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", + "\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", + "\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", + "\n", + "df.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "\n", + "\n", + "#check for missing values\n", + "df.isnull().sum()\n", + "\n", + "#df.isna().sum()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "\n", + "#check duplicates\n", + "df.duplicated().sum() #No duplicits" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "\n", + "df.info() #No object / strin types\n", + "#therefore no encoding required !!\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "#**Apply feature scaling** to numerical features (Use StandardScaler)\n", + "from sklearn.preprocessing import StandardScaler\n", + "\n", + "scalar = StandardScaler()\n", + "df['P_2'] = scalar.fit_transform(df[['P_2']])\n", + "df\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "\n", + "#I used (normalize=True) and then multiplied it by 100 to get the percentage for each class\n", + "df['Target'].value_counts(normalize = True) * 100 #Yeah there is some form of imbalance !!!\n", + "\n", + "# most of them are 0 (around 75%)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "#if we use it normally we remove the normalizeation and it should output like this\n", + "df['Target'].value_counts()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "\n", + "x = df.drop('Target', axis=1) #retain everything exept the target column (drop it)\n", + "y = df['Target']\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "#! pip install catboost # that needed to be installed" + ], + "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, StratifiedKFold\n", + "from sklearn.metrics import accuracy_score, f1_score\n", + "\n", + "from catboost import CatBoostClassifier\n", + "\n", + "#I opted to use stratified Kfold just to be safe from imbalanced data (maybe the batch has more male/felame ..etc)\n", + "#Shuffled it to indrocue some randomness which help the model generalize better\n", + "kf = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)\n", + "\n", + "scores_accuracy = []\n", + "scores_f1 = []\n", + "\n", + "# 3. Train a **CatBoostClassifier** model\n", + "\n", + "#..........\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", + "plt.figure(figsize=(10, 6))\n", + "plt.barh(range(len(model.feature_importances_)), model.feature_importances_)\n", + "plt.xlabel('Feature Importance')\n", + "plt.ylabel('Features')\n", + "plt.title('Feature Importance')\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "#print Most important feature name (the golden one):\n", + "print(x.columns[1])\n" + ], + "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/198/Q1.ipynb b/submissions_extracted/198/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..1ac5ee806941398f3a7d3afa9283086e2e97befb --- /dev/null +++ b/submissions_extracted/198/Q1.ipynb @@ -0,0 +1,369 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/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", + "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", + "%matplotlib inline" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "# read datset\n", + "\n", + "delivery_path = os.path.join(path, 'Q1_data.csv')\n", + "df_delivery = pd.read_csv(delivery_path)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "# show first rows\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", + "# display dataset info\n", + "\n", + "df_delivery.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "# show statistical description using describe\n", + "df_delivery.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "# plot the target (delivery time)\n", + "\n", + "def check_target_distribution(df, target_column):\n", + " df_delivery[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", + "# plot or print distribution of target variable\n", + "check_target_distribution(df_delivery, \"Delivery_Time\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "# drop order id column\n", + "\n", + "df_delivery.columns.drop(\"Order_ID\")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "# handle missing values\n", + "def check_missing_values(df_delivery):\n", + " missing_values = df_delivery.isnull().sum()\n", + " print(\"Missing Values per Column:\")\n", + " print(missing_values[missing_values > 0])\n", + " if missing_values.any():\n", + " print(\"\\nHandle Missing Values as needed.\")\n", + " else:\n", + " print(\"\\nNo Missing Values Found.\")\n", + "\n", + "check_missing_values(df_delivery)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# fill missing values with mode\n", + "for col in ['Weather', 'Traffic_Level', 'Time_of_Day', 'Courier_Experience_yrs', 'Delivery_Time']:\n", + " df_delivery[col] = df_delivery[col].fillna(df_delivery[col].mode()[0])\n", + "\n", + "# total missing values in whole dataset\n", + "print(\"Missing values remaining:\", df_delivery.isnull().sum().sum())" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "# check and remove duplicates\n", + "\n", + "def check_duplicates(df_delivery):\n", + " duplicates = df_delivery.duplicated().sum()\n", + " print(f\"Number of Duplicate Samples: {duplicates}\")\n", + " if duplicates > 0:\n", + " print(\"Dropping Duplicates...\")\n", + " df_delivery.drop_duplicates(inplace=True)\n", + " print(\"Duplicates Dropped.\")\n", + " else:\n", + " print(\"No Duplicate Samples Found.\")\n", + "\n", + "check_duplicates(df_delivery)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "# encode categorical variables\n", + "\n", + "# Encode categorical columns - converts text to integers\n", + "categorical_cols = ['Weather', 'Traffic_Level', 'Time_of_Day', 'Vehicle_Type', 'Delivery_Time']\n", + "for col in categorical_cols:\n", + " le = LabelEncoder()\n", + " df_delivery[col] = le.fit_transform(df_delivery[col].astype(str))\n", + "\n", + "\n", + "df_delivery.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "# apply feature scaling using standard scaler\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", + "# target imbalance\n", + "def check_target_imbalance(df_delivery, target_column):\n", + " print(\"Target Distribution:\")\n", + " print(df_delivery[target_column].value_counts(normalize=True))\n", + " sns.countplot(x=df_delivery[target_column])\n", + " plt.title(\"Target Distribution\")\n", + " plt.show()\n", + "\n", + "check_target_imbalance(df_delivery, \"Delivery_Time\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "# split dataset\n", + "features = ['Order_ID', 'Distance_km', 'Weather', 'Traffic_Level', 'Time_of_Day', 'Vehicle_Type', 'Preparation_Time_min', 'Courier_Experience_yrs']\n", + "X = df_delivery[features]\n", + "y = df_delivery['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, # shuffle data before splitting -- representative splits\n", + " stratify=y\n", + " )\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", + "\n", + "kfold = KFold(n_splits=5, shuffle=True, random_state=42)\n", + "\n", + "mae_scores = []\n", + "\n", + "scaler = StandardScaler()\n", + "X_train_scaled = scaler.fit_transform(X_train)\n", + "X_test_scaled = scaler.transform(X_test)\n", + "\n", + "# get min and max across all features\n", + "print(f\"\\nScaled ranges - Min: {X_train_scaled.min():.2f}, Max: {X_train_scaled.max():.2f}\")\n", + "# convert numpy array to dataframe with original columns names\n", + "pd.DataFrame(X_train_scaled, columns=X_train.columns).head(3)\n", + "\n", + "# returns indices for train and validation sets for each fold\n", + "for train_idx, val_idx in kfold.split(X_train_scaled):\n", + " # split train into train and validation sets\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 = RandomForestRegressor(n_estimators=100, max_depth=20, random_state=42, n_jobs=-1)\n", + "model.fit(X_train_scaled, y_train) # each tree learns patterns between features and price\n", + "print(\"Model trained!\")\n", + "\n", + "\n", + "# Predict and evaluate\n", + "y_pred = model.predict(X_test_scaled)\n", + "\n", + "# for model accuracy test, evaluate performance\n", + "mae = mean_absolute_error(y_test, y_pred) # between actual and predicted y\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}\")\n", + "\n", + "\n", + "# for model accuracy test, evaluate performance\n", + "mae = mean_absolute_error(y_test, y_pred) # between actual and predicted y\n", + "\n", + "print(f\"MAE: ${mae:,.2f}\")\n", + "\n", + "\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "# Feature importance - which features contribute more to predicting target\n", + "# list of column names used to train model, importance from randon forest for each feature, sort features from most to least important\n", + "feature_importance = pd.DataFrame({\n", + " 'feature': features,\n", + " 'importance': model.feature_importance_\n", + "}).sort_values('importance', ascending=False)\n", + "\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", + "# Ensures the most important feature appears at the top.\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/198/Q2.ipynb b/submissions_extracted/198/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..3f4c95d859b4b80f3bef859eea98ea7743523ec3 --- /dev/null +++ b/submissions_extracted/198/Q2.ipynb @@ -0,0 +1,393 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/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.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": [ + "# 1. Convert Numpy arrays to PyTorch Tensors\n", + "from torch.utils.data import TensorDataset\n", + "from torch.utils.data import DataLoader\n", + "import torch\n", + "X_train = torch.tensor(X_train, dtype=torch.float32)\n", + "X_test = torch.tensor(X_test, dtype=torch.float32)\n", + "y_train = torch.tensor(y_train, dtype=torch.float32)\n", + "y_test = torch.tensor(y_test, dtype=torch.float32)\n" + ], + "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", + "# DataLoader for training data\n", + "train_loader = DataLoader(\n", + " train_dataset,\n", + " batch_size=32,\n", + " shuffle=True,\n", + " num_workers=2\n", + ")\n", + "# DataLoader for test/validation data\n", + "test_loader = DataLoader(\n", + " test_dataset,\n", + " batch_size=32,\n", + " shuffle=False,\n", + " num_workers=2\n", + ")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 4. Print shape of one batch\n", + "\n", + "# Get the first batch from the training DataLoader\n", + "X_batch, y_batch = next(iter(train_loader))\n", + "print(f\"Training batch input shape: {X_batch.shape}\")\n", + "print(f\"Training batch labels shape: {y_batch.shape}\")\n" + ], + "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}\")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your model class here:\n", + "class NN4Layer(nn.Module):\n", + "\n", + " def __init__(self, input_dim, hidden_dim):\n", + "\n", + " super(NN4Layer, self).__init__()\n", + " # input_dim = num of features, hidden_dim = num of neurons\n", + " self.layer1 = nn.Linear(input_dim, hidden_dim)\n", + "\n", + " # hidden_dim = num of neurons, Output for binary classification is 1\n", + " self.layer2 = nn.Linear(hidden_dim,hidden_dim)\n", + "\n", + " # hidden_dim = num of neurons, Output for binary classification is 1\n", + " self.layer3 = nn.Linear(hidden_dim,hidden_dim)\n", + "\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", + " def forward(self, x):\n", + " z1 = self.layer1(x)\n", + " a1 = self.relu(z1)\n", + " z2 = self.layer2(a1)\n", + " a2 = self.sigmoid(z2)\n", + " z3 = self.layer2(a3)\n", + " a3 = self.sigmoid(z3)\n", + " z4 = self.layer2(a3)\n", + " a4 = self.sigmoid(z3)\n", + "\n", + " return a4" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your training loop here:\n", + "def train_one_epoch(model, optimizer, criterion, train_loader, device):\n", + " # Set the model to training mode\n", + " model.train()\n", + "\n", + " running_loss = 0.0\n", + "\n", + " for X_batch, y_batch in train_loader:\n", + " # Move batch to the selected device\n", + " X_batch = X_batch.to(device)\n", + " y_batch = y_batch.view(-1, 1).to(device)\n", + "\n", + " # Forward pass\n", + " outputs = model(X_batch)\n", + " loss = criterion(outputs, y_batch)\n", + "\n", + " # Backward pass & optimization\n", + " optimizer.zero_grad() # Clear previous gradients\n", + " loss.backward() # Compute gradients\n", + " optimizer.step() # Update model parameters\n", + "\n", + " running_loss += loss.item()\n", + "\n", + " # Average loss over all batches\n", + " avg_loss = running_loss / len(train_loader)\n", + "\n", + " return avg_loss\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Instantiate the model\n", + "input_dim = 4 # number of input features\n", + "hidden_dim = 3 # number of hidden neurons\n", + "\n", + "model = NN4Layer(input_dim, hidden_dim)\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}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your validation loop here:\n", + "def validate(model, criterion, test_loader, device):\n", + " # Set the model to evaluation mode\n", + " model.eval()\n", + "\n", + " running_loss = 0.0\n", + " correct = 0\n", + " total = 0\n", + "\n", + " with torch.no_grad(): # Disable gradient computation\n", + " for X_batch, y_batch in test_loader:\n", + " # Move batch to the selected device\n", + " X_batch = X_batch.to(device)\n", + " y_batch = y_batch.view(-1, 1).to(device)\n", + "\n", + " # Forward pass\n", + " outputs = model(X_batch)\n", + " loss = criterion(outputs, y_batch)\n", + " running_loss += loss.item()\n", + "\n", + " # Binary predictions\n", + " predicted = (outputs > 0.5).float()\n", + "\n", + " # Accuracy calculation\n", + " correct += (predicted == y_batch).sum().item()\n", + " total += y_batch.size(0)\n", + "\n", + " avg_loss = running_loss / len(test_loader)\n", + " accuracy = correct / total\n", + "\n", + " return avg_loss, accuracy" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Define device, model, loss, optimizer:\n", + "device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\n", + "print(f\"Using device: {device}\")\n", + "\n", + "input_dim = X_train.shape[1]\n", + "hidden_dim = 10\n", + "model =NN4Layer(input_dim, hidden_dim).to(device)\n", + "\n", + "y_pred = torch.tensor([[0.8], [0.3], [0.6]])\n", + "y_true = torch.tensor([[1.0], [0.0], [1.0]])\n", + "\n", + "\n", + "criterion = nn.BCELoss()\n", + "loss = criterion(y_pred, y_true)\n", + "print(\"Binary Cross Entropy Loss:\", loss.item())\n", + "\n", + "criterion = nn.BCELoss()\n", + "optimizer = Adam(model.parameters(), lr=learning_rate)\n", + "\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", + "\n", + "# Run Training\n", + "train_losses = []\n", + "val_losses = []\n", + "val_accuracies = []\n", + "\n", + "print('Starting Training...')\n", + "for epoch in range(num_epochs):\n", + " # Train one epoch\n", + " train_loss = train_one_epoch(model, optimizer, criterion, train_loader, device)\n", + "\n", + " # Validate\n", + " val_loss, val_accuracy = validate(model, criterion, test_loader, device)\n", + "\n", + " train_losses.append(train_loss)\n", + " val_losses.append(val_loss)\n", + " val_accuracies.append(val_accuracy)\n", + "\n", + " if (epoch + 1) % 5 == 0:\n", + " print(f'Epoch [{epoch+1}/{num_epochs}], Train Loss: {train_loss:.4f}, Val Loss: {val_loss:.4f}, Val Accuracy: {val_accuracy:.4f}')\n", + "\n", + "print('Training Complete!')" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "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/198/Q3.ipynb b/submissions_extracted/198/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..9a0d03be4b9d4d17552c60b95fe28c5310ea6218 --- /dev/null +++ b/submissions_extracted/198/Q3.ipynb @@ -0,0 +1,356 @@ +{ + "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", + "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", + "%pip install kagglehub catboost xgboost tqdm imbalanced-learn -q\n", + "\n", + "%matplotlib inline" + ], + "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", + "print(f\"Dataset shape: {df_anonymized.shape}\")\n", + "df_anonymized.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "df_anonymized.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "df_anonymized.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "# handle missing values\n", + "def check_missing_values(df_anonymized):\n", + " missing_values = df_anonymized.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_anonymized)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# fill empty values\n", + "for col in ['P_2',\t'D_39',\t'B_1',\t'B_2',\t'R_1',\t'S_3',\t'D_41',\t'B_3',\t'D_42',\t'D_43', 'D_137', \t'D_138',\t'D_139',\t'D_140',\t'D_141',\t'D_142',\t'D_143',\t'D_144',\t'D_145'\t]:\n", + " df_anonymized[col]=df_anonymized[col].fillna(df_anonymized[col].mean())" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "def check_duplicates(df_anonymized):\n", + " duplicates = df_anonymized.duplicated().sum()\n", + " print(f\"Number of Duplicate Samples: {duplicates}\")\n", + " if duplicates > 0:\n", + " print(\"Dropping Duplicates...\")\n", + " df_anonymized.drop_duplicates(inplace=True)\n", + " print(\"Duplicates Dropped.\")\n", + " else:\n", + " print(\"No Duplicate Samples Found.\")\n", + "\n", + "check_duplicates(df_anonymized)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "# no categorical variables" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "# apply feature scaling using standard scaler\n", + "\n", + "print('data before scaling:\\n', df_anonymized) #show before scaling\n", + "standard_scaler = StandardScaler() # Instantiate StandardScaler\n", + "data_standard_scaled = standard_scaler.fit_transform(df_anonymized) # 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_anonymized, target_column):\n", + " print(\"Target Distribution:\")\n", + " print(df_anonymized[target_column].value_counts(normalize=True))\n", + " sns.countplot(x=df_anonymized[target_column])\n", + " plt.title(\"Target Distribution\")\n", + " plt.show()\n", + "\n", + "check_target_imbalance(df_anonymized, \"Target\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "# split dataset\n", + "X = df_anonymized.drop(\"Target\", axis=1).astype(float)\n", + "y = df_anonymized['Target'].astype(float)\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, # shuffle data before splitting -- representative splits\n", + " stratify=y\n", + " )\n", + "\n", + "print(f\"Train: {X_train.shape}, Test: {X_test.shape}\")" + ], + "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 KFold\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", + "\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': [], 'f1': []}\n", + "\n", + "for fold_idx, (train_index, test_index) in enumerate(skf.split(X, y)):\n", + " print(f\"\\nFold {fold_idx + 1}/{n_splits}\")\n", + "\n", + " # Get the train & test split for this fold\n", + " X_train, X_test = X.iloc[train_index], X.iloc[test_index]\n", + " y_train, y_test = y.iloc[train_index], y.iloc[test_index]\n", + "\n", + " # Train & Validate Models\n", + " for model_name, model in models.items():\n", + "\n", + " print(f\"Training {model_name}...\")\n", + "\n", + " # Fit the model on train data\n", + " model.fit(X_train, y_train)\n", + "\n", + " # Use the model to predict the test data\n", + " y_pred = model.predict(X_test)\n", + "\n", + " # Calculate evaluation metrics\n", + " accuracy = accuracy_score(y_test, y_pred)\n", + " f1 = f1_score(y_test, y_pred, average='macro') # for multiclass f1 score, you should set the average hyperparameter (\"macro\", \"micro\", \"weighted\")\n", + "\n", + " results[model_name]['accuracy'].append(accuracy)\n", + " results[model_name]['f1'].append(f1)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "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", + "models = {\"CatBoost\": CatBoostRegressor(verbose=0)}\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", + " f1 = f1_score(y_test, y_pred, zero_division=0)\n", + "\n", + "\n", + " # Store results\n", + " lr_f1.append(f1)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "# Feature importance - which features contribute more to predicting target\n", + "# list of column names used to train model, importance from randon forest for each feature, sort features from most to least important\n", + "feature_importance = pd.DataFrame({\n", + " 'feature': features,\n", + " 'importance': model.feature_importance_\n", + "}).sort_values('importance', ascending=False)\n", + "\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", + "# Ensures the most important feature appears at the top.\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/199/Q1.ipynb b/submissions_extracted/199/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..a143af0ece072a43fe9f79be57b0a6b8fd2e5b1c --- /dev/null +++ b/submissions_extracted/199/Q1.ipynb @@ -0,0 +1,281 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "import os\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\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q1-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "csv_path = os.path.join(path, \"Q1_data.csv\")\n", + "\n", + "df = pd.read_csv(csv_path)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "df.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "df.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "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(\"Delivery_Time\")\n", + " plt.grid(False)\n", + "\n", + " plt.show()\n", + "\n", + "check_target_distribution(df, \"Delivery_Time\")\n", + "# if the target is heavily skewed, we might apply a log transform." + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "df.drop(columns=['Order_ID'])" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "def check_missing_values(df):\n", + " missing_values = df.isnull().sum()\n", + " print(\"Missing Values per Column:\")\n", + " print(missing_values[missing_values > 0])\n", + " if missing_values.any():\n", + " print(\"\\nHandle Missing Values as needed.\")\n", + " else:\n", + " print(\"\\nNo Missing Values Found.\")\n", + "we\n", + "check_missing_values(df)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "\n", + "#handeling whether and traffic level using Fill with constant\n", + "df_fill = df.fillna({'weather': 'Unknown', 'Trafficlevel': 'Unknown', 'Time_of_Day': 'Unknown'})\n", + "print(\"\\n2. Fill with constant:\")\n", + "print(df_fill)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "#handeling Courier_Experience_yrs and Delivery_Time using\n", + "df_mean = df.copy()\n", + "df_mean[ 'Courier_Experience_yrs ' ] = df_mean['Courier_Experience_yrs '].fillna(df_mean['Courier_Experience_yrs '].mean())\n", + "df_mean[' Delivery_Time '] = df_mean[' Delivery_Time '].fillna(df_mean[' Delivery_Time '].median())\n", + "print(\"\\n3. Fill with mean/median:\")\n", + "print(df_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)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "#one hot encoder\n", + "#encoder = OneHotEncoder(sparse_output=False)\n", + "#encoded = encoder.fit_transform( 'Weather ')\n", + "#print(\"Original:\", 'Weather ' )\n", + "#print(\"Encoded:\\n\", encoded)\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()\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "scaler = StandardScaler()\n", + "X_train_scaled = scaler.fit_transform()\n", + "X_test_scaled = scaler.transform()\n", + "\n", + "print(f\"\\nScaled ranges - Min: {X_train_scaled.min():.2f}, Max: {scaled.max():.2f}\")\n", + "pd.DataFrame(X_train_scaled, columns=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", + "\n", + "feature_cols = ['Order_Id', 'Distancee_km', 'Weather', 'Traffic_level',\n", + " 'Time_of_Day', 'Vehicle_type', 'Preparation_Time_min', 'Courier_Experience_yrs']\n", + "X = df[feature_cols]\n", + "y = df['Delivery_Time']\n", + "\n", + "# Train-test split (80% train, 20% test)\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n", + "print(f\"Train: {X_train.shape}, Test: {X_test.shape}\")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:\n", + "model = RandomForestRegressor(n_estimators=100, max_depth=20, random_state=42, n_jobs=-1)\n", + "model.fit(X_train_scaled, y_train)\n", + "print(\"Model trained!\")" + ], + "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/199/Q2.ipynb b/submissions_extracted/199/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..0c3c0908914315ae2cb9ae4addc1743e0b3cacbd --- /dev/null +++ b/submissions_extracted/199/Q2.ipynb @@ -0,0 +1,211 @@ +{ + "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 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_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", + "\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_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": [ + "# 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:\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/199/Q3.ipynb b/submissions_extracted/199/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..6ae86feb98654f5c6978242b68b1a8644c7f01c8 --- /dev/null +++ b/submissions_extracted/199/Q3.ipynb @@ -0,0 +1,218 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "import os\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\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", + "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.\")" + ], + "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 need" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "scaler = StandardScaler()\n", + "X_train_scaled = scaler.fit_transform()\n", + "X_test_scaled = scaler.transform()\n", + "\n", + "print(f\"\\nScaled ranges - Min: {X_train_scaled.min():.2f}, Max: {scaled.max():.2f}\")\n", + "pd.DataFrame(X_train_scaled, columns=columns).head(3)" + ], + "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\")\n", + "#soory i'dont know what the target in this case :)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "feature_cols = []\n", + "X = df[feature_cols]\n", + "y = df[]\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}\")" + ], + "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/2/Q1.ipynb b/submissions_extracted/2/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..98a86abe1b197d07efb606f1e60f19267a434a59 --- /dev/null +++ b/submissions_extracted/2/Q1.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/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.join(path, 'Q1_data.csv')\n", + "q1__data = read_csv(Q1_data)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "q1__data.heads()" + ], + "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", + "plt.figure()\n", + "plt.hist(Q1_data.csv['price'].dropna(), bins=50, edgecolor='black')\n", + "plt.title('Delivery Time')\n", + "plt.xlabel('Time')\n", + "plt.ylabel('null')\n", + "plt.show()" + ], + "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", + "#I will be honest that I am horrible at coding , I do not even know how to use Python\n", + "Stage 1's placement did not require me anything to genuinely pass" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "I have attended this as I expected something relevant enough with the theory of mathematics behind the frameworks within this" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "I still find it cool but it really is taking me more effort than I expected to master that" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "I do teach AP Calculus BC in an international school , but thought that AI and Data Science can be cool enough to lure me\n", + "Little did I know how cool things could get , even though it does never pose difficulty but rather time consuming to actually master.\n", + "And I" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 6: Write your code here:\n", + "But here we are , I personally do not think I would want to keep it up here\n", + "But I should thank you for reading the whole thing this far.\n", + "I can say that I have learned so much , not that I do lack interest , but mastering Python hasn't been on my reach due to constraint time...\n", + "But I'm honored.\n", + "And yeah please don't bother grading , I'm much more scared of the fact that you'd read until this point'" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "from sklearn.model_selection import train_test_split, StratifiedKFold, cross_val_score\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:\n", + "#Stratisfied K-fold#" + ], + "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/2/Q2.ipynb b/submissions_extracted/2/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..9016bef5f5c5729497787f8c44388545f75b2411 --- /dev/null +++ b/submissions_extracted/2/Q2.ipynb @@ -0,0 +1,190 @@ +{ + "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" + ], + "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/2/Q3.ipynb b/submissions_extracted/2/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..c97832709061629f03a86d1f40306ca8a3e2a744 --- /dev/null +++ b/submissions_extracted/2/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/20/Q1.ipynb b/submissions_extracted/20/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..d68d0259b0df4f4375f25aedb872c7b3c0c9a68a --- /dev/null +++ b/submissions_extracted/20/Q1.ipynb @@ -0,0 +1,232 @@ +{ + "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", + "csv_path = os.path.join(path, \"Q1_data.csv\")\n", + "\n", + "df = pd.read_csv(csv_path)\n", + "df = df.drop(columns=\"Unnamed: 0\", axis=1)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "\n", + "df.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "df.discribe()" + ], + "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, \"Sales\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "stat_cols = ['hp', 'attack', 'defense', 'sp_attack', 'sp_defense', 'speed']\n", + "\n", + "df_clean = target_column(subset=stat_cols).copy()\n", + "print(f\"Shape after cleaning: {df_clean.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "df_clean['type2'] = df_clean['type2'].fillna('none')" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "\n", + "# No duplicates are there :)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "df_clean['total_stats'] = df_clean[stat_cols].sum(axis=1)\n", + "\n", + "df_clean['attack_defense_ratio'] = df_clean['attack'] / (df_clean['defense'] + 1)\n", + "\n", + "df_clean[['total_stats', 'attack_defense_ratio']].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", + "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()}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:\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", + "plt.figure(figsize=(10, 5))\n", + "plt.hist(df_pokemon[''].dropna(), bins=30, edgecolor='black')\n", + "plt.title('feature importance')\n", + "plt.xlabel('')\n", + "plt.ylabel('')\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:plt.figure(figsize=(10, 5))\n", + "plt.hist(df_pokemon['attack'].dropna(), bins=30, edgecolor='black')\n", + "plt.title('')\n", + "plt.xlabel('')\n", + "plt.ylabel('')\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/20/Q2.ipynb b/submissions_extracted/20/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..2ce4912309f16f7d6176a1b8b5643be835ff6522 --- /dev/null +++ b/submissions_extracted/20/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": [ + "# 1. Convert Numpy arrays to PyTorch Tensors\n", + "\n", + "X_train = torch.tensor(X_train.values, dtype=torch.float32)\n", + "X_test = torch.tensor(X_test.values, dtype=torch.float32)\n", + "y_train = torch.tensor(y_train.values, dtype=torch.long)\n", + "y_test = torch.tensor(y_test.values, dtype=torch.long)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 2. Create TensorDataset objects\n", + "\n", + "train_dataset = TensorDataset(X_train, y_train)\n", + "test_dataset = TensorDataset(X_test, y_test)\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 3. Create DataLoaders\n", + "\n", + "train_loader = DataLoader(train_dataset, batch_size=32, shuffle=True)\n", + "test_loader = DataLoader(test_dataset, batch_size=32, shuffle=False)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 4. Print shape of one batch\n", + "\n", + "print(\"Train dataset:\", len(train_dataset))\n", + "print(\"Test dataset:\", len(test_dataset))\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", + " xs = torch.linspace(-5, 5, steps=100)\n", + " ys = torch.linspace(-5, 5, steps=100)\n", + " x, y = torch.meshgrid(xs, ys, indexing='xy')\n", + " z = torch.sin(torch.sqrt(x * x + y * y))\n", + " ax = plt.axes(projection='3d')\n", + " ax.plot_surface(x.numpy(), y.numpy(), z.numpy())\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", + " # 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", + " 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", + "\n", + "def train_one_epoch(model, optimizer, criterion, train_loader, device):\n", + " # Set the model to training mode\n", + " model.train()\n", + "\n", + " running_loss = 0.0\n", + "\n", + " for X_batch, y_batch in train_loader:\n", + " # Move batch to the selected device\n", + " X_batch = X_batch.to(device) # shape: (batch_size, num_features)\n", + " y_batch = y_batch.to(device) # shape: (batch_size,)\n", + "\n", + " # Forward pass (outputs are logits)\n", + " outputs = model(X_batch) # shape: (batch_size, num_classes)\n", + " loss = criterion(outputs, y_batch)\n", + "\n", + " # Backward pass & optimization\n", + " optimizer.zero_grad() # Clear previous gradients\n", + " loss.backward() # Compute gradients\n", + " optimizer.step() # Update model parameters\n", + "\n", + " running_loss += loss.item()\n", + "\n", + " # Average loss over all batches\n", + " avg_loss = running_loss / len(train_loader)\n", + "\n", + " return avg_loss" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your validation loop here:\n", + "\n", + "def validate(model, criterion, test_loader, device):\n", + " # Set the model to evaluation mode\n", + " model.eval()\n", + "\n", + " running_loss = 0.0\n", + " correct = 0\n", + " total = 0\n", + "\n", + " with torch.no_grad():\n", + " for X_batch, y_batch in test_loader:\n", + " # Move data to device\n", + " X_batch = X_batch.to(device) # shape: (batch_size, num_features)\n", + " y_batch = y_batch.to(device) # shape: (batch_size,)\n", + "\n", + " # Forward pass\n", + " outputs = model(X_batch) # shape: (batch_size, num_classes)\n", + " loss = criterion(outputs, y_batch)\n", + " running_loss += loss.item()\n", + "\n", + " # Apply Softmax to get probabilities\n", + " probabilities = F.softmax(outputs, dim=1)\n", + "\n", + " # Pick the classes with highest probabilities\n", + " predicted = torch.argmax(probabilities, dim=1)\n", + "\n", + " # Accuracy calculation\n", + " correct += (predicted == y_batch).sum().item()\n", + " total += y_batch.size(0)\n", + "\n", + " avg_loss = running_loss / len(test_loader)\n", + " accuracy = correct / total\n", + "\n", + " return avg_loss, accuracy" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Define device, model, loss, optimizer:\n", + "\n", + "# Device setup\n", + "device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n", + "\n", + "# Model parameters\n", + "input_dim = X_train.shape[1] # Number of tabular features\n", + "hidden_dim = 14 # Design choice\n", + "output_dim = 4 # Weather classes: Rainy, Sunny, Cloudy, Snowy\n", + "\n", + "# Instantiate model\n", + "model = NN4Layer(input_dim, hidden_dim, output_dim).to(device)\n", + "\n", + "# Print the model architecture\n", + "print(\"Model Architecture:\\n\")\n", + "print(model)\n", + "\n", + "# Calculate the total number of trainable parameters\n", + "total_params = sum(p.numel() for p in model.parameters() if p.requires_grad)\n", + "print(f\"\\nTotal trainable parameters: {total_params}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Start training for 20 epochs:\n", + "\n", + "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", + "# 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 predictions\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/20/Q3.ipynb b/submissions_extracted/20/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..809e6a26a4280a36bf92f8050fa138b0a61270db --- /dev/null +++ b/submissions_extracted/20/Q3.ipynb @@ -0,0 +1,204 @@ +{ + "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", + "\n", + "df = pd.read_csv(csv_path)\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", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "df.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "\n", + "df.discribe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "\n", + "stat_cols = ['hp', 'attack', 'defense', 'sp_attack', 'sp_defense', 'speed']\n", + "\n", + "df_clean = target_column(subset=stat_cols).copy()\n", + "print(f\"Shape after cleaning: {df_clean.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "df_clean['total_stats'] = df_clean[stat_cols].sum(axis=1)\n", + "\n", + "# Attack/defense ratio: offensive vs defensive Pokemon\n", + "df_clean['attack_defense_ratio'] = df_clean['attack'] / (df_clean['defense'] + 1)\n", + "\n", + "df_clean[['total_stats', 'attack_defense_ratio']].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", + "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()}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:\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", + "plt.figure(figsize=(10, 5))\n", + "plt.hist(df_pokemon[''].dropna(), bins=30, edgecolor='black')\n", + "plt.title('feature importance')\n", + "plt.xlabel('')\n", + "plt.ylabel('')\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_pokemon[''].dropna(), bins=30, edgecolor='black')\n", + "plt.title('the golden feature')\n", + "plt.xlabel('')\n", + "plt.ylabel('')\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/200/Q1.ipynb b/submissions_extracted/200/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..e70b564f5a23c5d207d20dd36d44f62745c39de0 --- /dev/null +++ b/submissions_extracted/200/Q1.ipynb @@ -0,0 +1,283 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import pandas as pd\n", + "import numpy as np\n", + "import matplotlib.pyplot as plt\n", + "import seaborn as sns\n", + "\n", + "import numpy as np\n", + "import pandas as pd\n", + "import matplotlib.pyplot as plt\n", + "import os\n", + "import kagglehub" + ], + "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", + "data_path = os.path.join(path, 'Q1_data.csv')\n", + "data = pd.read_csv(data_path)\n", + "data\n" + ], + "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", + "plt.figure(figsize=(10, 5))\n", + "plt.hist(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", + "data.drop(columns= \"Order_ID\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "missing_percentage = (data.isnull().sum() / len(data)) * 100\n", + "missing_data = pd.DataFrame({\n", + " 'Missing Values': missing_percentage.index,\n", + " 'Percentage': missing_percentage.values\n", + "})\n", + "missing_data = missing_data[missing_data['Percentage']>0].sort_values('Percentage', ascending=False)\n", + "print(missing_data)\n", + "data['Weather']=data['Weather'].fillna(data['Weather'].mode()[0])\n", + "data['Traffic_Level']=data['Traffic_Level'].fillna(data['Traffic_Level'].mode()[0])\n", + "data['Time_of_Day']=data['Time_of_Day'].fillna(data['Time_of_Day'].mode()[0])\n", + "data[\"Courier_Experience_yrs\"]=data[\"Courier_Experience_yrs\"].fillna(data[\"Courier_Experience_yrs\"].mean())\n", + "data[\"Delivery_Time\"]=data[\"Delivery_Time\"].fillna(data[\"Delivery_Time\"].mean())\n", + "missing_data" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "def check_duplicates(df):\n", + " duplicates = df.duplicated().sum()\n", + " print(f\"Number of Duplicate Samples: {duplicates}\")\n", + " if duplicates > 0:\n", + " print(\"Dropping Duplicates...\")\n", + " df.drop_duplicates(inplace=True)\n", + " print(\"Duplicates Dropped.\")\n", + " else:\n", + " print(\"No Duplicate Samples Found.\")\n", + "\n", + "check_duplicates(data)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "from sklearn.preprocessing import LabelEncoder\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(data)\n", + "\n", + "# Transfer all objects to new\n", + "\n", + "categorical_cols = data.select_dtypes(include=[\"object\"]).columns\n", + "for col in categorical_cols:\n", + " print(f\"Encoding column: {col}\")\n", + " le = LabelEncoder()\n", + " data[col] = le.fit_transform(data[col])\n", + "data" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "\n", + "from sklearn.preprocessing import StandardScaler #import StandardScaler\n", + "standard_scaler = StandardScaler() # Instantiate StandardScaler\n", + "data_standard_scaled = standard_scaler.fit_transform(data) # Apply fit_transform\n", + "data_standard_scaled" + ], + "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(data,\"Delivery_Time\")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "X = data.drop(\"Delivery_Time\", axis=1)\n", + "y = data['Delivery_Time']\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "from sklearn.ensemble import RandomForestRegressor\n", + "from sklearn.model_selection import KFold\n", + "from sklearn.metrics import mean_squared_error as sklearn_mse, mean_absolute_error, r2_score\n", + "from sklearn.model_selection import train_test_split" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:\n", + "model = RandomForestRegressor(n_estimators=200),\n", + "kf = KFold(n_splits=5, shuffle=True, random_state=42)\n", + "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", + "\n", + " model.fit(X_train, y_train)\n", + "\n", + " y_pred = model.predict(X_test)\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:\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/200/Q2.ipynb b/submissions_extracted/200/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..a820454e04f7ae4a0746e3bbdef8d28dcf6d65e6 --- /dev/null +++ b/submissions_extracted/200/Q2.ipynb @@ -0,0 +1,308 @@ +{ + "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" + ], + "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(\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", + ")" + ], + "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}\")" + ], + "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):\n", + "\n", + " super(NN3Layer, 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", + "\n", + " self.layer3 = nn.Linear(hidden_dim, hidden_dim,)\n", + "\n", + " self.layer4 = (hidden_dim,1)\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.relu(z2)\n", + " z3 = self.layer3(a2)\n", + " a3 = self.relu(z3)\n", + " z4 = self.layer4(a3)\n", + " a4 = self.sigmoid(z2)\n", + "\n", + "\n", + "\n", + " return a4" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + " z1 = self.layer1(x)\n", + " a1 = self.relu(z1)\n", + " z2 = self.layer2(a1)\n", + " a2 = self.relu(z2)\n", + " z3 = self.layer3(a2)\n", + " a3 = self.relu(z3)\n", + " z4 = self.layer4(a3)\n", + " a2 = self.sigmoid(z2)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your training loop here:\n", + "def train_one_epoch(model, optimizer, criterion, train_loader, device):\n", + " # Set the model to training mode\n", + " model.train()\n", + "\n", + " running_loss = 0.0\n", + "\n", + " for X_batch, y_batch in train_loader:\n", + " # Move batch to the selected device\n", + " X_batch = X_batch.to(device)\n", + " y_batch = y_batch.view(-1, 1).to(device)\n", + "\n", + " # Forward pass\n", + " outputs = model(X_batch)\n", + " loss = criterion(outputs, y_batch)\n", + "\n", + " # Backward pass & optimization\n", + " optimizer.zero_grad() # Clear previous gradients\n", + " loss.backward() # Compute gradients\n", + " optimizer.step() # Update model parameters\n", + "\n", + " running_loss += loss.item()\n", + "\n", + " # Average loss over all batches\n", + " avg_loss = running_loss / len(train_loader)\n", + "\n", + " return avg_loss" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your validation loop here:\n", + "def validate(model, criterion, test_loader, device):\n", + " # Set the model to evaluation mode\n", + " model.eval()\n", + "\n", + " running_loss = 0.0\n", + " correct = 0\n", + " total = 0\n", + "\n", + " with torch.no_grad(): # Disable gradient computation\n", + " for X_batch, y_batch in test_loader:\n", + " # Move batch to the selected device\n", + " X_batch = X_batch.to(device)\n", + " y_batch = y_batch.view(-1, 1).to(device)\n", + "\n", + " # Forward pass\n", + " outputs = model(X_batch)\n", + " loss = criterion(outputs, y_batch)\n", + " running_loss += loss.item()\n", + "\n", + " # Binary predictions\n", + " predicted = (outputs > 0.5).float()\n", + "\n", + " # Accuracy calculation\n", + " correct += (predicted == y_batch).sum().item()\n", + " total += y_batch.size(0)\n", + "\n", + " avg_loss = running_loss / len(test_loader)\n", + " accuracy = correct / total\n", + "\n", + " return avg_loss, accuracy\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Define device, model, loss, optimizer:\n", + "device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n", + "\n", + "optimizer = Adam(model.parameters(), lr=learning_rate)" + ], + "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/200/Q3.ipynb b/submissions_extracted/200/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..8d21b9d3a1f99ecadbe83723d6a334c44952f2dc --- /dev/null +++ b/submissions_extracted/200/Q3.ipynb @@ -0,0 +1,287 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [], + "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 os\n", + "import kagglehub\n", + "\n", + "\n", + "# Download latest version\n", + "\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q3-exam-data\")\n", + "\n", + "\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "data_path = os.path.join(path, 'Q3_data.csv')\n", + "data = pd.read_csv(data_path)\n", + "data\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "data.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "data.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "data.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "missing_percentage = (data.isnull().sum() / len(data)) * 100\n", + "missing_data = pd.DataFrame({\n", + " 'Missing Values': missing_percentage.index,\n", + " 'Percentage': missing_percentage.values\n", + "})\n", + "missing_data = missing_data[missing_data['Percentage']>0].sort_values('Percentage', ascending=False)\n", + "missing_data\n", + "\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(data)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "# Task 4: Write your code here:\n", + "from sklearn.preprocessing import LabelEncoder\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(data)\n", + "\n", + "# Transfer all objects to new\n", + "\n", + "categorical_cols = data.select_dtypes(include=[\"object\"]).columns\n", + "for col in categorical_cols:\n", + " print(f\"Encoding column: {col}\")\n", + " le = LabelEncoder()\n", + " data[col] = le.fit_transform(data[col])\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "from sklearn.preprocessing import StandardScaler #import StandardScaler\n", + "standard_scaler = StandardScaler() # Instantiate StandardScaler\n", + "data_standard_scaled = standard_scaler.fit_transform(data) # Apply fit_transform\n", + "data_standard_scaled" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "# Task 6: Write your code here:\n", + "def check_target_imbalance(df, target_column):\n", + " print(\"Target Distribution:\")\n", + "\n", + " df[target_column].hist() # Yeah you can just do this :)\n", + " plt.show()\n", + "\n", + "check_target_imbalance(data,\"Target\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "X = data.drop(\"Target\", axis=1)\n", + "y = data['Target']" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "#from catboost import CatBoostClassifier\n", + "from sklearn.model_selection import StratifiedKFold\n", + "from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score\n", + "!pip install catboost\n", + "from catboost import CatBoostClassifier" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:\n", + "model = CatBoostClassifier(\n", + " verbose=0,\n", + " n_estimators=320,\n", + " max_depth=4\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", + " # 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", + " model.fit(X_train, y_train)\n", + " y_pred = model.predict(X_test)\n", + "\n", + " accuracy = accuracy_score(y_test, y_pred)\n", + " f1 = f1_score(y_test, y_pred, zero_division=0)\n", + "\n", + "print(f1)\n", + "print(accuracy)\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" + ], + "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/201/Q1.ipynb b/submissions_extracted/201/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..3823f6f1cd9bf38aac7359c3ffa34fd587038fa8 --- /dev/null +++ b/submissions_extracted/201/Q1.ipynb @@ -0,0 +1,304 @@ +{ + "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", + "from sklearn.preprocessing import OneHotEncoder #import OneHotEncoder for bouns :)\n", + "\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": [ + "# Load the dataset\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": [ + "print(f\"Dataset shape: {df_Delivery.shape}\")\n", + "df_Delivery.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Check data types and structure\n", + "df_Delivery.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Descriptive statistics for numerical columns\n", + "df_Delivery.describe()" + ], + "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(df_Delivery, \"Sales\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "df_Delivery = df_Delivery.drop(columns=['Order_ID'])\n", + "df_Delivery.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Drop rows where target (price) or key features are missing - can't predict without them\n", + "print(f\"Before: {df_Delivery.shape}\")\n", + "df_clean = df_Delivery.dropna(subset=[\"Delivery_Time\"])\n", + "print(f\"After dropping missing Delivery_Time: {df_clean.shape}\")\n", + "\n", + "# Fill categorical columns with 'unknown' - missing likely means \"not specified\"\n", + "for col in ['Courier_Experience_yrs']:\n", + " df_clean[col] = df_clean[col].fillna('unknown') #rplace unknwon feld with\n", + "\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())\n", + "\n", + "df_Delivery.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "categorical_cols = [\"Weather\", \"Courier_Experience_yrs\",\"Traffic_Level\", \"Time_of_Day\", \"Vehicle_Type\"]\n", + "\n", + "for col in categorical_cols:\n", + " le = LabelEncoder()\n", + " df_clean[col] = le.fit_transform(df_clean[col].astype(str))\n", + "\n", + "df_clean.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "categorical_cols = [\"Weather\", \"Traffic_Level\", \"Time_of_Day\", \"Vehicle_Type\"]\n", + "\n", + "\n", + "print('data before encoding:\\n', categorical_cols) #show before encoding\n", + "\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\n", + "\n", + "print('\\nData after encoding:\\n', data_onehot_encoded) #show after encoding" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Define features (X) and target (y)\n", + "\n", + "df_clean.info()\n", + "feature_cols = ['Distance_km', 'Weather', \"Traffic_Level\" ,'Time_of_Day', 'Vehicle_Type',\n", + " '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": [ + "print(f\"\\nFeature ranges - Min: {X_train.min().min():.2f}, Max: {X_train.max().max():.2f}\")\n", + "X_train.head(3)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 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" + ], + "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", + "from tqdm import tqdm\n", + "\n", + "# Mean Squared Error in NumPy\n", + "def mean_squared_error(y, y_hat):\n", + " return (1 / (2 * len(y))) * np.sum((y_hat - y) ** 2)\n", + "\n", + "def gradient_descent(X, y, learning_rate, n_iters=500):\n", + " m, n = X.shape # m rows, n columns (dimensions)\n", + " theta = np.zeros(n) # initialize a zeros weight vector with n dimensions\n", + " losses = []\n", + "\n", + " for _ in tqdm(range(n_iters), desc=\"Training Linear Regression\"):\n", + " y_hat = np.dot(X, theta)\n", + " gradient = np.dot(X.T, (y_hat - y)) / m\n", + " theta -= learning_rate * gradient\n", + "\n", + " loss = mean_squared_error(y, y_hat)\n", + " losses.append(loss)\n", + "\n", + " return theta, losses\n", + "\n", + "n_splits = 5 # K=5 Folds\n", + "\n", + "# 5-Fold Cross-Validation, shuffled\n", + "kf = KFold(n_splits=n_splits, shuffle=True, random_state=42)\n", + "\n", + "# Storage for linear regression results for each fold\n", + "lr_losses = []\n", + "lr_mse = []\n", + "lr_rmse = []\n", + "lr_r2 = []\n", + "\n", + "for fold_idx, (train_index, test_index) in enumerate(kf.split(X)):\n", + " print(f\"\\nFold {fold_idx + 1}/{n_splits}\")\n", + "\n", + " X_train, X_test = X.iloc[train_index], X.iloc[test_index]\n", + " y_train, y_test = y.iloc[train_index], y.iloc[test_index]\n", + "\n", + " # Train\n", + " theta, losses = gradient_descent(X_train.values, y_train.values, learning_rate=0.1, n_iters=500)\n", + "\n", + " # Validate\n", + " y_pred = np.dot(X_test.values, theta)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "model = RandomForestRegressor(n_estimators=100, max_depth=20, random_state=42, n_jobs=-1)\n", + "model.fit(X_train_scaled, y_train)\n", + "print(\"Model trained!\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:" + ], + "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/201/Q2.ipynb b/submissions_extracted/201/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..e41d9f25ea970bf399098e6e3d56de5fdd774b52 --- /dev/null +++ b/submissions_extracted/201/Q2.ipynb @@ -0,0 +1,329 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "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 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": [ + "# 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}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 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}\")" + ], + "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": [ + "# 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": [ + "#use 5 layer to make the model most deep and powerfull\n", + "\n", + "class NN5Layer(nn.Module):\n", + "\n", + " def __init__(self, input_dim, hidden_dim, output_dim):\n", + " super(NN5Layer, self).__init__()\n", + "\n", + " self.layer1 = nn.Linear(input_dim, hidden_dim)\n", + "\n", + " self.layer2 = nn.Linear(hidden_dim, hidden_dim)\n", + "\n", + " self.layer3 = nn.Linear(hidden_dim, hidden_dim)\n", + "\n", + " self.layer4 = nn.Linear(hidden_dim, hidden_dim)\n", + "\n", + " self.layer5 = nn.Linear(hidden_dim, output_dim)\n", + "\n", + " # activation function for non-linearity\n", + " self.relu = nn.ReLU()\n", + "\n", + " # Defines how input data flows through the network\n", + " def forward(self, x):\n", + " # Layer 1: TODO\n", + " z1 = self.layer1(x)\n", + " a1 = self.relu(z1)\n", + "\n", + " # Layer 2 TODO\n", + " z2 = self.layer2(a1)\n", + " a2 = self.relu(z2)\n", + "\n", + " # Layer 3 TODO\n", + " z3 = self.layer3(a2)\n", + " a3 = self.relu(z3)\n", + "\n", + " # 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", + "\n", + " return z5" + ], + "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": [ + "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", + "\n", + " # Device setup\n", + "device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n", + "\n", + "# Model parameters\n", + "input_dim = 3 * 32 * 32 # CIFAR-10 images flattened (RGB)\n", + "\n", + "hidden_dim = 64 # Design choice\n", + "\n", + "output_dim = 10 # CIFAR-10 classes\n", + "\n", + "model = NN5Layer(input_dim, hidden_dim, output_dim).to(device)\n", + "\n", + "print(\"Model Architecture:\\n\")\n", + "print(model)\n", + "\n", + "# Calculate the total number of trainable parameters\n", + "total_params = sum(p.numel() for p in model.parameters() if p.requires_grad)\n", + "print(f\"\\nTotal trainable parameters: {total_params}\")\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/201/Q3.ipynb b/submissions_extracted/201/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..84d36628e9d0750ec4c6354dcfca84133fcf9671 --- /dev/null +++ b/submissions_extracted/201/Q3.ipynb @@ -0,0 +1,372 @@ +{ + "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", + "\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", + "# Download latest version\n", + "\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q3-exam-data\")\n", + "\n", + "\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "csv_path = os.path.join(path, \"Q3_data.csv\")\n", + "\n", + "df = pd.read_csv(csv_path)\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": [ + "# cheek the missing values\n", + "\n", + "def check_missing_values(df):\n", + " missing_values = df.isnull().sum()\n", + " print(\"Missing Values per Column:\")\n", + " print(missing_values[missing_values > 0])\n", + " if missing_values.any():\n", + " print(\"\\nHandle Missing Values as needed.\")\n", + " else:\n", + " print(\"\\nNo Missing Values Found.\")\n", + "\n", + "check_missing_values(df)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "from sklearn.preprocessing import LabelEncoder\n", + "\n", + "categorical_cols = df.select_dtypes(include=[\"object\"]).columns\n", + "\n", + "print(\"Categorical Columns:\", list(categorical_cols))\n", + "\n", + "label_encoders = {}\n", + "for col in categorical_cols:\n", + " le = LabelEncoder()\n", + " df[col] = le.fit_transform(df[col])\n", + " label_encoders[col] = le\n", + "\n", + "df" + ], + "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 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": [ + "# 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, \"status\")" + ], + "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": [ + "# 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", + "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", + "# Storage for logistic regression results for each fold\n", + "lr_losses = []\n", + "lr_accuracy = []\n", + "lr_precision = []\n", + "lr_recall = []\n", + "lr_f1 = []\n", + "\n", + "for fold_idx, (train_index, test_index) in enumerate(skf.split(X, y)):\n", + " print(f\"\\nFold {fold_idx + 1}/{n_splits}\")\n", + "\n", + " X_train, X_test = X.iloc[train_index], X.iloc[test_index]\n", + " y_train, y_test = y.iloc[train_index], y.iloc[test_index]\n", + "\n", + " # Train\n", + " theta, losses = gradient_descent(X_train, y_train, learning_rate=0.5, n_iters=500)\n", + "\n", + " # Validate\n", + " y_pred_proba = sigmoid(np.dot(X_test, theta))\n", + " y_pred = (y_pred_proba >= 0.5).astype(int)\n", + "\n", + " # Calculate evaluation metrics\n", + " accuracy = accuracy_score(y_test, y_pred)\n", + " precision = precision_score(y_test, y_pred, zero_division=0)\n", + " recall = recall_score(y_test, y_pred, zero_division=0)\n", + " f1 = f1_score(y_test, y_pred, zero_division=0)\n", + "\n", + " # Store results\n", + " lr_losses.append(losses)\n", + " lr_accuracy.append(accuracy)\n", + " lr_precision.append(precision)\n", + " lr_recall.append(recall)\n", + " lr_f1.append(f1)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "\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", + "\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", + "}" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "all_results = {}\n", + "\n", + "for name in sklearn_models:\n", + " all_results[name] = {'accuracy': [], 'precision': [], 'recall': [], 'f1': []}" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "n_splits = 5 # K\n", + "\n", + "# Stratified 5-Fold Cross-Validation, shuffled\n", + "skf = StratifiedKFold(n_splits=n_splits, shuffle=True, random_state=42)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "#use all LOGISTIC REGRESSION Performance :)\n", + "\n", + "print(\"LOGISTIC REGRESSION Performance:\")\n", + "print(f\" Accuracy: {np.mean(lr_accuracy):.4f}\")\n", + "print(f\" Precision: {np.mean(lr_precision):.4f}\")\n", + "print(f\" Recall: {np.mean(lr_recall):.4f}\")\n", + "print(f\" F1-Score: {np.mean(lr_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/202/Q1.ipynb b/submissions_extracted/202/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..5d0f6cdadc58254785fa387f2823b82e19d18e59 --- /dev/null +++ b/submissions_extracted/202/Q1.ipynb @@ -0,0 +1,301 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "import os\n", + "import pandas as pd\n", + "import matplotlib.pyplot as plt\n", + "import numpy as np\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", + "\n", + "print(f\"Dataset shape: {df_food.shape}\")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "df_food.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "df_food.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "df_food.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "plt.figure(figsize=(10, 5))\n", + "plt.hist(df_food['Delivery_Time'].dropna(), bins=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", + "stat_cols = ['Order_ID']\n", + "\n", + "# Drop rows with missing stat values\n", + "df_clean = df_food.dropna(subset=stat_cols).copy()\n", + "print(f\"Shape after cleaning: {df_clean.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\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_food)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "df_food" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "stat_cols = ['Weather', 'Traffic_Level', 'Time_of_Day', 'Courier_Experience_yrs', 'Delivery_Time']\n", + "\n", + "# Drop rows with missing stat values\n", + "df_clean = df_clean.dropna(subset=stat_cols).copy()\n", + "print(f\"Shape after cleaning: {df_clean.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "def check_duplicates(df):\n", + " 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_food)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "categorical_cols = df_food.select_dtypes(include=[\"object\"]).columns\n", + "\n", + "print(\"Categorical Columns:\", list(categorical_cols))" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "df_food" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "from sklearn.preprocessing import LabelEncoder\n", + "\n", + "label_encoders = {}\n", + "for col in categorical_cols:\n", + " le = LabelEncoder()\n", + " df_food[col] = le.fit_transform(df_food[col])\n", + " label_encoders[col] = le\n", + "df_food\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 6: Write your code here:\n", + "#not needed" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "X = df_food.drop(\"Delivery_Time\", axis=1).astype(float)\n", + "y = df_food['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", + "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", + "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]" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "from sklearn.ensemble import RandomForestClassifier\n", + "model = RandomForestClassifier(n_estimators=100, max_depth=15,\n", + " class_weight='balanced', random_state=42)\n", + "model.fit(train_index, test_index)\n", + "print(\"Model trained!\")" + ], + "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:" + ], + "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/202/Q2.ipynb b/submissions_extracted/202/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..b7d21c941d7e9b5286f8858c8a9ea961fde231ee --- /dev/null +++ b/submissions_extracted/202/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/203/Q1.ipynb b/submissions_extracted/203/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..ee52caec85345c94141ff5a03bf48428c997a586 --- /dev/null +++ b/submissions_extracted/203/Q1.ipynb @@ -0,0 +1,307 @@ +{ + "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 kagglehub\n", + "import pandas as pd\n", + "import torch\n", + "import torch.nn as nn\n", + "from torch.optim import AdamW\n", + "import matplotlib.pyplot as plt\n", + "import torch.nn.functional as F\n", + "from torch.utils.data import DataLoader, TensorDataset\n", + "from sklearn.model_selection import train_test_split\n", + "from sklearn.preprocessing import StandardScaler, LabelEncoder\n", + "\n", + "\n", + "df = pd.read_csv(f\"{path}/Q1_data.csv\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "df.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "df.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "plt.figure(figsize=(10, 5))\n", + "plt.hist(df['Delivery_Time'].dropna(), bins=10, edgecolor='black')\n", + "plt.title('delievery time distribution')\n", + "plt.xlabel('delievry 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=df.drop(\"Order_ID\", axis=1)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "def check_missing_values(df):\n", + " missing_values = df.isnull().sum()\n", + " print(\"Missing Values per Column:\")\n", + " print(missing_values[missing_values > 0])\n", + " if missing_values.any():\n", + " print(\"\\nHandle Missing Values as needed.\")\n", + " else:\n", + " print(\"\\nNo Missing Values Found.\")\n", + "\n", + "check_missing_values(df)\n", + "\n", + "df = df.dropna(subset=['Weather', 'Traffic_Level','Time_of_Day','Courier_Experience_yrs','Delivery_Time'])\n", + "\n", + "def check_missing_values(df):\n", + " missing_values = df.isnull().sum()\n", + " print(\"Missing Values per Column:\")\n", + " print(missing_values[missing_values > 0])\n", + " if missing_values.any():\n", + " print(\"\\nHandle Missing Values as needed.\")\n", + " else:\n", + " print(\"\\nNo Missing Values Found.\")\n", + "\n", + "check_missing_values(df)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "\n", + "def check_duplicates(df_clean):\n", + " duplicates = df_clean.duplicated().sum()\n", + " print(f\"Number of Duplicate Samples: {duplicates}\")\n", + " if duplicates > 0:\n", + " print(\"Dropping Duplicates...\")\n", + " df.drop_duplicates(inplace=True)\n", + " print(\"Duplicates Dropped.\")\n", + " else:\n", + " print(\"No Duplicate Samples Found.\")\n", + "\n", + "check_duplicates(df)\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: 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 5: Write your code here:\n", + "\n", + "numerical_cols = df.select_dtypes(include=[\"int64\", \"float64\"]).columns.drop(\"Delivery_Time\")\n", + "\n", + "scaler = StandardScaler()\n", + "df[numerical_cols] = scaler.fit_transform(df[numerical_cols])\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 6: Write your code here:\n", + "def check_target_imbalance(df, target_column):\n", + " print(\"Target Distribution:\")\n", + "\n", + " df[target_column].hist() # Yeah you can just do this :)\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)\n", + "\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n", + "\n", + "print(X_train.head())" + ], + "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", + "from sklearn.ensemble import RandomForestRegressor\n", + "from sklearn.metrics import mean_squared_error, mean_absolute_error\n", + "\n", + "model = RandomForestRegressor(n_estimators=100, max_depth=20, random_state=42, n_jobs=-1)\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", + " model.fit()\n", + "\n", + " print(\"-\" * 40)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "\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": [], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/203/Q2.ipynb b/submissions_extracted/203/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..f73de1a764b10efd0a0a059a2f47e5e1451c3e67 --- /dev/null +++ b/submissions_extracted/203/Q2.ipynb @@ -0,0 +1,387 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q2-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import os\n", + "import pandas as pd\n", + "import numpy as np\n", + "from PIL import Image\n", + "from sklearn.model_selection import train_test_split\n", + "\n", + "# Load Labels\n", + "labels_df = pd.read_csv(os.path.join(path, \"labels.csv\"))\n", + "img_dir = os.path.join(path, \"images\")\n", + "\n", + "images = []\n", + "ages = []\n", + "\n", + "# Load Images and Resize\n", + "print(\"Loading images...\")\n", + "for index, row in labels_df.iterrows():\n", + " img_name = row.iloc[0]\n", + " age = row.iloc[1]\n", + " img_path = os.path.join(img_dir, img_name)\n", + "\n", + " if os.path.exists(img_path):\n", + " img = Image.open(img_path).convert('RGB')\n", + " img_array = np.array(img) / 255.0 # Normalize pixel values to [0, 1]\n", + " images.append(img_array)\n", + " ages.append(age)\n", + "\n", + "X = np.array(images)\n", + "y = np.array(ages)\n", + "\n", + "# Transpose image dimensions to match PyTorch format (N, C, H, W)\n", + "X = np.transpose(X, (0, 3, 1, 2))\n", + "\n", + "# Split Data\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n", + "\n", + "print(f\"X_train shape: {X_train.shape}\")\n", + "print(f\"X_test shape: {X_test.shape}\")\n", + "print(f\"y_train shape: {y_train.shape}\")\n", + "print(f\"y_test shape: {y_test.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 1. Convert Numpy arrays to PyTorch Tensors\n", + "\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", + "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", + "import kagglehub\n", + "import pandas as pd\n", + "import torch\n", + "import torch.nn as nn\n", + "from torch.optim import AdamW\n", + "import matplotlib.pyplot as plt\n", + "import torch.nn.functional as F\n", + "from torch.utils.data import DataLoader, TensorDataset\n", + "from sklearn.model_selection import train_test_split\n", + "from sklearn.preprocessing import StandardScaler, LabelEncoder\n", + "\n", + "X_train = torch.tensor(X_train, dtype=torch.float32)\n", + "X_test = torch.tensor(X_test, dtype=torch.float32)\n", + "y_train = torch.tensor(y_train, dtype=torch.float32)\n", + "y_test = torch.tensor(y_test, dtype=torch.float32)\n", + "\n" + ], + "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", + "\n", + "# Print dataset sizes\n", + "print(\"Train dataset:\", len(train_dataset))\n", + "print(\"Test dataset:\", len(test_dataset))" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 4. Print shape of one batch\n", + "X_batch, y_batch = next(iter(train_loader))\n", + "print(f\"Training batch input shape: {X_batch.shape}\")\n", + "print(f\"Training batch labels shape: {y_batch.shape}\")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 5. Display sample images\n", + "images, labels = next(iter(train_loader))\n", + "\n", + "# Display the first 6 images in the batch\n", + "plt.figure(figsize=(8, 4))\n", + "\n", + "for i in range(6):\n", + " plt.subplot(2, 3, i + 1)\n", + " 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", + "\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", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your training loop here:\n", + "def train_one_epoch(model, optimizer, criterion, train_loader, device):\n", + " # Set the model to training mode\n", + " model.train()\n", + "\n", + " running_loss = 0.0\n", + "\n", + " for X_batch, y_batch in train_loader:\n", + " # Move batch to the selected device\n", + " X_batch = X_batch.to(device)\n", + " y_batch = y_batch.view(-1, 1).to(device)\n", + "\n", + " # Forward pass\n", + " outputs = model(X_batch)\n", + " loss = criterion(outputs, y_batch)\n", + "\n", + " # Backward pass & optimization\n", + " optimizer.zero_grad() # Clear previous gradients\n", + " loss.backward() # Compute gradients\n", + " optimizer.step() # Update model parameters\n", + "\n", + " running_loss += loss.item()\n", + "\n", + " # Average loss over all batches\n", + " avg_loss = running_loss / len(train_loader)\n", + "\n", + " return avg_loss" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your validation loop here:\n", + "\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.flatten(-1, 1).to(device)\n", + "\n", + " # Forward pass\n", + " outputs = model(X_batch)\n", + " loss = criterion(outputs, y_batch)\n", + " running_loss += loss.item()\n", + "\n", + " # Binary predictions\n", + " predicted = (outputs > 0.5).float()\n", + "\n", + " # Accuracy calculation\n", + " correct += (predicted == y_batch).sum().item()\n", + " total += y_batch.size(0)\n", + "\n", + " avg_loss = running_loss / len(test_loader)\n", + " accuracy = correct / total\n", + "\n", + " return avg_loss, accuracy\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Define device, model, loss, optimizer:\n", + "\n", + "device = 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", + "# 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", + "\n", + "num_epochs = 20\n", + "learning_rate = 0.001\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", + "\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/203/Q3.ipynb b/submissions_extracted/203/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..2ab21ebc93bbb9f1331b1daa67a880d96a27ae31 --- /dev/null +++ b/submissions_extracted/203/Q3.ipynb @@ -0,0 +1,217 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "import pandas as pd\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()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "df.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "\n", + "df.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "missing_values = df.isnull().sum()\n", + "missing_values" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "def check_missing_values(df):\n", + " missing_values = df.isnull().sum()\n", + " print(\"Missing Values per Column:\")\n", + " print(missing_values[missing_values > 0])\n", + " if missing_values.any():\n", + " print(\"\\nHandle Missing Values as needed.\")\n", + " else:\n", + " print(\"\\nNo Missing Values Found.\")\n", + "\n", + "check_missing_values(df)\n", + "\n", + "\n" + ], + "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))" + ], + "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\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", + "\n", + "plt.hist(df['target'].dropna(), bins=50, edgecolor='black')\n", + "plt.title('target Distribution')\n", + "plt.xlabel('target')\n", + "plt.ylabel('Frequency')\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:\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/204/Q1.ipynb b/submissions_extracted/204/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..c343759691f10a0c5b3cfde5e9fc4011a01aafaf --- /dev/null +++ b/submissions_extracted/204/Q1.ipynb @@ -0,0 +1,320 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import numpy as np\n", + "import pandas as pd\n", + "import matplotlib.pyplot as plt\n", + "import os\n", + "import 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, KFold, 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", + "\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(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", + "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", + "numerical_cols = df.select_dtypes(include=[\"number\"]).columns.drop(\"Order_ID\")\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", + "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", + " le = LabelEncoder()\n", + " df[col] = le.fit_transform(df[col])" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "\n", + "standard_scaler = StandardScaler() # Instantiate StandardScaler\n", + "data_standard_scaled = standard_scaler.fit_transform(df)\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", + "\n", + "\n", + "check_target_imbalance(df, \"Order_ID\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "X = df.drop(\"Order_ID\", axis=1).astype(float)\n", + "y = df['Order_ID'].astype(float)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:\n", + "model = RandomForestRegressor(n_estimators=100, max_depth=20, random_state=42)\n", + "\n", + "\n", + "skf = StratifiedKFold(n_splits=2, 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", + " model.fit(X_train, y_train)\n", + "\n", + "\n", + " mae = mean_absolute_error(y_test, y)\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 = pd.DataFrame({\n", + " 'feature': df,\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=(8, 6))\n", + "plt.scatter(y_test, y, 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 Values')\n", + "plt.ylabel('Predicted Values')\n", + "plt.title('Predicted vs Actual')\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/204/Q2.ipynb b/submissions_extracted/204/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..24fb028839d98330ff49adfcb1e51c5d12e1f8f7 --- /dev/null +++ b/submissions_extracted/204/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", + "import torch\n", + "import torch.nn as nn\n", + "import torch.nn.functional as F\n", + "from torch.utils.data import DataLoader\n", + "from torchvision import datasets, transforms\n", + "from torchvision.transforms.functional import to_tensor\n", + "import matplotlib.pyplot as plt\n", + "from torch.utils.data import DataLoader, TensorDataset\n", + "from torch.optim import Adam, AdamW, SGD\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", + "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.values, dtype=torch.float32).view(-1, 1)\n", + "y_test = torch.tensor(y_test.values, dtype=torch.float32).view(-1, 1)\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", + "batch_size = 32\n", + "train_loader = DataLoader(TensorDataset(X_train, y_train), batch_size=batch_size, shuffle=True)\n", + "test_loader = DataLoader(TensorDataset(X_test, y_test), batch_size=batch_size, 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\"Batch X shape: {X_batch.shape}\")\n", + "print(f\"Batch y 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", + " # 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", + " 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(a3)\n", + "\n", + " return output" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your training loop here:\n", + "def train_one_epoch(model, optimizer, criterion, train_loader, device):\n", + " # Set the model to training mode\n", + " model.train()\n", + "\n", + " running_loss = 0.0\n", + "\n", + " for X_batch, y_batch in train_loader:\n", + " # Move batch to the selected device\n", + " X_batch = X_batch.view(X_batch.size(0), -1).to(device)\n", + " y_batch = y_batch.to(device)\n", + "\n", + " # Forward pass\n", + " outputs = model(X_batch) # shape: (batch_size, 10)\n", + " loss = criterion(outputs, y_batch)\n", + "\n", + " # Backward pass & optimization\n", + " optimizer.zero_grad() # Clear previous gradients\n", + " loss.backward() # Compute gradients\n", + " optimizer.step() # Update model parameters\n", + "\n", + " running_loss += loss.item()\n", + "\n", + " # Average loss over all batches\n", + " avg_loss = running_loss / len(train_loader)\n", + "\n", + " return avg_loss" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your validation loop here:\n", + "def validate(model, criterion, test_loader, device):\n", + " # Set the model to evaluation mode\n", + " model.eval()\n", + "\n", + " running_loss = 0.0\n", + " correct = 0\n", + " total = 0\n", + "\n", + " with torch.no_grad():\n", + " for X_batch, y_batch in test_loader:\n", + " # Move data to device\n", + " X_batch = X_batch.view(X_batch.size(0), -1).to(device)\n", + " y_batch = y_batch.to(device)\n", + "\n", + " # Forward pass\n", + " outputs = model(X_batch) # shape: (batch_size, 10)\n", + " loss = criterion(outputs, y_batch)\n", + " running_loss += loss.item()\n", + "\n", + " # Apply Softmax to get probabilities\n", + " probabilities = F.softmax(outputs, dim=1)\n", + "\n", + " # Multiclass predictions\n", + " predicted = torch.argmax(probabilities, dim=1)\n", + "\n", + " # Accuracy calculation\n", + " correct += (predicted == y_batch).sum().item()\n", + " total += y_batch.size(0)\n", + "\n", + " avg_loss = running_loss / len(test_loader)\n", + " accuracy = correct / total\n", + "\n", + " return avg_loss, accuracy" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Define device, model, loss, optimizer:\n", + "device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n", + "\n", + "# Model parameters\n", + "input_dim = 36 * 36 * 3\n", + "hidden_dim = 14\n", + "output_dim = 10\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", + "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:\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/204/Q3.ipynb b/submissions_extracted/204/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..837cc16e883af991d7385cb26836fc847e36246c --- /dev/null +++ b/submissions_extracted/204/Q3.ipynb @@ -0,0 +1,271 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "#i will import every thing cuz i have no time\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, KFold, 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", + "!pip install catboost\n", + "\n", + "\n", + "\n", + "# Download latest version\n", + "\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q3-exam-data\")\n", + "\n", + "\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "df = pd.read_csv(path + \"/Q3_data.csv\")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "df.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "df.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "def check_missing_values(df):\n", + " missing_values = df.isnull().sum()\n", + " print(\"Missing Values per Column:\")\n", + " print(missing_values[missing_values > 0])\n", + " if missing_values.any():\n", + " print(\"\\nHandle Missing Values as needed.\")\n", + " else:\n", + " print(\"\\nNo Missing Values Found.\")\n", + "\n", + "check_missing_values(df)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "def check_duplicates(df):\n", + " duplicates = df.duplicated().sum()\n", + " print(f\"Number of Duplicate Samples: {duplicates}\")\n", + " if duplicates > 0:\n", + " print(\"Dropping Duplicates...\")\n", + " df.drop_duplicates(inplace=True)\n", + " print(\"Duplicates Dropped.\")\n", + " else:\n", + " print(\"No Duplicate Samples Found.\")\n", + "\n", + "check_duplicates(df)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "categorical_cols = df.select_dtypes(include=['object']).columns\n", + "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": [ + "# Task 4: Write your code here:\n", + "standard_scaler = StandardScaler() # Instantiate StandardScaler\n", + "data_standard_scaled = standard_scaler.fit_transform(df)\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):\n", + " print(\"Target Distribution:\")\n", + " print(df.value_counts(normalize=True))\n", + "\n", + "\n", + "check_target_imbalance(df)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "X_train, X_test, y_train, y_test = train_test_split(\n", + " X, y, test_size=0.2, random_state=42, stratify=y\n", + ")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:\n", + "model = CatBoostClassifier()\n", + "model.fit(X_train, y_train)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "feature_importance = pd.DataFrame({\n", + " 'feature': df,\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/205/Q1.ipynb b/submissions_extracted/205/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..8a5071102ce004b191e9df4c9e40bc6a6106e963 --- /dev/null +++ b/submissions_extracted/205/Q1.ipynb @@ -0,0 +1,325 @@ +{ + "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 the packages\n", + "import os\n", + "import pandas as pd\n", + "import matplotlib.pyplot as plt\n", + "from sklearn.preprocessing import OneHotEncoder #import OneHotEncoder\n", + "from sklearn.preprocessing import StandardScaler #import StandardScaler\n", + "\n", + "\n", + "\n", + "# Load the CSV file\n", + "df_Delivery = pd.read_csv(os.path.join(path , \"Q1_data.csv\"))\n", + "\n", + "print(f\"Shape: {df_Delivery.shape}\") # we want to know the number of rows and columns = (1663 columns) , (9 rows)\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() # know the number of non null values for each features" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "df_Delivery.describe() # show the mean , min , max ..etc" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "\n", + "# Attack distribution\n", + "plt.figure(figsize=(10, 5))\n", + "plt.hist(df_Delivery['Delivery_Time'].dropna(), bins=30, edgecolor='black')\n", + "plt.title('Delivery Time Distribution')\n", + "plt.xlabel('Delivery Time')\n", + "plt.ylabel('Frequency')\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "id = \"Order_ID\"\n", + "\n", + "df_clean = df_Delivery.drop(id, axis=1)\n", + "\n", + "print(f\"Shape: {df_clean.shape}\") # to check\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "# Missing values\n", + "print(\"Missing values:\")\n", + "print(df_clean.isnull().sum())" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "df_very_clean = df_clean.dropna().copy()\n", + "print(f\"Shape after cleaning: {df_very_clean.shape}\")\n", + "\n", + "print(df_very_clean.isnull().sum()) # to check" + ], + "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", + " 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_very_clean)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "import numpy as np\n", + "\n", + "def one_hot_encode(y, num_classes):\n", + " y = np.array(y)\n", + " m = len(y)\n", + " # 1. Create a grid of all zeros (num_samples, num_classes)\n", + " one_hot = np.zeros((m, num_classes))\n", + "\n", + " # 2. Go through each sample one by one\n", + " for i in range(m):\n", + " # Identify which class this sample belongs to\n", + " class_label = int(y[i])\n", + "\n", + " # In this row (i), set the specific class column to 1\n", + " one_hot[i, class_label] = 1\n", + "\n", + " return one_hot\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "\n", + "\n", + "from sklearn.preprocessing import LabelEncoder #import LabelEncoder\n", + "\n", + "le = LabelEncoder() # Instantiate LabelEncoder\n", + "categories[\"Weather\"] = le.fit_transform(categories[\"Weather\"])# Apply fit_transform to the column\n", + "categories[\"Traffic_Level\"] = le.fit_transform(categories[\"Traffic_Level\"])\n", + "categories[\"Time_of_Day\"] = le.fit_transform(categories[\"Time_of_Day\"])\n", + "categories[\"Vehicle_Type\"] = le.fit_transform(categories[\"Vehicle_Type\"])\n", + "categories.head()\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "\n", + "data_for_scale = pd.DataFrame(categories)\n", + "\n", + "\n", + "print(\"Before scaling:\")\n", + "data_for_scale" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "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:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "feature_cols = [\"Weather\",\"Traffic_Level\",\"Time_of_Day\",\"Courier_Experience_yrs\",\"Distance_km\",\"Vehicle_Type\"\"Preparation_Time_min\"]\n", + "X = data_standard_scaled[feature_cols]\n", + "y = data_standard_scaled['Delivery_Time']" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:\n", + "#2\n", + "\n", + "from sklearn.model_selection import KFold , cross_val_score\n", + "from sklearn.linear_model import LogisticRegression\n", + "\n", + "\n", + "# KFold Cross-Validation\n", + "kfold = KFold(n_splits=5, shuffle=True, random_state=42)\n", + "model = LogisticRegression()\n", + "\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})\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "#3\n", + "\n", + "from sklearn.ensemble import RandomForestClassifier\n", + "\n", + "\n", + "models = { \"CatBoost\": RandomForestClassifier(\n", + " n_estimators=200,\n", + " max_depth=10\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: 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/205/Q2.ipynb b/submissions_extracted/205/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..f98a172ea219d228fb615abedcc27ac6d66a5170 --- /dev/null +++ b/submissions_extracted/205/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", + "import torch\n", + "from torch.utils.data import DataLoader, TensorDataset\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", + "# Create Dataloaders to train and test data in batches\n", + "train_loader = DataLoader(train_dataset, batch_size=32, shuffle=True)\n", + "test_loader = DataLoader(test_dataset, batch_size=32, shuffle=False)\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 4. Print shape of one batch\n", + "\n", + "# Get the first batch from the training DataLoader\n", + "X_batch, y_batch = next(iter(train_loader))\n", + "print(f\"Training batch input shape: {X_batch.shape}\")\n", + "print(f\"Training batch labels shape: {y_batch.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 5. Display sample images\n", + "import matplotlib.pyplot as plt\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", + " 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 layer: hidden layer -> hidden layer\n", + " self.layer3 = nn.Linear(hidden_dim, hidden_dim)\n", + "\n", + " # output layer: hidden layer -> output layer\n", + " self.layer3 = nn.Linear(hidden_dim, output_dim)\n", + "\n", + " # ReLU activation for non-linearity in hidden layers\n", + " self.relu = nn.ReLU()\n", + " # Defines how input data flows through the network\n", + " def forward(self, x):\n", + " # First hidden layer\n", + " a1 = self.relu(self.layer1(x))\n", + "\n", + " # Second hidden layer\n", + " a2 = self.relu(self.layer2(a1))\n", + "\n", + " # Third hidden layer\n", + " a3 = self.relu(self.layer3(a2))\n", + "\n", + " # Output layer (raw scores / logits)\n", + " output = self.layer4(a3) # we said we'll use softmax, where is it? ¯\\(ツ)/¯\n", + "\n", + " return output" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your training loop here:\n", + "\n", + "def train_one_epoch(model, optimizer, criterion, train_loader, device):\n", + " # Set the model to training mode\n", + " model.train()\n", + "\n", + " running_loss = 0.0\n", + "\n", + " for X_batch, y_batch in train_loader:\n", + " # Move batch to the selected device\n", + " X_batch = X_batch.to(device) # shape: (batch_size, num_features)\n", + " y_batch = y_batch.to(device) # shape: (batch_size,)\n", + "\n", + " # Forward pass (outputs are logits)\n", + " outputs = model(X_batch) # shape: (batch_size, num_classes)\n", + " loss = criterion(outputs, y_batch)\n", + "\n", + " # Backward pass & optimization\n", + " optimizer.zero_grad() # Clear previous gradients\n", + " loss.backward() # Compute gradients\n", + " optimizer.step() # Update model parameters\n", + "\n", + " running_loss += loss.item()\n", + "\n", + " # Average loss over all batches\n", + " avg_loss = running_loss / len(train_loader)\n", + "\n", + " return avg_loss" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your validation loop here:\n", + "\n", + "def validate(model, criterion, test_loader, device):\n", + " # Set the model to evaluation mode\n", + " model.eval()\n", + "\n", + " running_loss = 0.0\n", + " correct = 0\n", + " total = 0\n", + "\n", + " with torch.no_grad():\n", + " for X_batch, y_batch in test_loader:\n", + " # Move data to device\n", + " X_batch = X_batch.to(device) # shape: (batch_size, num_features)\n", + " y_batch = y_batch.to(device) # shape: (batch_size,)\n", + "\n", + " # Forward pass\n", + " outputs = model(X_batch) # shape: (batch_size, num_classes)\n", + " loss = criterion(outputs, y_batch)\n", + " running_loss += loss.item()\n", + "\n", + " # Apply Softmax to get probabilities\n", + " probabilities = F.softmax(outputs, dim=1)\n", + "\n", + " # Pick the classes with highest probabilities\n", + " predicted = torch.argmax(probabilities, dim=1)\n", + "\n", + " # Accuracy calculation\n", + " correct += (predicted == y_batch).sum().item()\n", + " total += y_batch.size(0)\n", + "\n", + " avg_loss = running_loss / len(test_loader)\n", + " accuracy = correct / total\n", + "\n", + " return avg_loss, accuracy" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Define device, model, loss, optimizer:\n", + "from torch.optim import AdamW\n", + "\n", + "# Device setup\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 = 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", + "\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 = AdamW(model.parameters(), learning_rate)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Start training for 20 epochs:\n", + "\n", + "num_epochs = 20\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:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/205/Q3.ipynb b/submissions_extracted/205/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..04ae4b4cac6bc077b3dad0276fb982a817e4cdb4 --- /dev/null +++ b/submissions_extracted/205/Q3.ipynb @@ -0,0 +1,292 @@ +{ + "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", + "import matplotlib.pyplot as plt\n", + "from sklearn.preprocessing import OneHotEncoder #import OneHotEncoder\n", + "from sklearn.preprocessing import StandardScaler #import StandardScaler\n", + "\n", + "df_Anonymized_Data = pd.read_csv(os.path.join(path , \"Q3_data.csv\"))\n", + "\n", + "print(f\"Shape: {df_Anonymized_Data.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "df_Anonymized_Data.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "df_Anonymized_Data.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "df_Anonymized_Data.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "print(\"Missing values:\")\n", + "print(df_Anonymized_Data.isnull().sum())" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "df_clean_Anonymized_Data = df_Anonymized_Data.dropna().copy()\n", + "print(df_clean_Anonymized_Data.isnull().sum())#to check" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: 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", + " 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_Anonymized_Data)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "# No need to encode the data because it's all numbers" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "\n", + "standard_scaler = StandardScaler() # Instantiate StandardScaler\n", + "data_standard_scaled = standard_scaler.fit_transform(df_clean_Anonymized_Data) # Apply fit_transform\n", + "\n", + "print('\\nData after scaling:\\n', data_standard_scaled) #show after scaling" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "\n", + "# 1. Is the target imbalanced?\n", + "def check_target_imbalance(df, target_column):\n", + " print(\"Target Distribution:\")\n", + "\n", + " df[target_column].hist() # Yeah you can just do this :)\n", + " plt.show()\n", + "\n", + "check_target_imbalance(df_clean_Anonymized_Data, \"Anonymized_Data\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "from sklearn.model_selection import train_test_split\n", + "\n", + "X_train, X_test, y_train, y_test = train_test_split(\n", + " X, y, test_size=0.2, random_state=42\n", + ")\n" + ], + "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 , cross_val_score\n", + "from sklearn.linear_model import LogisticRegression\n", + "\n", + "\n", + "# KFold Cross-Validation\n", + "kfold = KFold(n_splits=5, shuffle=True, random_state=42)\n", + "model = LogisticRegression()\n", + "\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})\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "%pip install kagglehub catboost xgboost tqdm imbalanced-learn -q\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "#3\n", + "from tqdm import tqdm\n", + "from catboost import CatBoostClassifier\n", + "\n", + "models = { \"CatBoost\": CatBoostClassifier(\n", + " verbose=0,\n", + " n_estimators=200,\n", + " max_depth=4\n", + " )}\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "#4\n", + "from sklearn.metrics import accuracy_score, f1_score\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')" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "#5\n", + "import numpy as np\n", + "\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/206/Q1.ipynb b/submissions_extracted/206/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..ffe175078afdd23ddd767d2bbd7a12adee77116a --- /dev/null +++ b/submissions_extracted/206/Q1.ipynb @@ -0,0 +1,313 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "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", + "import pandas as pd\n", + "import os\n", + "\n", + "food_delivery_path = os.path.join(path, 'Q1_data.csv')\n", + "\n", + "df_food_delivery = pd.read_csv(food_delivery_path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "df_food_delivery.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "df_food_delivery.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "df_food_delivery.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "import matplotlib.pyplot as plt # import the pylot to plot the target\n", + "def check_target_distribution(df, target_column):\n", + " df[target_column].hist(bins=20, edgecolor='black')\n", + "\n", + " plt.title(f\"Target Distribution ({'Delivery_Time'})\")\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, \"Delivery_Time\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "df_food_delivery.drop('Order_ID' ,axis=1 , inplace=True) # droping the Order_id\n", + "df_food_delivery" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "def check_missing_values(df): # to check if we have missing value\n", + " missing_values = df.isnull().sum()\n", + " print(\"Missing Values per Column:\")\n", + " print(missing_values[missing_values > 0])\n", + " if missing_values.any():\n", + " print(\"\\nHandle Missing Values as needed.\")\n", + " else:\n", + " print(\"\\nNo Missing Values Found.\")\n", + "\n", + "check_missing_values(df_food_delivery)\n", + "\n", + "for col in ['Weather', 'Traffic_Level', 'Time_of_Day']: #here we fill the string col with unknown\n", + " df_food_delivery[col] = df_food_delivery[col].fillna('unknown')\n", + "\n", + "for col in ['Courier_Experience_yrs', 'Delivery_Time']: #here we fill the int col with mode\n", + " df_food_delivery[col] = df_food_delivery[col].fillna(df_food_delivery[col].mode()[0])\n", + "\n", + "print(\"Missing values remaining:\", df_food_delivery.isnull().sum().sum()) #here to check if we still have missing value" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "def check_duplicates(df): #check if we have duplicates if we have drop it\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_food_delivery)" + ], + "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", + "categorical_cols = ['Weather', 'Traffic_Level', 'Time_of_Day','Vehicle_Type']\n", + "for col in categorical_cols:\n", + " le = LabelEncoder()\n", + " df_food_delivery[col] = le.fit_transform(df_food_delivery[col])\n", + "\n", + "df_food_delivery.head()" + ], + "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", + "features = df_food_delivery.columns.drop(\"Delivery_Time\") #we won't SCALE THE TARGET\n", + "print(features)\n", + "scaler = StandardScaler()\n", + "df_food_delivery[features] = scaler.fit_transform(df_food_delivery[features])\n", + "\n", + "df_food_delivery.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 6: Write your code here:\n", + "import matplotlib.pyplot as plt # import the pylot to plot the target\n", + "import seaborn as sns\n", + "def check_target_imbalance(df, target_column):\n", + " print(\"Target Distribution:\")\n", + " print(df[target_column].value_counts(normalize=True))\n", + " sns.countplot(x=df[target_column])\n", + " plt.title(\"Target Distribution\")\n", + " plt.show()\n", + "\n", + "check_target_imbalance(df_food_delivery, \"Delivery_Time\") # the target is balnce so just k fold" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "features = df_food_delivery.columns.drop(\"Delivery_Time\")\n", + "X= df_food_delivery[features]\n", + "y= df_food_delivery[\"Delivery_Time\"]\n", + "\n", + "\n", + "X" + ], + "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.ensemble import RandomForestRegressor\n", + "from sklearn.metrics import mean_absolute_error\n", + "\n", + "\n", + "\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):\n", + "\n", + " X_fold_train, X_fold_val = X.iloc[train_idx], X.iloc[val_idx]\n", + " y_fold_train, y_fold_val = y.iloc[train_idx], y.iloc[val_idx]\n", + "\n", + " model = RandomForestRegressor(n_estimators=200)\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", + "\n", + "print(f\"5-Fold df_food_delivery Results:\")\n", + "for x in mae_scores:\n", + " sum1=0\n", + " sum1 += x\n", + "average_mae = sum1 / 5\n", + "print(f\"MAE: ${average_mae:,.2f}\")\n", + "\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "# Feature importance\n", + "features = df_food_delivery.columns.drop(\"Delivery_Time\")\n", + "feature_importance = pd.DataFrame({\n", + " 'feature': features,\n", + " 'importance': model.feature_importances_\n", + "}).sort_values('importance', ascending=False)\n", + "\n", + "plt.figure(figsize=(10, 6))\n", + "plt.barh(feature_importance['feature'], feature_importance['importance'])\n", + "plt.xlabel('Importance')\n", + "plt.title('Feature Importance')\n", + "plt.gca().invert_yaxis()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "def check_target_distribution(df, target_column):\n", + " df[target_column].hist(bins=20, edgecolor='black')\n", + "\n", + " plt.title(f\"Target Distribution ({'Delivery_Time'})\")\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, \"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/206/Q2.ipynb b/submissions_extracted/206/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..e7c329557f1b877b7ca2359b01e7f84e2c0aee00 --- /dev/null +++ b/submissions_extracted/206/Q2.ipynb @@ -0,0 +1,354 @@ +{ + "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 torch.utils.data import TensorDataset\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", + "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" + ], + "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", + "X_batch, y_batch = next(iter(train_loader))\n", + "print(f\"Training batch input shape: {X_batch.shape}\")\n", + "print(f\"Training batch labels shape: {y_batch.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 5. Display sample images\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your model class here:\n", + "import torch.nn as nn\n", + "\n", + "class NN4Layer(nn.Module):\n", + "\n", + " def __init__(self, input_dim, hidden_dim):\n", + " super(NN4Layer, self).__init__()\n", + "\n", + " # First linear layer: input features -> hidden layer\n", + " self.layer1 = nn.Linear(input_dim, hidden_dim)\n", + "\n", + " # Second linear layer: hidden layer -> hidden layer\n", + " self.layer2 = nn.Linear(hidden_dim, hidden_dim)\n", + "\n", + " # Third linear layer: hidden layer -> hidden layer\n", + " self.layer3 = nn.Linear(hidden_dim, hidden_dim)\n", + "\n", + " # Output layer: hidden layer -> age\n", + " self.layer4 = nn.Linear(hidden_dim, 1)\n", + "\n", + " # ReLU activation for non-linearity\n", + " self.relu = nn.ReLU()\n", + "\n", + " # Defines how input data flows through the network\n", + " def forward(self, x):\n", + " # First hidden layer\n", + " a1 = self.relu(self.layer1(x))\n", + "\n", + " # Second hidden layer\n", + " a2 = self.relu(self.layer2(a1))\n", + "\n", + " # Third hidden layer\n", + " a3 = self.relu(self.layer3(a2))\n", + "\n", + " # Output layer\n", + " output = self.layer4(a3)\n", + "\n", + " return output" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your training loop here:\n", + "\n", + "def train_one_epoch(model, optimizer, criterion, train_loader, device):\n", + " # Set the model to training mode\n", + " model.train()\n", + "\n", + " running_loss = 0.0\n", + "\n", + " for X_batch, y_batch in train_loader:\n", + " # Move batch to the selected device\n", + " X_batch = X_batch.view(X_batch.size(0), -1).to(device) # shape: (batch_size, num_features)\n", + " y_batch = y_batch.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.view(X_batch.size(0), -1).to(device) # shape: (batch_size, num_features)\n", + " y_batch = y_batch.to(device) # shape: (batch_size, 1) # 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", + "# Model parameters\n", + "input_dim = 3 * 36 * 36 # Number of tabular features\n", + "hidden_dim = 36 # 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", + "criterion = nn.MSELoss()\n", + "\n", + "learning_rate = 0.001\n", + "\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", + "# Hyperparameters\n", + "num_epochs = 20\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "# Run Training\n", + "import matplotlib.pyplot as plt\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!')\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/206/Q3.ipynb b/submissions_extracted/206/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..e29808a7dc76b48b1849cdcf9a26f1519087a279 --- /dev/null +++ b/submissions_extracted/206/Q3.ipynb @@ -0,0 +1,285 @@ +{ + "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", + "Golden_Feature_path = os.path.join(path, 'Q3_data.csv')\n", + "\n", + "df_Golden_Feature = pd.read_csv(Golden_Feature_path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "df_Golden_Feature.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "df_Golden_Feature.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "df_Golden_Feature.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): # to check if we have missing value\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_Golden_Feature)\n", + "\n", + "for col in df_Golden_Feature.columns: #here we fill the int col with mode\n", + " df_Golden_Feature[col] = df_Golden_Feature[col].fillna(df_Golden_Feature[col].mode()[0])\n", + "\n", + "print(\"Missing values remaining:\", df_Golden_Feature.isnull().sum().sum()) #here to check if we still have missing value\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "def check_duplicates(df): #check if we have duplicates if we have drop it\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_Golden_Feature)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "#there isn't any categorical variables in df_Golden_Feature" + ], + "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", + "features = df_Golden_Feature.columns.drop(\"Target\") #we won't SCALE THE TARGET\n", + "print(features)\n", + "scaler = StandardScaler()\n", + "df_Golden_Feature[features] = scaler.fit_transform(df_Golden_Feature[features])\n", + "\n", + "df_Golden_Feature.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "import matplotlib.pyplot as plt # import the pylot to plot the target\n", + "import seaborn as sns\n", + "def check_target_imbalance(df, target_column):\n", + " print(\"Target Distribution:\")\n", + " print(df[target_column].value_counts(normalize=True))\n", + " sns.countplot(x=df[target_column])\n", + " plt.title(\"Target Distribution\")\n", + " plt.show()\n", + "\n", + "check_target_imbalance(df_Golden_Feature, \"Target\") # the target is imbalnce" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "features = df_Golden_Feature.columns.drop(\"Target\")\n", + "X= df_Golden_Feature[features]\n", + "y= df_Golden_Feature[\"Target\"]\n", + "\n", + "\n", + "X" + ], + "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", + "\n", + "\n", + "\n", + "strfold = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)\n", + "\n", + "lr_accuracy = []\n", + "lr_f1 = []\n", + "\n", + "for train_idx, val_idx in strfold.split(X,y):\n", + "\n", + " X_fold_train, X_fold_val = X.iloc[train_idx], X.iloc[val_idx]\n", + " y_fold_train, y_fold_val = y.iloc[train_idx], y.iloc[val_idx]\n", + "\n", + " model = CatBoostClassifier(\n", + " verbose=0,\n", + " n_estimators=320,\n", + " max_depth=4\n", + " )\n", + "\n", + " model.fit(X_fold_train, y_fold_train)\n", + " y_fold_pred = model.predict(X_fold_val)\n", + "\n", + " accuracy = accuracy_score(y_fold_val, y_fold_pred)\n", + " f1 = f1_score(y_fold_val, y_fold_pred, zero_division=0)\n", + "\n", + " lr_accuracy.append(accuracy)\n", + " lr_f1.append(f1)\n", + "\n", + "\n", + "print(f\"5-Fold df_Golden_Feature Results:\")\n", + "for x in lr_accuracy:\n", + " sum1=0\n", + " sum1 += x\n", + "average_accuracy = sum1 / 5\n", + "\n", + "for x in lr_f1:\n", + " sum1=0\n", + " sum1 += x\n", + "average_f1 = sum1 / 5\n", + "\n", + "print(f\"accuracy: {average_accuracy:,.2f}\")\n", + "print(f\"f1: {average_f1:,.2f}\")\n", + "\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "features = df_Golden_Feature.columns.drop(\"Target\")\n", + "feature_importance = pd.DataFrame({\n", + " 'feature': features,\n", + " 'importance': model.feature_importances_\n", + "}).sort_values('importance', ascending=False)\n", + "\n", + "plt.figure(figsize=(30, 20))\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() # the golden_feature is P_2" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "print('the golden_feature is P_2')" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/207/Q1.ipynb b/submissions_extracted/207/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..f89997ac9c2080ca42474bbb43771604a99b1c10 --- /dev/null +++ b/submissions_extracted/207/Q1.ipynb @@ -0,0 +1,173 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q1-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 6: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/207/Q2.ipynb b/submissions_extracted/207/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..c8937ff34d658b6340ef5c82e1d71e84083e0ea8 --- /dev/null +++ b/submissions_extracted/207/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/207/Q3.ipynb b/submissions_extracted/207/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..c97832709061629f03a86d1f40306ca8a3e2a744 --- /dev/null +++ b/submissions_extracted/207/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/208/Q1.ipynb b/submissions_extracted/208/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..37cc9916059dd1a736b4da43a7476031315a2c53 --- /dev/null +++ b/submissions_extracted/208/Q1.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/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", + "import seaborn as sns\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", + "# 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" + ], + "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": [ + "print(\"Missing values:\")\n", + "print(df_Q1.isnull().sum())" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "# Time distribution (target variable)\n", + "#plt.figure(figsize=(10, 5))\n", + "#plt.hist(df_Q1['Delivery_time'].dropna(), bins=50, edgecolor='black')\n", + "#plt.title('Delivery Time Distribution')\n", + "#plt.xlabel('time')\n", + "#plt.ylabel('Time')\n", + "#plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "df_Q1 = df_Q1.drop(columns=['Order_ID'])\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", + "df_Q1['Weather'] = df_Q1['Weather'].fillna('unknown')\n", + "df_Q1['Traffic_Level'] = df_Q1['Traffic_Level'].fillna('unkown')\n", + "df_Q1['Time_of_Day'] = df_Q1['Time_of_Day'].fillna('unknown')\n", + "df_Q1['Courier_Experience_yrs'] = df_Q1['Courier_Experience_yrs'].fillna(df_Q1['Courier_Experience_yrs'].median())\n", + "df_Q1['Delivery_Time'] = df_Q1['Delivery_Time'].fillna(df_Q1['Delivery_Time'].mode()[0])\n", + "\n", + "\n", + "# I am not sure how to explain it but what happend is that the code when I ran it the first it worked fine but when I re ran it to double check\n", + "# it had already filled them so now it causes an error but you can see that .sum() prints 0\n", + "# so if you want to check uncomment the code and run it once. or like the whole code at once\n", + "# that is what happend to me\n", + "print(df_Q1.head())\n", + "print(\"Missing values:\")\n", + "print(df_Q1.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_Q1)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "le = LabelEncoder()\n", + "\n", + "df_Q1['Weather'] = le.fit_transform(df_Q1['Weather'])\n", + "df_Q1['Traffic_Level'] = le.fit_transform(df_Q1['Traffic_Level'])\n", + "df_Q1['Time_of_Day'] = le.fit_transform(df_Q1['Time_of_Day'])\n", + "df_Q1['Vehicle_Type'] = le.fit_transform(df_Q1['Vehicle_Type'])\n", + "print(df_Q1.head())" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "from sklearn.preprocessing import StandardScaler #import StandardScaler\n", + "feature_cols = ['Distance_km', 'Weather', 'Traffic_Level', 'Time_of_Day',\n", + " 'Vehicle_Type', 'Preparation_Time_min', 'Courier_Experience_yrs']\n", + "X = df_Q1[feature_cols]\n", + "y = df_Q1['Delivery_Time']\n", + "\n", + " #show before scaling\n", + "standard_scaler = StandardScaler() # Instantiate StandardScaler\n", + "data_standard_scaled = standard_scaler.fit_transform(X) # 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", + " 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", + "# I have spillted them before the scaling so I don't scale the output\n", + "print(y)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:\n", + "from sklearn.metrics import mean_absolute_error\n", + "from sklearn.model_selection import train_test_split, KFold\n", + "from sklearn.metrics import classification_report, confusion_matrix, accuracy_score\n", + "X_train, X_test, y_train, y_test = train_test_split(data_standard_scaled, y, test_size=0.2, random_state=42, stratify=y)\n", + "\n", + "model = RandomForestClassifier(n_estimators=100, max_depth=15,\n", + " class_weight='balanced', random_state=42)\n", + "model.fit(X_train, y_train)\n", + "print(\"Model trained!\")\n", + "\n", + "y_pred = model.predict(X_test)\n", + "\n", + "kfold = KFold(n_splits=5, shuffle=True, random_state=42)\n", + "\n", + "mae_scores = []\n", + "\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", + "\n", + "mae_scores = np.array(mae_scores)\n", + "\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": [ + "# Task 1: Write your code here:\n", + "# Feature importance\n", + "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(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/208/Q2.ipynb b/submissions_extracted/208/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..055e4fae2d654b59b84bee79ec3ace471acc270d --- /dev/null +++ b/submissions_extracted/208/Q2.ipynb @@ -0,0 +1,433 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q2-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import os\n", + "import pandas as pd\n", + "import numpy as np\n", + "from PIL import Image\n", + "from sklearn.model_selection import train_test_split\n", + "import 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", + "X_train = torch.tensor(X_train)\n", + "y_train = torch.tensor(y_train)\n", + "X_test = torch.tensor(X_test)\n", + "y_test = torch.tensor(y_test)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 2. Create TensorDataset objects\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": [ + "# 3. Create DataLoaders\n", + "\n", + "train_loader = DataLoader(\n", + " train_dataset,\n", + " batch_size=32,\n", + " shuffle=True,\n", + " num_workers=2\n", + ")\n", + "# DataLoader for test/validation data\n", + "test_loader = DataLoader(\n", + " test_dataset,\n", + " batch_size=32,\n", + " shuffle=False,\n", + " num_workers=2\n", + ")\n", + "# Get the first batch from the training DataLoader\n", + "X_batch, y_batch = next(iter(train_loader))\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 4. Print shape of one batch\n", + "print(f\"Training batch input shape: {X_batch.shape}\")\n", + "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", + "# Get one batch of images and labels\n", + "images, labels = next(iter(train_loader))\n", + "\n", + "# Display the first 6 images in the batch\n", + "plt.figure(figsize=(8, 4))\n", + "\n", + "for i in range(6):\n", + " plt.subplot(2, 3, i + 1)\n", + " plt.imshow(images[i].squeeze(), cmap='gray')\n", + " plt.title(f\"Label: {labels[i].item()}\")\n", + " plt.axis('off')\n", + "\n", + "plt.tight_layout()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your model class here:\n", + "class NN4Layer(nn.Module):\n", + "\n", + " def __init__(self, input_dim, hidden_dim, output_dim):\n", + " super(NN4Layer, self).__init__()\n", + "\n", + " # First linear layer: input features -> hidden layer\n", + " self.layer1 = nn.Linear(input_dim, hidden_dim)\n", + "\n", + " # Second linear layer: hidden layer -> hidden layer\n", + " self.layer2 = nn.Linear(hidden_dim, hidden_dim)\n", + "\n", + " # Output layer: hidden layer -> number of classes (logits)\n", + " self.layer3 = nn.Linear(hidden_dim, hidden_dim)\n", + "\n", + " self.layer4 = nn.linear(hidden_dim, output_dim)\n", + "\n", + " # 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.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" + ], + "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 = 10\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 = Adam(model.parameters(), learning_rate)\n", + "\n", + "train_losses = []\n", + "val_losses = []\n", + "val_accuracies = []\n", + "\n", + "print('Starting Training...')\n", + "for epoch in range(num_epochs):\n", + " # Train one epoch\n", + " train_loss = train_one_epoch(model, optimizer, criterion, train_loader, device)\n", + "\n", + " # Validate\n", + " val_loss, 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='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/208/Q3.ipynb b/submissions_extracted/208/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..cab3f56681c0415957734f6683c89d78da09cc99 --- /dev/null +++ b/submissions_extracted/208/Q3.ipynb @@ -0,0 +1,285 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "\n", + "\n", + "# Download latest version\n", + "\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q3-exam-data\")\n", + "\n", + "\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "import numpy as np\n", + "import pandas as pd\n", + "import matplotlib.pyplot as plt\n", + "import os\n", + "import kagglehub\n", + "import pandas as pd\n", + "import numpy as np\n", + "import matplotlib.pyplot as plt\n", + "import seaborn as sns\n", + "import kagglehub\n", + "import os\n", + "from tqdm import tqdm\n", + "\n", + "%matplotlib inline\n", + "from sklearn.model_selection import 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.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.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", + "\n", + "import warnings\n", + "warnings.filterwarnings('ignore')\n", + "# Task 1: Write your code here:\n", + "Q3_path = os.path.join(path, 'Q3_data.csv')\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()\n", + "print(\"Missing values:\")\n", + "print(df_Q3.isnull().sum())" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "df_Q3['P_2'] = df_Q3['P_2'].fillna(df_Q3['P_2'].median())\n", + "df_Q3['B_2'] = df_Q3['B_2'].fillna(df_Q3['B_2'].median())\n", + "df_Q3['S_3'] = df_Q3['S_3'].fillna(df_Q3['S_3'].median())\n", + "df_Q3['D_41'] = df_Q3['D_41'].fillna(df_Q3['D_41'].median())\n", + "df_Q3['B_3'] = df_Q3['B_3'].fillna(df_Q3['B_3'].median())\n", + "feature_cols = ['P_2', 'D_39', 'B_1', 'B_2','R_1','S_3','D_41','B_3']\n", + "\n", + "X = df_Q3[feature_cols]\n", + "y = df_Q3['Target']\n", + "print(X)\n", + "print(\"Missing values:\")\n", + "print(X.isnull().sum())" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "def check_duplicates(df):\n", + " duplicates = df.duplicated().sum()\n", + " print(f\"Number of Duplicate Samples: {duplicates}\")\n", + " if duplicates > 0:\n", + " print(\"Dropping Duplicates...\")\n", + " df.drop_duplicates(inplace=True)\n", + " print(\"Duplicates Dropped.\")\n", + " else:\n", + " print(\"No Duplicate Samples Found.\")\n", + "\n", + "check_duplicates(X)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "\n", + "# No need" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "from sklearn.preprocessing import StandardScaler #import StandardScaler\n", + "standard_scaler = StandardScaler() # Instantiate StandardScaler\n", + "data_standard_scaled = standard_scaler.fit_transform(X) # Apply fit_transform\n", + "\n", + "print('\\nData after scaling:\\n', data_standard_scaled) #show after scaling" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "def check_target_imbalance(df, target_column):\n", + " print(\"Target Distribution:\")\n", + " print(df[target_column].value_counts(normalize=True))\n", + " sns.countplot(x=df[target_column])\n", + " plt.title(\"Target Distribution\")\n", + " plt.show()\n", + "\n", + "check_target_imbalance(df_Q3, \"Target\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "# the data was splitted before the scaling so we won't scale the output" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:\n", + "from sklearn.metrics import mean_absolute_error\n", + "from sklearn.model_selection import train_test_split, KFold\n", + "from catboost import CatBoostRegressor , CatBoostClassifier\n", + "X_train, X_test, y_train, y_test = train_test_split(data_standard_scaled, y, test_size=0.2, random_state=42, stratify=y)\n", + "\n", + "model = CatBoostClassifier(verbose=0)\n", + "model.fit(X_train, y_train)\n", + "print(\"Model trained!\")\n", + "\n", + "y_pred = model.predict(X_test)\n", + "\n", + "kfold = KFold(n_splits=5, shuffle=True, random_state=42)\n", + "\n", + "\n", + "\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", + "\n", + "\n", + "y_pred = model.predict(X_test)\n", + "\n", + "\n", + "print(f\"5-Fold CV Results:\")\n", + "print(f\"Accuracy: {accuracy_score(y_test, y_pred):.4f}\\n\")\n", + "print(f\"F1-score: {f1_score(y_test, y_pred, zero_division=0):.4f}\")\n", + "\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "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(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/209/Q1.ipynb b/submissions_extracted/209/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..6bec4c06398704baaadb70a2a25b0d06ea5b6fc4 --- /dev/null +++ b/submissions_extracted/209/Q1.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/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 os\n", + "\n", + "# Part 1: Read Data\n", + "# Task 1: Read the dataset\n", + "print(os.listdir(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: Inspect the first few rows\n", + "print(\"First 5 rows of the dataset:\")\n", + "print(df.head())" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Display dataset information\n", + "print(\"\\nDataset Information:\")\n", + "print(df.info())" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Show statistical description\n", + "print(\"\\nStatistical Description:\")\n", + "print(df.describe())\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Plot the target distribution (delivery_time)\n", + "plt.figure(figsize=(10, 6))\n", + "plt.hist(df['Delivery_Time'], bins=30, color='skyblue', edgecolor='black')\n", + "plt.title('Delivery Time Distribution')\n", + "plt.xlabel('Delivery Time (minutes)')\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_clean = df.copy()\n", + "df_clean.drop(columns=['Order_ID'])\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Handle missing values appropriately\n", + "def check_missing_values(df_clean):\n", + " missing_values = df_clean.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", + "# Handle missing values (drop rows with missing target values)\n", + "df_cleaned = df_clean.dropna(subset=['Delivery_Time'])\n", + "print(df_cleaned.Delivery_Time.isna().sum())\n", + "\n", + "df_clean = df_clean.dropna(subset=['Delivery_Time']).copy()\n", + "\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Do we have duplicate samples?\n", + "def check_duplicates(df_clean):\n", + " duplicates = df_clean.duplicated().sum()\n", + " print(f\"Number of Duplicate Samples: {duplicates}\")\n", + " if duplicates > 0:\n", + " print(\"Dropping Duplicates...\")\n", + " df_clean.drop_duplicates(inplace=True)\n", + " print(\"Duplicates Dropped.\")\n", + " else:\n", + " print(\"No Duplicate Samples Found.\")\n", + "\n", + "check_duplicates(df)\n", + "\n", + "df_clean = df_clean.drop_duplicates().copy()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Encode ALL object columns\n", + "from sklearn.preprocessing import LabelEncoder\n", + "\n", + "obj_cols = df_clean.select_dtypes(include=['object']).columns\n", + "\n", + "for col in obj_cols:\n", + " df_clean[col] = df_clean[col].fillna('Unknown').astype(str)\n", + " le = LabelEncoder()\n", + " df_clean[col] = le.fit_transform(df_clean[col])\n", + "\n", + " print(df_clean.select_dtypes(include=['object']).columns) # لازم تطلع Index([]) يعني ما فيه نصوص\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "# I did it when Prepare Data for Modeling (in the bottom)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 6: Write your code here: NO Need" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1\n", + "\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 into X and y\n", + "X = df_clean.drop('Delivery_Time', axis=1)\n", + "y = df_clean['Delivery_Time']\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: KFold + RandomForest + MAE (avg across folds)\n", + "\n", + "# 2) KFold\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_fold = X.iloc[train_idx]\n", + " X_val_fold = X.iloc[val_idx]\n", + " y_train_fold = y.iloc[train_idx]\n", + " y_val_fold = y.iloc[val_idx]\n", + "\n", + " model = RandomForestRegressor(n_estimators=200, random_state=42, n_jobs=-1)\n", + " model.fit(X_train_fold, y_train_fold)\n", + "\n", + " preds = model.predict(X_val_fold)\n", + " mae_scores.append(mean_absolute_error(y_val_fold, preds))\n", + "\n", + "print(\"Average MAE across all folds:\", np.mean(mae_scores))\n", + "\n", + "" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import matplotlib.pyplot as plt\n", + "import numpy as np\n", + "\n", + "# Train final model on full data (for plots)\n", + "final_model = RandomForestRegressor(n_estimators=200, random_state=42, n_jobs=-1)\n", + "final_model.fit(X, y)\n", + "\n", + "# 1) Feature importance\n", + "importances = final_model.feature_importances_\n", + "feat_names = X.columns\n", + "\n", + "sorted_idx = np.argsort(importances)[::-1]\n", + "\n", + "plt.figure(figsize=(10, 5))\n", + "plt.bar(feat_names[sorted_idx], importances[sorted_idx])\n", + "plt.title(\"Feature Importance (RandomForest)\")\n", + "plt.xticks(rotation=45, ha='right')\n", + "plt.tight_layout()\n", + "plt.show()\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Predicted delivery time histogram\n", + "y_pred_all = final_model.predict(X)\n", + "\n", + "plt.figure(figsize=(10, 5))\n", + "plt.hist(y_pred_all, bins=30, edgecolor='black')\n", + "plt.title(\"Predicted Delivery Time Distribution\")\n", + "plt.xlabel(\"Predicted Delivery Time\")\n", + "plt.ylabel(\"Frequency\")\n", + "plt.tight_layout()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "!pip install catboost\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Ensemble (RandomForest + CatBost) with KFold + MAE on averaged preds\n", + "\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", + "\n", + "X = df_clean.drop('Delivery_Time', axis=1)\n", + "y = df_clean['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_fold = X.iloc[train_idx]\n", + " X_val_fold = X.iloc[val_idx]\n", + " y_train_fold = y.iloc[train_idx]\n", + " y_val_fold = y.iloc[val_idx]\n", + "\n", + " rf = RandomForestRegressor(n_estimators=200, random_state=42, n_jobs=-1)\n", + " cb = CatBoostRegressor(\n", + " iterations=500,\n", + " learning_rate=0.1,\n", + " depth=6,\n", + " loss_function=\"MAE\",\n", + " random_seed=42,\n", + " verbose=False\n", + " )\n", + "\n", + " rf.fit(X_train_fold, y_train_fold)\n", + " cb.fit(X_train_fold, y_train_fold)\n", + "\n", + " pred_rf = rf.predict(X_val_fold)\n", + " pred_cb = cb.predict(X_val_fold)\n", + "\n", + " pred_avg = (pred_rf + pred_cb) / 2.0\n", + " mae_scores.append(mean_absolute_error(y_val_fold, pred_avg))\n", + "\n", + "print(\"Average MAE across all folds (Ensemble):\", np.mean(mae_scores))\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/209/Q2.ipynb b/submissions_extracted/209/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..4ccf915651cca1b22a6efc6b854e7821d9435c6b --- /dev/null +++ b/submissions_extracted/209/Q2.ipynb @@ -0,0 +1,308 @@ +{ + "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 torch.utils.data import TensorDataset, DataLoader\n", + "import matplotlib.pyplot as plt\n", + "\n", + "X_train_t = torch.tensor(X_train, dtype=torch.float32)\n", + "X_test_t = torch.tensor(X_test, dtype=torch.float32)\n", + "\n", + "y_train_t = torch.tensor(y_train, dtype=torch.float32).view(-1, 1)\n", + "y_test_t = torch.tensor(y_test, dtype=torch.float32).view(-1, 1)\n", + "\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 2. Create TensorDataset objects\n", + "train_ds = TensorDataset(X_train_t, y_train_t)\n", + "test_ds = TensorDataset(X_test_t, y_test_t)\n", + "\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 3. Create DataLoaders\n", + "train_loader = DataLoader(train_ds, batch_size=32, shuffle=True)\n", + "test_loader = DataLoader(test_ds, batch_size=32, shuffle=False)\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 4. Print shape of one batch\n", + "xb, yb = next(iter(train_loader))\n", + "print(\"X batch:\", xb.shape)\n", + "print(\"y batch:\", yb.shape)\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 5. Display sample images\n", + "xb, yb = next(iter(train_loader))\n", + "\n", + "plt.figure(figsize=(10, 4))\n", + "for i in range(6):\n", + " img = xb[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: {yb[i].item():.0f}\")\n", + " plt.axis(\"off\")\n", + "plt.tight_layout()\n", + "plt.show()\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your model class here:\n", + "import torch.nn as nn\n", + "\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, 128),\n", + " nn.ReLU(),\n", + " nn.Linear(128, 1)\n", + " )\n", + "\n", + " def forward(self, x):\n", + " x = x.view(x.size(0), -1) # flatten\n", + " return self.net(x)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your training loop here:\n", + "def train_one_epoch(model, loader, loss_fn, optimizer, device):\n", + " model.train()\n", + " total_loss = 0.0\n", + "\n", + " for xb, yb in loader:\n", + " xb, yb = xb.to(device), yb.to(device)\n", + "\n", + " optimizer.zero_grad()\n", + " pred = model(xb)\n", + " loss = loss_fn(pred, yb)\n", + " loss.backward()\n", + " optimizer.step()\n", + "\n", + " total_loss += loss.item() * xb.size(0)\n", + "\n", + " return total_loss / len(loader.dataset)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your validation loop here:\n", + "@torch.no_grad()\n", + "def validate(model, loader, loss_fn, device):\n", + " model.eval()\n", + " total_loss = 0.0\n", + "\n", + " for xb, yb in loader:\n", + " xb, yb = xb.to(device), yb.to(device)\n", + " pred = model(xb)\n", + " loss = loss_fn(pred, yb)\n", + " total_loss += loss.item() * xb.size(0)\n", + "\n", + " return total_loss / len(loader.dataset)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Define device, model, loss, optimizer:\n", + "device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n", + "\n", + "C, H, W = X_train.shape[1], X_train.shape[2], X_train.shape[3]\n", + "input_dim = C * H * W\n", + "\n", + "model = AgeRegressor(input_dim).to(device)\n", + "loss_fn = 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", + "train_losses, val_losses = [], []\n", + "\n", + "for epoch in range(20):\n", + " tr_loss = train_one_epoch(model, train_loader, loss_fn, optimizer, device)\n", + " va_loss = validate(model, test_loader, loss_fn, device)\n", + "\n", + " train_losses.append(tr_loss)\n", + " val_losses.append(va_loss)\n", + "\n", + " print(f\"Epoch {epoch+1:02d} | Train Loss: {tr_loss:.4f} | Val Loss: {va_loss:.4f}\")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "plt.figure(figsize=(7,4))\n", + "plt.plot(train_losses, label=\"Train Loss\")\n", + "plt.plot(val_losses, label=\"Val Loss\")\n", + "plt.xlabel(\"Epoch\")\n", + "plt.ylabel(\"Loss\")\n", + "plt.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", + "@torch.no_grad()\n", + "def show_predictions(model, loader, device, n=6):\n", + " model.eval()\n", + " xb, yb = next(iter(loader))\n", + " xb, yb = xb[:n].to(device), yb[:n].to(device)\n", + " preds = model(xb).squeeze(1)\n", + "\n", + " plt.figure(figsize=(10, 4))\n", + " for i in range(n):\n", + " img = xb[i].cpu().permute(1, 2, 0).numpy()\n", + " plt.subplot(2, 3, i+1)\n", + " plt.imshow(img)\n", + " plt.title(f\"T:{yb[i].item():.0f} | P:{preds[i].item():.0f}\")\n", + " plt.axis(\"off\")\n", + " plt.tight_layout()\n", + " plt.show()\n", + "\n", + "show_predictions(model, test_loader, device, n=6)\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/209/Q3.ipynb b/submissions_extracted/209/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..78247199e4e2801257f07dca26b5445e23adbd46 --- /dev/null +++ b/submissions_extracted/209/Q3.ipynb @@ -0,0 +1,301 @@ +{ + "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", + "df = pd.read_csv(os.path.join(path, \"Q3_data.csv\"))\n", + "df.head()" + ], + "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", + "import numpy as np\n", + "\n", + "df_clean = df.copy()\n", + "\n", + "num_cols = df_clean.select_dtypes(include=[np.number]).columns\n", + "obj_cols = df_clean.select_dtypes(include=['object']).columns\n", + "\n", + "df_clean[num_cols] = df_clean[num_cols].fillna(df_clean[num_cols].median())\n", + "df_clean[obj_cols] = df_clean[obj_cols].fillna(\"Unknown\")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "df_clean = df_clean.drop_duplicates().copy()\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "from sklearn.preprocessing import LabelEncoder\n", + "\n", + "obj_cols = df_clean.select_dtypes(include=['object']).columns\n", + "for col in obj_cols:\n", + " le = LabelEncoder()\n", + " df_clean[col] = le.fit_transform(df_clean[col].astype(str))\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "from sklearn.preprocessing import StandardScaler\n", + "\n", + "# Identify numeric columns (exclude target later)\n", + "scaler = StandardScaler()\n", + "df_scaled = df_clean.copy()\n", + "\n", + "# We'll scale all numeric features later after defining X/y to avoid scaling target by mistake.\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "# Detect target column (common names, else last column)\n", + "target_candidates = [\"target\", \"Target\", \"default\", \"Default\", \"Credit_Default\", \"credit_default\", \"label\", \"Label\", \"y\"]\n", + "target_col = next((c for c in target_candidates if c in df_scaled.columns), df_scaled.columns[-1])\n", + "\n", + "class_counts = df_scaled[target_col].value_counts(normalize=True)\n", + "print(\"Target column:\", target_col)\n", + "print(class_counts)\n", + "\n", + "is_imbalanced = class_counts.max() > 0.6\n", + "print(\"Imbalanced?\" , is_imbalanced)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "!pip -q install catboost\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "\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_scaled.drop(columns=[target_col])\n", + "y = df_scaled[target_col]\n", + "\n", + "# Scale features only\n", + "scaler = StandardScaler()\n", + "X_scaled = scaler.fit_transform(X)\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", + "scores = []\n", + "\n", + "use_f1 = is_imbalanced # if imbalanced -> F1 else Accuracy\n", + "\n", + "for train_idx, val_idx in skf.split(X_scaled, y):\n", + " X_train_fold, X_val_fold = X_scaled[train_idx], X_scaled[val_idx]\n", + " y_train_fold, y_val_fold = y.iloc[train_idx], y.iloc[val_idx]\n", + "\n", + " model = CatBoostClassifier(\n", + " iterations=500,\n", + " learning_rate=0.1,\n", + " depth=6,\n", + " random_seed=42,\n", + " verbose=False\n", + " )\n", + "\n", + " model.fit(X_train_fold, y_train_fold)\n", + " preds = model.predict(X_val_fold)\n", + "\n", + " if use_f1:\n", + " scores.append(f1_score(y_val_fold, preds))\n", + " else:\n", + " scores.append(accuracy_score(y_val_fold, preds))\n", + "\n", + "metric_name = \"F1\" if use_f1 else \"Accuracy\"\n", + "print(f\"Average {metric_name} across folds:\", np.mean(scores))\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "import matplotlib.pyplot as plt\n", + "import numpy as np\n", + "\n", + "# Get feature importances\n", + "importances = full_model.get_feature_importance()\n", + "feat_names = X.columns.to_numpy()\n", + "\n", + "# Sort features\n", + "sorted_idx = np.argsort(importances)[::-1]\n", + "\n", + "# Take Top 10 only\n", + "top_n = 10\n", + "top_idx = sorted_idx[:top_n]\n", + "\n", + "plt.figure(figsize=(10, 5))\n", + "plt.barh(feat_names[top_idx][::-1], importances[top_idx][::-1])\n", + "plt.xlabel(\"Importance\")\n", + "plt.title(\"Top 10 Feature Importance (CatBoost)\")\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", + "golden_feature = feat_names[sorted_idx[0]]\n", + "print(\"Golden Feature:\", golden_feature)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:\n", + "X_golden = df_scaled[[golden_feature]].values\n", + "X_golden_scaled = StandardScaler().fit_transform(X_golden)\n", + "\n", + "skf = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)\n", + "\n", + "scores_golden = []\n", + "\n", + "for train_idx, val_idx in skf.split(X_golden_scaled, y):\n", + " X_train_fold, X_val_fold = X_golden_scaled[train_idx], X_golden_scaled[val_idx]\n", + " y_train_fold, y_val_fold = y.iloc[train_idx], y.iloc[val_idx]\n", + "\n", + " model = CatBoostClassifier(\n", + " iterations=500,\n", + " learning_rate=0.1,\n", + " depth=6,\n", + " random_seed=42,\n", + " verbose=False\n", + " )\n", + "\n", + " model.fit(X_train_fold, y_train_fold)\n", + " preds = model.predict(X_val_fold)\n", + "\n", + " if use_f1:\n", + " scores_golden.append(f1_score(y_val_fold, preds))\n", + " else:\n", + " scores_golden.append(accuracy_score(y_val_fold, preds))\n", + "\n", + "metric_name = \"F1\" if use_f1 else \"Accuracy\"\n", + "print(f\"Golden-only Average {metric_name}:\", np.mean(scores_golden))\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/21/Q1.ipynb b/submissions_extracted/21/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..dce18e819c269e1d85f44881c47a77b8e4265345 --- /dev/null +++ b/submissions_extracted/21/Q1.ipynb @@ -0,0 +1,180 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [], + "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": [ + "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": [ + "df.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "df.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [], + "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/21/Q2.ipynb b/submissions_extracted/21/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..b17c266b4b6d650340ffe750bf0f35fd521fa8f5 --- /dev/null +++ b/submissions_extracted/21/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/21/Q3.ipynb b/submissions_extracted/21/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..c97832709061629f03a86d1f40306ca8a3e2a744 --- /dev/null +++ b/submissions_extracted/21/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/210/Q1.ipynb b/submissions_extracted/210/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..80586828a848b967bcc6bf485b040dee7f064ffa --- /dev/null +++ b/submissions_extracted/210/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", + "import kagglehub\n", + "\n", + "from sklearn.model_selection import train_test_split, StratifiedKFold\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": [ + "import pandas as pd\n", + "# Task 1: Write your code here:\n", + "import os\n", + "file_ = os.path.join(path,\"Q1_data.csv\")\n", + "df = pd.read_csv(file_)" + ], + "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": [ + "# 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", + "print(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,10))\n", + "plt.hist(df[\"Delivery_Time\"],color=\"red\")\n", + "plt.title(\"Target Distribution\")\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "df.drop(columns=[\"Order_ID\"],inplace=True)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "df[\"Weather\"] = df[\"Weather\"].fillna(df[\"Weather\"].mode()[0])\n", + "df[\"Traffic_Level\"] = df[\"Traffic_Level\"].fillna(df[\"Traffic_Level\"].mode()[0])\n", + "df[\"Time_of_Day\"] = df[\"Time_of_Day\"].fillna(df[\"Time_of_Day\"].mode()[0])\n", + "df[\"Courier_Experience_yrs\"] = df[\"Courier_Experience_yrs\"].fillna(df[\"Courier_Experience_yrs\"].median())\n", + "df.dropna(subset=[\"Delivery_Time\"],inplace=True)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "df.drop_duplicates(inplace=True)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "from sklearn.preprocessing import OneHotEncoder #import OneHotEncoder\n", + "categories = [\"Weather\",\"Traffic_Level\",\"Time_of_Day\",\"Vehicle_Type\"]\n", + "df_test = df[categories].copy()\n", + "for col in categories:\n", + "\n", + " onehot_encoder = OneHotEncoder(sparse_output=False) # Instantiate OneHotEncoder\n", + " df_encoded = onehot_encoder.fit_transform(df_test) # Apply fit_transform to the copied\n", + " df[col] = df_encoded\n", + "\n", + "print('\\nData after encoding:\\n', df) #show after encoding\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "# Scale features - fit on train, transform both\n", + "#df.drop(columns=[\"Time\"],inplace=True)\n", + "scaler = StandardScaler()\n", + "columns = df.columns.drop(\"Delivery_Time\")\n", + "df[columns] = scaler.fit_transform(df[columns])\n", + "\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 6: Write your code here:\n", + "print(df[\"Delivery_Time\"].value_counts())" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "feature = df.drop(columns=[\"Delivery_Time\"])\n", + "target = df[\"Delivery_Time\"].copy()" + ], + "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", + "rf = RandomForestRegressor(random_state=42)\n", + "\n", + "error = []\n", + "y_pred = \"\"\n", + "for train_idx, test_idx in skf.split(feature,target):\n", + " X_train, X_test = feature.iloc[train_idx], feature.iloc[test_idx]\n", + " y_train, y_test = target.iloc[train_idx], target.iloc[test_idx]\n", + "\n", + " # Train\n", + " rf.fit(X_train,y_train)\n", + "\n", + " y_pred = rf.predict(X_test)\n", + "\n", + " # Calculate evaluation metrics\n", + " mae = mean_absolute_error(y_test, y_pred)\n", + "\n", + " # Store results\n", + " error.append(mae)\n", + "print(f\"Average score:- {np.mean(error):.4f}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "importance = rf.feature_importances_\n", + "\n", + "# Create a 1x3 plot\n", + "plt.figure(figsize=(10,10))\n", + "features = feature.columns\n", + "plt.barh(features[np.argsort(importance)],width=20)\n", + "plt.title(\"Importance\")\n", + "\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,10))\n", + "plt.hist(y_pred,color=\"blue\")\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", + "# TODO: Define models with hyperparameters of your choice\n", + "from catboost import CatBoostRegressor\n", + "models = {\n", + " \"RF\": RandomForestRegressor(random_state=42),\n", + " \"CatBoost\": CatBoostRegressor(verbose=0)\n", + "}\n", + "\n", + "\n", + "# Storage for results\n", + "all_results = {}\n", + "\n", + "for name in models:\n", + " all_results[name] = {'mae': []}\n", + "\n", + "skf = StratifiedKFold(n_splits=5,shuffle=True,random_state=42)\n", + "rf = RandomForestRegressor(random_state=42)\n", + "\n", + "error = []\n", + "y_pred = \"\"\n", + "for train_idx, test_idx in skf.split(feature,target):\n", + " X_train, X_test = feature.iloc[train_idx], feature.iloc[test_idx]\n", + " y_train, y_test = target.iloc[train_idx], target.iloc[test_idx]\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", + "\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": [] + }, + { + "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/210/Q2.ipynb b/submissions_extracted/210/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..83e8362883f13db99bbcc1b9c0f3f11acd5c03d4 --- /dev/null +++ b/submissions_extracted/210/Q2.ipynb @@ -0,0 +1,364 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q2-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import os\n", + "import pandas as pd\n", + "import numpy as np\n", + "from PIL import Image\n", + "from sklearn.model_selection import train_test_split\n", + "\n", + "# Load Labels\n", + "labels_df = pd.read_csv(os.path.join(path, \"labels.csv\"))\n", + "img_dir = os.path.join(path, \"images\")\n", + "\n", + "images = []\n", + "ages = []\n", + "\n", + "# Load Images and Resize\n", + "print(\"Loading images...\")\n", + "for index, row in labels_df.iterrows():\n", + " img_name = row.iloc[0]\n", + " age = row.iloc[1]\n", + " img_path = os.path.join(img_dir, img_name)\n", + "\n", + " if os.path.exists(img_path):\n", + " img = Image.open(img_path).convert('RGB')\n", + " img_array = np.array(img) / 255.0 # Normalize pixel values to [0, 1]\n", + " images.append(img_array)\n", + " ages.append(age)\n", + "\n", + "X = np.array(images)\n", + "y = np.array(ages)\n", + "\n", + "# Transpose image dimensions to match PyTorch format (N, C, H, W)\n", + "X = np.transpose(X, (0, 3, 1, 2))\n", + "\n", + "# Split Data\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n", + "\n", + "print(f\"X_train shape: {X_train.shape}\")\n", + "print(f\"X_test shape: {X_test.shape}\")\n", + "print(f\"y_train shape: {y_train.shape}\")\n", + "print(f\"y_test shape: {y_test.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Import 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", + "# 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,shuffle=True,batch_size=32,num_workers=2)\n", + "test_loader = DataLoader(test_dataset,shuffle=True,batch_size=32,num_workers=2)\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 4. Print shape of one batch\n", + "# Print dataset sizes\n", + "print(\"Train dataset:\", len(train_dataset))\n", + "print(\"Test dataset:\", len(test_dataset))\n", + "\n", + "# Get the first batch from the training DataLoader\n", + "X_batch, y_batch = next(iter(train_loader))\n", + "print(f\"Training batch input shape: {X_batch.shape}\")\n", + "print(f\"Training batch labels shape: {y_batch.shape}\")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 5. Display sample images\n", + "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=(100, 100))\n", + "plt.imshow(images.view(images.size(0),-1).squeeze())\n", + "plt.axis('off')\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)\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.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": [ + "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) # shape: (batch_size, 10)\n", + " loss = criterion(outputs, y_batch)\n", + " running_loss += loss.item()\n", + "\n", + " # Multiclass predictions\n", + " predicted = outputs\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 * 3 # Number of tabular features\n", + "hidden_dim = 64 # Design choice\n", + "\n", + "num_epochs = 20\n", + "learning_rate = 0.001\n", + "# Instantiate regression model\n", + "model = NN4Layer(input_dim, hidden_dim,1).to(device)\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", + "# 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,accuracy = 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", + " f'accuracy: {accuracy:.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')\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/210/Q3.ipynb b/submissions_extracted/210/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..a2f5a94502ca295515d6479546f4c124e3ced3f2 --- /dev/null +++ b/submissions_extracted/210/Q3.ipynb @@ -0,0 +1,322 @@ +{ + "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", + "file_ = os.path.join(path,\"Q3_data.csv\")\n", + "\n", + "df = pd.read_csv(file_)" + ], + "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": [ + "# 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", + "print(df.describe())" + ], + "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" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "df.dropna(axis=1,inplace=True)\n", + "\n" + ], + "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 #import StandardScaler\n", + "\n", + "print('data before scaling:\\n', df) #show before scaling\n", + "feature = df.drop(columns=[\"Target\"])\n", + "standard_scaler = StandardScaler() # Instantiate StandardScaler\n", + "feature[feature.columns] = standard_scaler.fit_transform(feature) # Apply fit_transform\n", + "df[feature.columns] = feature[feature.columns]\n", + "print('\\nData after scaling:\\n', df) #show after scaling" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "\n", + "print(df[\"Target\"].value_counts())" + ], + "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.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", + "from sklearn.model_selection import StratifiedKFold\n", + "from sklearn.metrics import accuracy_score, f1_score\n", + "import numpy as np\n", + "n_splits = 2\n", + "\n", + "skf = StratifiedKFold(n_splits=n_splits, shuffle=True, random_state=42)\n", + "# Task 1: Write your code here:\n", + "X = df.drop(columns=[\"Target\"]).copy()\n", + "y = df[\"Target\"].copy()\n", + "\n", + "f1_ = []\n", + "model = CatBoostClassifier(random_state=42,verbose=0)\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", + " model.fit(X_train,y_train)\n", + "\n", + " # Pick the predicted classes with the highest probability\n", + " y_pred = model.predict(X_test)\n", + "\n", + " # Calculate evaluation metrics\n", + " f1 = f1_score(y_test, y_pred) # for multiclass f1 score, you should set the average hyperparameter (\"macro\", \"micro\", \"weighted\")\n", + " print(\"f1-scroe: \",f1)\n", + "\n", + " # Store results\n", + " f1_.append(f1)\n", + "\n", + "\n", + "# Print the average of each evaluation metric across folds\n", + "print(f\" F1-Score: {np.mean(f1_):.4f}\")" + ], + "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", + "import matplotlib.pyplot as plt\n", + "\n", + "importances = model.feature_importances_\n", + "print(features[np.argsort(importances)])\n", + "\n", + "# Create a 1x3 plot\n", + "plt.Figure(figsize=(10,10))\n", + "features = X.columns\n", + "plt.barh(features[np.argsort(importances)],width=importances[np.argsort(importances)])\n", + "plt.tight_layout()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "print(\"golden feature: \",\"D_47\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:\n", + "\n", + "# Import models\n", + "from sklearn.linear_model import LogisticRegression\n", + "from sklearn.neighbors import KNeighborsClassifier\n", + "from sklearn.svm import SVC\n", + "from sklearn.tree import DecisionTreeClassifier\n", + "from sklearn.ensemble import RandomForestClassifier\n", + "from xgboost import XGBClassifier\n", + "from catboost import CatBoostClassifier\n", + "from sklearn.model_selection import StratifiedKFold\n", + "from sklearn.metrics import accuracy_score, f1_score\n", + "import numpy as np\n", + "n_splits = 2\n", + "\n", + "skf = StratifiedKFold(n_splits=n_splits, shuffle=True, random_state=42)\n", + "# Task 1: Write your code here:\n", + "X = pd.DataFrame(df[\"D_47\"])\n", + "y = df[\"Target\"].copy()\n", + "\n", + "f1_ = []\n", + "model = CatBoostClassifier(random_state=42,verbose=0)\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", + " model.fit(X_train,y_train)\n", + "\n", + " # Pick the predicted classes with the highest probability\n", + " y_pred = model.predict(X_test)\n", + "\n", + " # Calculate evaluation metrics\n", + " f1 = f1_score(y_test, y_pred) # for multiclass f1 score, you should set the average hyperparameter (\"macro\", \"micro\", \"weighted\")\n", + " print(\"f1-scroe: \",f1)\n", + "\n", + " # Store results\n", + " f1_.append(f1)\n", + "\n", + "\n", + "# Print the average of each evaluation metric across folds\n", + "print(f\" F1-Score: {np.mean(f1_):.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/211/Q1.ipynb b/submissions_extracted/211/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..69c7267480ad9bf05f8a4d12903ae4adb33f8e4e --- /dev/null +++ b/submissions_extracted/211/Q1.ipynb @@ -0,0 +1,394 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/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", + "#1. Read the dataset `Q1_data.csv` using `read_csv()`\n", + "import pandas as pd\n", + "import os\n", + "data_path = os.path.join(path, 'Q1_data.csv')\n", + "df = pd.read_csv(data_path)\n", + "\n", + "print(f\"Shape: {df.shape}\")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "#2. 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", + "3. #Display dataset information using `info()`\n", + "\n", + "df.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "#4. Show statistical description using `describe()`\n", + "df.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "#5. Plot the target distribution (delivery_time)\n", + "\n", + "# \"delivery_time\" distribution (target variable)\n", + "import matplotlib.pyplot as plt\n", + "plt.figure(figsize=(10, 5))\n", + "plt.hist(df[\"Delivery_Time\"].dropna(), bins=50, edgecolor='black')\n", + "plt.title('delivery_time Distribution')\n", + "plt.xlabel('delivery_time')\n", + "plt.ylabel('Frequency')\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "#Drop the 'Order_ID' column from the data\n", + "df.drop(columns=['Order_ID'])\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "#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)\n", + "\n", + "\n", + "# Drop them:\n", + "df.dropna()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "# 3. 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 4: Write your code here:\n", + "#Encode categorical variables if needed (Bonus if used One Hot Encoding)\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(df)\n", + "\n", + "from sklearn.preprocessing import LabelEncoder\n", + "\n", + "categorical_cols = df.select_dtypes(include=[\"object\"]).columns\n", + "for col in categorical_cols:\n", + " print(f\"Encoding column: {col}\")\n", + " le = LabelEncoder()\n", + " #(fit -> mapping) + (transform -> text-num)\n", + " df[col] = le.fit_transform(df[col])\n", + "df" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "from sklearn.preprocessing import StandardScaler\n", + "\n", + "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:\n", + "#Check for target imbalance and state if it is imbalanced or not (keep this cell empty if not needed)\n", + "# There's no need cause the label is numbers not classes" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "#Split the dataset into features (X) and target (y)\n", + "# Split data\n", + "\n", + "X = df.drop('Delivery_Time', axis=1)\n", + "y = df['Delivery_Time']\n", + "from sklearn.model_selection import train_test_split\n", + "\n", + "X_train, X_test, y_train, y_test = train_test_split(\n", + " X, y, test_size=0.2, random_state=42\n", + ")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:\n", + "#Use the correct split: KFold OR StratifiedKFold\n", + "#Train a RandomForest model\n", + "#Evaluate using MAE (Mean Absolute Error) ONLY\n", + "#Print the averaged score across all folds\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", + "# 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", + "# 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}\")\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": [ + "# 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:\n", + "import matplotlib.pyplot as plt\n", + "plt.figure(figsize=(10, 5))\n", + "plt.hist(y_fold_pred, bins=50, edgecolor='black')\n", + "plt.title('predicted delivery time Distribution')\n", + "plt.xlabel('predicted delivery time')\n", + "plt.ylabel('Frequency')\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:\n", + "# Define classification models\n", + "from sklearn.ensemble import RandomForestClassifier\n", + "from sklearn.linear_model import LogisticRegression\n", + "from sklearn.model_selection import KFold\n", + "from sklearn.ensemble import VotingClassifier\n", + "from catboost import CatBoostClassifier\n", + "\n", + "from sklearn.metrics import f1_score\n", + "\n", + "\n", + "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.loc[train_index, :], X.loc[test_index, :]\n", + " y_Train, y_Test = y.iloc[train_index], y.iloc[test_index]\n", + " # Train the model\n", + " model.fit(X_Train, y_Train)\n", + " # Predict on the test set\n", + " y_pred = model.predict(X_Test)\n", + "\n", + " # Calculate metrics\n", + " scores_f1.append(f1_score(y_Test, y_pred, average='weighted'))\n", + "\n", + " # Print the results\n", + " print(f\"{model_name} F1-Score: {np.mean(scores_f1):.4f}\")\n", + " print(\"\\n\")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Retrieve CatBoost feature importances and sort them\n", + "catboost_model = models[\"CatBoost Classifier\"]\n", + "catboost_importance = list(zip(X.columns, catboost_model.feature_importances_))\n", + "\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=(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": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/211/Q2.ipynb b/submissions_extracted/211/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..d14681e61f3fd5ce5ae1bfb932e782833a097dd7 --- /dev/null +++ b/submissions_extracted/211/Q2.ipynb @@ -0,0 +1,420 @@ +{ + "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", + "# 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", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 2. Create TensorDataset objects\n", + "\n", + "train_dataset = TensorDataset(X_train, y_train)\n", + "test_dataset = TensorDataset(X_test, y_test)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 3. Create DataLoaders\n", + "train_loader = DataLoader(train_dataset, batch_size=32, shuffle=True)\n", + "test_loader = DataLoader(test_dataset, batch_size=32, shuffle=False)\n", + "\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 4. Print shape of one batch\n", + "print(\"Train dataset:\", len(train_dataset))\n", + "print(\"Test dataset:\", len(test_dataset))\n", + "# 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", + "\n", + " def __init__(self, input_dim, hidden_dim, output_dim):\n", + " super(NN4Layer, self).__init__()\n", + "\n", + " # First linear layer: input features -> hidden layer\n", + " self.layer1 = nn.Linear(input_dim, hidden_dim)\n", + "\n", + " # Second linear layer: hidden layer -> hidden layer\n", + " self.layer2 = nn.Linear(hidden_dim, hidden_dim)\n", + "\n", + " # Third linear layer: hidden layer -> hidden layer\n", + " self.layer3 = nn.Linear(hidden_dim, hidden_dim)\n", + "\n", + " # Output layer: hidden layer -> number of classes (logits)\n", + " self.layer4 = nn.Linear(hidden_dim, output_dim)\n", + "\n", + " # ReLU activation for non-linearity\n", + " self.relu = nn.ReLU()\n", + "\n", + " # Defines how input data flows through the network\n", + " def forward(self, x):\n", + " # First hidden layer\n", + " a1 = self.relu(self.layer1(x))\n", + "\n", + " # Second hidden layer\n", + " a2 = self.relu(self.layer2(a1))\n", + "\n", + " # Third hidden layer\n", + " a3 = self.relu(self.layer3(a2))\n", + "\n", + " # Output layer (raw scores / logits)\n", + " output = self.layer4(a3) # we said we'll use softmax, where is it? ¯\\(ツ)/¯\n", + "\n", + " return output\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your training loop here:\n", + "def train_one_epoch(model, optimizer, criterion, train_loader, device):\n", + " # Set the model to training mode\n", + " model.train()\n", + "\n", + " running_loss = 0.0\n", + "\n", + " for X_batch, y_batch in train_loader:\n", + " # Move batch to the selected device\n", + " X_batch = X_batch.to(device) # shape: (batch_size, num_features)\n", + " y_batch = y_batch.to(device) # shape: (batch_size,)\n", + "\n", + " # Forward pass (outputs are logits)\n", + " outputs = model(X_batch) # shape: (batch_size, num_classes)\n", + " loss = criterion(outputs, y_batch)\n", + "\n", + " # Backward pass & optimization\n", + " optimizer.zero_grad() # Clear previous gradients\n", + " loss.backward() # Compute gradients\n", + " optimizer.step() # Update model parameters\n", + "\n", + " running_loss += loss.item()\n", + "\n", + " # Average loss over all batches\n", + " avg_loss = running_loss / len(train_loader)\n", + "\n", + " return avg_loss\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your validation loop here:\n", + "def validate(model, criterion, test_loader, device):\n", + " # Set the model to evaluation mode\n", + " model.eval()\n", + "\n", + " running_loss = 0.0\n", + " correct = 0\n", + " total = 0\n", + "\n", + " with torch.no_grad():\n", + " for X_batch, y_batch in test_loader:\n", + " # Move data to device\n", + " X_batch = X_batch.to(device) # shape: (batch_size, num_features)\n", + " y_batch = y_batch.to(device) # shape: (batch_size,)\n", + "\n", + " # Forward pass\n", + " outputs = model(X_batch) # shape: (batch_size, num_classes)\n", + " loss = criterion(outputs, y_batch)\n", + " running_loss += loss.item()\n", + "\n", + " # Apply Softmax to get probabilities\n", + " probabilities = F.softmax(outputs, dim=1)\n", + "\n", + " # Pick the classes with highest probabilities\n", + " predicted = torch.argmax(probabilities, dim=1)\n", + "\n", + " # Accuracy calculation\n", + " correct += (predicted == y_batch).sum().item()\n", + " total += y_batch.size(0)\n", + "\n", + " avg_loss = running_loss / len(test_loader)\n", + " accuracy = correct / total\n", + "\n", + " return avg_loss, accuracy" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Define device, model, loss, optimizer:\n", + "# Device setup\n", + "device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n", + "\n", + "# Model parameters\n", + "input_dim = X_train.shape[1] # Number of tabular features\n", + "hidden_dim = 14 # Design choice\n", + "output_dim = 4 # Weather classes: Rainy, Sunny, Cloudy, Snowy\n", + "\n", + "# Instantiate model\n", + "model = NN4Layer(input_dim, hidden_dim, output_dim).to(device)\n", + "\n", + "# Print the model architecture\n", + "print(\"Model Architecture:\\n\")\n", + "print(model)\n", + "\n", + "# Calculate the total number of trainable parameters\n", + "total_params = sum(p.numel() for p in model.parameters() if p.requires_grad)\n", + "print(f\"\\nTotal trainable parameters: {total_params}\")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Start training for 20 epochs:\n", + "num_epochs = 20\n", + "learning_rate = 0.001\n", + "\n", + "# Define criterion (loss function) - using CrossEntropyLoss as model now outputs logits\n", + "criterion = nn.CrossEntropyLoss()\n", + "# Define optimizer\n", + "optimizer = AdamW(model.parameters(), learning_rate)\n", + "# 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='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": [ + "# Save the trained model parameters\n", + "torch.save(model.state_dict(), \"weather_nn4layer.pth\")\n", + "\n", + "print(\"Model saved successfully!\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Recreate the model architecture\n", + "model = NN4Layer(input_dim, hidden_dim, output_dim)\n", + "# Load saved parameters\n", + "model.load_state_dict(torch.load(\"weather_nn4layer.pth\"))\n", + "# Set model to evaluation mode\n", + "model.eval()\n", + "print(\"Model loaded successfully!\")" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/211/Q3.ipynb b/submissions_extracted/211/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..63f11ba84f7d3f9a1a5c89d3b2972a4c817ec4a9 --- /dev/null +++ b/submissions_extracted/211/Q3.ipynb @@ -0,0 +1,294 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "from sklearn.metrics import f1_score\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", + "#1. Read the dataset `Q1_data.csv` using `read_csv()`\n", + "import pandas as pd\n", + "import os\n", + "data_path = os.path.join(path, 'Q3_data.csv')\n", + "df = pd.read_csv(data_path)\n", + "\n", + "print(f\"Shape: {df.shape}\")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "df.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "df.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 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)\n", + "\n", + "\n", + "# Drop them:\n", + "df.dropna()" + ], + "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)\n", + "#there is no Duplicate" + ], + "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(df)\n", + "#there is no Categorical Columns." + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "#Apply feature scaling for all features (Use StandardScaler)\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", + "import matplotlib.pyplot as plt\n", + "\n", + "# 1. Is the target imbalanced?\n", + "def check_target_imbalance(df, target_column):\n", + " print(\"Target Distribution:\")\n", + "\n", + " df[target_column].hist() # Yeah you can just do this :)\n", + " plt.show()\n", + "\n", + "check_target_imbalance(df, \"Target\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "X = df.drop(\"Target\", axis=1).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", + "import numpy as np\n", + "\n", + "%pip install catboost\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_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", + "# Storage for logistic regression results for each fold\n", + "lr_accuracy = []\n", + "lr_f1 = []\n", + "model = CatBoostClassifier(verbose=0)\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", + " lr_f1.append(f1_score(y_Test, y_pred, average='weighted'))\n", + " lr_f1.append(f1_score(y_Test, y_pred, average='weighted'))\n", + "\n", + "# Print the results\n", + "print(np.mean(lr_f1))\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", + "# 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", + "# Gather importances from the models (from the last fold)\n", + "importances = {}\n", + "\n", + "importances['Random Forest'] = sklearn_models['Random Forest'].feature_importances_\n", + "importances['XGBoost'] = sklearn_models['XGBoost'].feature_importances_\n", + "importances['CatBoost'] = sklearn_models['CatBoost'].feature_importances_\n", + "\n", + "# Create a 1x3 plot\n", + "fig, axes = plt.subplots(1, 3, figsize=(18, 6))\n", + "axes = axes.flatten()\n", + "features = X.columns\n", + "\n", + "for i, (model_name, imp) in enumerate(importances.items()):\n", + " # Sort features by importance for a cleaner plot\n", + " sorted_idx = np.argsort(imp)\n", + "\n", + " ax = axes[i]\n", + " ax.barh(features[sorted_idx], imp[sorted_idx])\n", + " ax.set_title(f\"{model_name} Feature Importance\")\n", + " ax.set_xlabel(\"Importance Score\")\n", + "\n", + "plt.tight_layout()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/212/Q1.ipynb b/submissions_extracted/212/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..548ee6a3dbb0395f6c314e67913f5e89f874f2ec --- /dev/null +++ b/submissions_extracted/212/Q1.ipynb @@ -0,0 +1,275 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "import os\n", + "import pandas as pd\n", + "import numpy as np\n", + "import matplotlib.pyplot as plt\n", + "import kagglehub\n", + "\n", + "from sklearn.model_selection import train_test_split, StratifiedKFold, cross_val_score\n", + "from sklearn.preprocessing import StandardScaler, LabelEncoder\n", + "from sklearn.ensemble import RandomForestClassifier\n", + "from sklearn.metrics import classification_report, confusion_matrix, accuracy_score\n", + "\n", + "import warnings\n", + "warnings.filterwarnings('ignore')\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q1-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "# Read the dataset Q1_data.csv using read_csv()\n", + "Food_path = os.path.join(path, 'Q1_data.csv')\n", + "df_food = pd.read_csv(Food_path)\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", + "# Inspect the first few rows using head()\n", + "df_food.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "# Display dataset information using info()\n", + "df_food.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "# Show statistical description using\n", + "df_food.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "# Plot the target distribution (delivery_time)\n", + "plt.figure(figsize=(10, 5))\n", + "plt.hist(df_food['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: Drop the 'Order_ID' column from the data\n", + "df_clean = df_food.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: 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())" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: 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_food)" + ], + "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 OneHotEncoder\n", + "\n", + "categorical_cols = df_food.select_dtypes(include=[\"object\"]).columns\n", + "\n", + "print(\"Categorical Columns:\", list(categorical_cols))\n", + "\n", + "categorical = ['Weather', 'Traffic_Level', 'Time_of_Day', 'Vehicle_Type']\n", + "\n", + "# onehot_encoder = OneHotEncoder(sparse_output=False) # Instantiate OneHotEncoder\n", + "# data_onehot_encoded = onehot_encoder.fit_transform(stat_cols) # Apply fit_transform to the copied\n", + "\n", + "# print('\\nData after encoding:\\n', data_onehot_encoded)\n", + "\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" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here: Apply feature scaling for all features (Use StandardScaler)\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: 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_food, target_column):\n", + " print(\"Target Distribution:\")\n", + " print(df_food[target_column].value_counts(normalize=True))\n", + " sns.countplot(x=df_food[target_column])\n", + " plt.title(\"Target Distribution\")\n", + " plt.show()\n", + "\n", + "check_target_imbalance(df_food, \"Delivery_Time\")" + ], + "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", + "feature_cols = ['Distance_km', 'Weather', 'Traffic_Level', 'Time_of_Day',\n", + " 'Vehicle_Type', 'Preparation_Time_min', 'Courier_Experience_yrs', 'Vehicle_Type', 'Delivery_Time']\n", + "\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", + "# Use the correct split: KFold OR StratifiedKFold\n", + "\n", + "# Train a RandomForest 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", + "# Evaluate using MAE (Mean Absolute Error) ONLY\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", + "# Print the averaged score across all folds" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here: Plot feature importance from your trained model" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here: Plot predicted delivery time histogram" + ], + "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/212/Q2.ipynb b/submissions_extracted/212/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..59382693772f4f5b63dd4e15ea80af18c88e2bc6 --- /dev/null +++ b/submissions_extracted/212/Q2.ipynb @@ -0,0 +1,212 @@ +{ + "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 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", + "# TODO: Transform to PyTorch tensors with dtype=torch.float32\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", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 3. Create DataLoaders\n", + "\n", + "# Create Dataloaders to train and test data in batches\n", + "train_loader = DataLoader(train_dataset, batch_size=32, shuffle=True)\n", + "test_loader = DataLoader(test_dataset, batch_size=32, shuffle=False)\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 4. Print shape of one batch\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 5. Display sample images\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [], + "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/212/Q3.ipynb b/submissions_extracted/212/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..868bdb17f04be55c5ecaca689221b36aa08b5346 --- /dev/null +++ b/submissions_extracted/212/Q3.ipynb @@ -0,0 +1,211 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "\n", + "import kagglehub\n", + "import os\n", + "import pandas as pd\n", + "import numpy as np\n", + "import matplotlib.pyplot as plt\n", + "import kagglehub\n", + "\n", + "from sklearn.model_selection import train_test_split, StratifiedKFold, cross_val_score\n", + "from sklearn.preprocessing import StandardScaler, LabelEncoder\n", + "from sklearn.ensemble import RandomForestClassifier\n", + "from sklearn.metrics import classification_report, confusion_matrix, accuracy_score\n", + "\n", + "import warnings\n", + "warnings.filterwarnings('ignore')\n", + "\n", + "\n", + "# Download latest version\n", + "\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q3-exam-data\")\n", + "\n", + "\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "g_path = os.path.join(path, 'Q3_data.csv')\n", + "df_data = pd.read_csv(g_path)\n", + "\n", + "print(f\"Shape: {df_data.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "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", + "print(\"\\nMissing Values (df.isnull().sum()):\")\n", + "print(df_data.isnull().sum())" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "def check_duplicates(df):\n", + " duplicates = df.duplicated().sum()\n", + " print(f\"Number of Duplicate Samples: {duplicates}\")\n", + " if duplicates > 0:\n", + " print(\"Dropping Duplicates...\")\n", + " df.drop_duplicates(inplace=True)\n", + " print(\"Duplicates Dropped.\")\n", + " else:\n", + " print(\"No Duplicate Samples Found.\")\n", + "\n", + "check_duplicates(df_data)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here: Encode categorical variables if needed\n", + "categorical_cols = df_data.select_dtypes(include=[\"object\"]).columns\n", + "\n", + "print(\"Categorical Columns:\", list(categorical_cols))" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here: Apply feature scaling to numerical features (Use StandardScaler)\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 5: Write your code here: Check for target imbalance and state if it is imbalanced or not\n", + "\n", + "def check_target_imbalance(df_data, target_column):\n", + " print(\"Target Distribution:\")\n", + " print(df_data[target_column].value_counts(normalize=True))\n", + " sns.countplot(x=df_data[target_column])\n", + " plt.title(\"Target Distribution\")\n", + " plt.show()\n", + "\n", + "check_target_imbalance(df_data, \"Target\")\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:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here: Plot feature importance from your trained model" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here: Identify and print the name of the most important feature (the 'golden feature')" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/213/Q1.ipynb b/submissions_extracted/213/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..47695aa89d432b69737a4d806a594a53044034b2 --- /dev/null +++ b/submissions_extracted/213/Q1.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/q1-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# importing the libraries I need for this question\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" + ], + "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_delivery = pd.read_csv(data_path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "print(f\"Shape: {df_delivery.shape}\") # print the 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", + "# Delivery_Time distribution (target variable)\n", + "plt.figure(figsize=(10, 5))\n", + "plt.hist(df_delivery['Delivery_Time'].dropna(), bins=50, edgecolor='black')\n", + "plt.title('Delivery_Time Distribution')\n", + "plt.xlabel('Delivery_Time')\n", + "plt.ylabel('Frequency')\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "df_delivery = df_delivery.drop(columns=['Order_ID'])" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# checking the data after droping the column\n", + "df_delivery.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "# droping the rows where the tagret valuse in null\n", + "df_delivery = df_delivery.dropna(subset=['Delivery_Time'])\n", + "# Fill categorical columns with 'unknown'\n", + "for col in ['Weather', 'Traffic_Level', 'Time_of_Day']:\n", + " df_delivery[col] = df_delivery[col].fillna('unknown')\n", + "# Fill Courier_Experience_yrs with mode - discrete feature, mode is most representative\n", + "df_delivery['Courier_Experience_yrs'] = df_delivery['Courier_Experience_yrs'].fillna(df_delivery['Courier_Experience_yrs'].mode()[0])\n", + "\n", + "# checking the data after dealing with missing values\n", + "df_delivery.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "df_delivery.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "# checking if ther eare 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) # change the same dataframe\n", + " print(\"Duplicates Dropped.\")\n", + " else:\n", + " print(\"No Duplicate Samples Found.\")\n", + "\n", + "# removing the duplicates\n", + "df_delivery.drop_duplicates(inplace=True)\n", + "\n", + "# chceking again after droping\n", + "check_duplicates(df_delivery)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# # Task 4: Write your code here:\n", + "# from sklearn.preprocessing import OneHotEncoder\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", + "# onehot_encoder = OneHotEncoder(sparse_output=False)\n", + "# data_onehot_encoded = onehot_encoder.fit_transform(categorical_cols) # Apply fit_transform to the copied\n", + "\n", + "\n", + "# data_onehot_encoded.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "from sklearn.preprocessing import OneHotEncoder #import OneHotEncoder\n", + "\n", + "categorical_cols = ['Weather', 'Traffic_Level', 'Time_of_Day', 'Vehicle_Type']\n", + "for col in categorical_cols:\n", + " le = LabelEncoder()\n", + " # onehot_encoder = OneHotEncoder(sparse_output=False)\n", + " df_delivery[col] = le.fit_transform(df_delivery[col].astype(str))\n", + "\n", + "df_delivery.head()" + ], + "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_delivery.columns.drop(\"Delivery_Time\") # DON'T SCALE THE TARGET to prevent data leakage\n", + "\n", + "scaler = StandardScaler()\n", + "df_delivery[features] = scaler.fit_transform(df_delivery[features])\n", + "df_delivery.head()" + ], + "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", + "# def check_target_distribution(df, target_column):\n", + "# df[target_column].hist(bins=30, edgecolor='black')\n", + "\n", + "# plt.title(f\"Target Distribution ({target_column})\")\n", + "# plt.xlabel(target_column)\n", + "# plt.ylabel(\"Frequency\")\n", + "# plt.grid(False)\n", + "\n", + "# plt.show()\n", + "\n", + "# check_target_distribution(df_delivery, \"Delivery_Time\") #-- chek the skew of the target -- # if yes --> take the log transformor" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "X = df_delivery[features]\n", + "y = df_delivery['Delivery_Time']\n", + "# print(X)\n", + "# print(y)" + ], + "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_absolute_error\n", + "\n", + "n_splits = 5 # K=5 Folds\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", + " 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", + "rf = RandomForestRegressor(n_estimators=100, max_depth=5, random_state=42)\n", + "rf.fit(X_train, y_train)\n", + "y_pred = rf.predict(X_test)\n", + "print(\"Random Forest R²:\", rf.score(X_test, y_test))\n", + "\n", + "# Mean Absolute Error (MAE)\n", + "mae = mean_absolute_error(y_test, y_pred)\n", + "print(f\"MAE: {mae:.2f}\")\n", + "print(\" → Average absolute error\")\n", + "print(\" → Easy to interpret (same units as target)\")\n", + "\n", + "\n", + "# Storage for linear regression results for each fold\n", + "lr_losses = []\n", + "lr_mae = []\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", + "# # ------baseline in regression is the mean -----#\n", + "# lr_mae.append(mae)" + ], + "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/213/Q2.ipynb b/submissions_extracted/213/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..2bba0314f0b860335a3ba2625cd80f2a0d8c5cfa --- /dev/null +++ b/submissions_extracted/213/Q2.ipynb @@ -0,0 +1,406 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q2-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import os\n", + "import pandas as pd\n", + "import numpy as np\n", + "from PIL import Image\n", + "from sklearn.model_selection import train_test_split\n", + "\n", + "# Load Labels\n", + "labels_df = pd.read_csv(os.path.join(path, \"labels.csv\"))\n", + "img_dir = os.path.join(path, \"images\")\n", + "\n", + "images = []\n", + "ages = []\n", + "\n", + "# Load Images and Resize\n", + "print(\"Loading images...\")\n", + "for index, row in labels_df.iterrows():\n", + " img_name = row.iloc[0]\n", + " age = row.iloc[1]\n", + " img_path = os.path.join(img_dir, img_name)\n", + "\n", + " if os.path.exists(img_path):\n", + " img = Image.open(img_path).convert('RGB')\n", + " img_array = np.array(img) / 255.0 # Normalize pixel values to [0, 1]\n", + " images.append(img_array)\n", + " ages.append(age)\n", + "\n", + "X = np.array(images)\n", + "y = np.array(ages)\n", + "\n", + "# Transpose image dimensions to match PyTorch format (N, C, H, W)\n", + "X = np.transpose(X, (0, 3, 1, 2))\n", + "\n", + "# Split Data\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n", + "\n", + "print(f\"X_train shape: {X_train.shape}\")\n", + "print(f\"X_test shape: {X_test.shape}\")\n", + "print(f\"y_train shape: {y_train.shape}\")\n", + "print(f\"y_test shape: {y_test.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 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": [ + "# 1. Convert Numpy arrays to PyTorch Tensors\n", + "\n", + "X_train = torch.tensor(X_train, dtype=torch.float32)\n", + "X_test = torch.tensor(X_test, dtype=torch.float32)\n", + "y_train = torch.tensor(y_train, dtype=torch.float32)\n", + "y_test = torch.tensor(y_test, dtype=torch.float32)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 2. Create TensorDataset objects\n", + "from torch.utils.data import DataLoader, TensorDataset\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)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 4. Print shape of one batch\n", + "\n", + "# Get the first batch from the training DataLoader\n", + "X_batch, y_batch = next(iter(train_loader))\n", + "print(f\"Training batch input shape: {X_batch.shape}\")\n", + "print(f\"Training batch labels shape: {y_batch.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 5. Display sample images\n", + "# Get one batch of images and labels\n", + "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 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)\n", + " a1 = self.relu(z1)\n", + "\n", + " # Layer 2 TODO\n", + " z2 = self.layer2(a1)\n", + " a2 = self.relu(z2)\n", + "\n", + " # Layer 3 TODO\n", + " z3 = self.layer3(a2)\n", + " a3 = self.relu(z3)\n", + "\n", + " # Output layer TODO\n", + " z5 = self.layer4(a3)\n", + "\n", + " 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(32, -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": [ + "print(f\"X_train shape: {X_batch.shape}\")\n", + "print(f\"X_test shape: {y_batch.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": [ + "# 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(32, -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", + "\n", + "# Device setup\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\n", + "output_dim = 1\n", + "# Instantiate model\n", + "model = NN4Layer(input_dim, hidden_dim, output_dim).to(device)\n", + "\n", + "# Define criterion (loss function)\n", + "criterion = nn.MSELoss()\n", + "# Define optimizer\n", + "learning_rate = 0.001\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", + "# 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, val_accuracy = 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" + ], + "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/213/Q3.ipynb b/submissions_extracted/213/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..feb827c8b566321849c786b4ca06d512fb2034f4 --- /dev/null +++ b/submissions_extracted/213/Q3.ipynb @@ -0,0 +1,186 @@ +{ + "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", + "# Descriptive statistics for numerical columns\n", + "df.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "print(\"\\nMissing Values (df.isnull().sum()):\")\n", + "print(df.isnull().sum())" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/214/Q1.ipynb b/submissions_extracted/214/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..e24ec2fa1783693a77acdfd4e3adb5c4d83abf4b --- /dev/null +++ b/submissions_extracted/214/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": [ + "\n", + "import numpy as np\n", + "import pandas as pd\n", + "import matplotlib.pyplot as plt\n", + "import os\n", + "import kagglehub\n", + "\n", + "from sklearn.model_selection import train_test_split, KFold\n", + "from sklearn.preprocessing import StandardScaler, LabelEncoder\n", + "from sklearn.ensemble import RandomForestRegressor\n", + "from sklearn.metrics import mean_absolute_error, mean_squared_error\n", + "\n", + "import warnings\n", + "warnings.filterwarnings('ignore')\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "\n", + "Delivery_Time = os.path.join(path, 'Q1_data.csv')\n", + "df = pd.read_csv(Delivery_Time)\n", + "\n", + "print(f\"Dataset shape: {df.shape}\")\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "\n", + "df.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "\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": [ + "\n", + "df.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "\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('Frequency')\n", + "plt.show()\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "\n", + "cols = ['Distance_km', 'Weather', 'Traffic_Level', 'Time_of_Day',\n", + " 'Vehicle_Type', 'Preparation_Time_min', 'Courier_Experience_yrs', 'Delivery_Time']\n", + "df_clean = df[cols].copy()\n", + "\n", + "\n", + "print(f\"Before: {df_clean.shape}\")\n", + "df_clean = df_clean.dropna(subset=['Delivery_Time'])\n", + "print(f\"After dropping missing price/year/odometer: {df_clean.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "\n", + "for col in ['Distance_km', 'Weather', 'Traffic_Level', 'Time_of_Day',\n", + " 'Vehicle_Type', 'Preparation_Time_min', 'Courier_Experience_yrs', 'Delivery_Time']:\n", + " df_clean[col] = df_clean[col].fillna('unknown')\n", + "\n", + "df_clean['cylinders'] = df_clean['cylinders'].fillna(df_clean['cylinders'].mode()[0])\n", + "\n", + "print(\"Missing values remaining:\", df_clean.isnull().sum().sum())\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "categorical_cols = ['Distance_km', 'Weather', 'Traffic_Level', 'Time_of_Day',\n", + " 'Vehicle_Type', 'Preparation_Time_min', 'Courier_Experience_yrs', '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": [ + "feature_cols = ['Distance_km', 'Weather', 'Traffic_Level', 'Time_of_Day',\n", + " 'Vehicle_Type', 'Preparation_Time_min', 'Courier_Experience_yrs', 'Delivery_Time']\n", + "X = df_clean[feature_cols]\n", + "y = df_clean['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)\n", + "print(f\"Train: {X_train.shape}, Test: {X_test.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "\n", + "print(f\"\\nFeature ranges - Min: {X_train.min().min():.2f}, Max: {X_train.max().max():.2f}\")\n", + "X_train.head(3)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "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": [ + "\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", + "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 6: Check for target imbalance and state if it is imbalanced or not (keep this cell empty if not needed) there are no outliers" + ], + "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", + "\n", + " model.fit(X_fold_train, y_fold_train)\n", + " y_fold_pred = model.predict(X_fold_val)\n", + "\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": [ + "# 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/214/Q2.ipynb b/submissions_extracted/214/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..9be214eb5b31d59a2ec7ea2caeafea9648279714 --- /dev/null +++ b/submissions_extracted/214/Q2.ipynb @@ -0,0 +1,248 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q2-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)\n", + "\n", + "df = pd.read_csv(f\"{path}/labels.csv\")\n", + "df.head()" + ], + "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\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" + ], + "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": [ + "df.info()\n", + "\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 3. Create DataLoaders\n", + "\n", + "categorical_cols = df.select_dtypes(include=[\"object\"]).columns\n", + "for col in categorical_cols:\n", + " print(f\"Encoding column: {col}\")\n", + " le = LabelEncoder()\n", + " df[col] = le.fit_transform(df[col])\n", + "df\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 4. Print shape of one batch\n", + "numerical_cols = df.select_dtypes(include=[\"int64\", \"float64\"]).columns.drop(\"age\") ### DON'T SCALE THE TARGET\n", + "scaler = StandardScaler()\n", + "df[numerical_cols] = scaler.fit_transform(df[numerical_cols])\n", + "df\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "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}\")" + ], + "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/214/Q3.ipynb b/submissions_extracted/214/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..c97832709061629f03a86d1f40306ca8a3e2a744 --- /dev/null +++ b/submissions_extracted/214/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/215/Q1.ipynb b/submissions_extracted/215/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..3b6f72c85356c8baed8c9940dfdbb048d19235dd --- /dev/null +++ b/submissions_extracted/215/Q1.ipynb @@ -0,0 +1,271 @@ +{ + "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", + "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", + "import matplotlib.pyplot as plt\n", + "import os\n", + "\n", + "path = os.path.join(path, 'Q1_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", + "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", + "df.describe()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "\n", + "plt.figure(figsize=(10, 5))\n", + "plt.hist(df['Delivery_Time'], bins=50, edgecolor='black')\n", + "plt.title('Target Distribution')\n", + "plt.xlabel('Delivery Time')\n", + "plt.ylabel('time')\n", + "plt.show()\n" + ], + "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", + "print(\"Missing values per column:\")\n", + "print(df.isnull().sum())\n", + "print(f\"\\nTotal missing: {df.isnull().sum().sum()}\")\n", + "\n", + "# we have 5 columns with missing values\n", + "missing_columns = ['Weather','Traffic_Level','Time_of_Day',\n", + " 'Courier_Experience_yrs','Delivery_Time']\n", + "\n", + "print(\"\\nShape before handling: \",df.shape)\n", + "\n", + "df = df.dropna(subset= missing_columns)\n", + "\n", + "print(\"Shape after handling: \",df.shape)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\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 4: Write your code here:\n", + "from sklearn.preprocessing import OneHotEncoder\n", + "categorical_cols = df.select_dtypes(include=[\"object\"]).columns\n", + "print(categorical_cols)\n", + "\n", + "encoder = OneHotEncoder(sparse_output=False)\n", + "for col in categorical_cols:\n", + " df[col] = encoder.fit_transform(df[[col]])\n", + "\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "df.info()\n", + "\n", + "from sklearn.preprocessing import StandardScaler\n", + "\n", + "features = df.columns.drop(\"Delivery_Time\")\n", + "scaler = StandardScaler()\n", + "df[features] = scaler.fit_transform(df[features])\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 6: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "X = df.drop('Delivery_Time',axis=1)\n", + "y = df['Delivery_Time']" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:\n", + "from sklearn.model_selection import KFold\n", + "from sklearn.ensemble import RandomForestRegressor\n", + "from sklearn.metrics import mean_squared_error\n", + "\n", + "mse_result = []\n", + "kf = KFold(n_splits=6, 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", + "\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", + " mse = mean_squared_error(y_test, y_pred)\n", + " mse_result.append(mse)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "feature_cols = X.columns\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=30, edgecolor='black')\n", + "plt.title('Distribution of predicted delivery time')\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/215/Q2.ipynb b/submissions_extracted/215/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..75f0bcd36abb096b8edd8b4a3a45474f370e2325 --- /dev/null +++ b/submissions_extracted/215/Q2.ipynb @@ -0,0 +1,315 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/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_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) # float for regression\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", + "from torch.utils.data import TensorDataset, DataLoader\n", + "\n", + "train_dataset = TensorDataset(X_train_tensor, y_train_tensor)\n", + "test_dataset = TensorDataset(X_test_tensor, y_test_tensor)\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", + "X_batch, y_batch = next(iter(train_loader))\n", + "print(f\"Batch shape: {X_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.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.axis('off')\n", + "\n", + "plt.tight_layout()\n", + "plt.show()\n", + "\n", + "# handsome people btw" + ], + "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 NN4(nn.Module):\n", + " def __init__(self, input_dim, hidden_dim):\n", + " super(NN4, 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", + " 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", + "\n", + " model.train()\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", + " 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", + "\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():\n", + "\n", + " for X_batch, y_batch in test_loader:\n", + " X_batch = X_batch.view(X_batch.size(0), -1).to(device)\n", + " y_batch = y_batch.to(device)\n", + "\n", + " outputs = model(X_batch)\n", + " loss = criterion(outputs, y_batch)\n", + " running_loss += loss.item()\n", + "\n", + " avg_loss = running_loss / len(test_loader)\n", + "\n", + " return avg_loss" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Define device, model, loss, optimizer:\n", + "device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n", + "\n", + "input_dim = 3*36*36\n", + "hidden_dim = 14\n", + "output_dim = 10\n", + "\n", + "model = NN4(input_dim, hidden_dim).to(device)\n", + "\n", + "criterion = nn.MSELoss()\n", + "\n", + "optimizer = torch.optim.AdamW(model.parameters(), lr=0.0001)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Start training for 20 epochs:\n", + "\n", + "num_of_epochs = 20\n", + "train_losses = []\n", + "val_losses = []\n", + "\n", + "for epoch in range(num_of_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_of_epochs}], Train Loss: {train_loss:.4f}, Val Loss: {val_loss:.4f}')" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "plt.figure(figsize=(10, 5))\n", + "plt.plot(train_losses, label='Train Loss')\n", + "plt.plot(val_losses, label='Validation Loss')\n", + "plt.xlabel('Epoch')\n", + "plt.ylabel('Loss')\n", + "plt.title('Training and Validation Loss')\n", + "plt.legend()\n", + "plt.grid(True, alpha=0.3)\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2 (Bonus): Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/215/Q3.ipynb b/submissions_extracted/215/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..3e077232ce0b5ba6df1be8f1d7a309205c0d6366 --- /dev/null +++ b/submissions_extracted/215/Q3.ipynb @@ -0,0 +1,269 @@ +{ + "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", + "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()\n", + "\n", + "# 189 columns, 20000 rows approx, all data numerical" + ], + "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 per column:\")\n", + "df_missing = df.isnull().sum()\n", + "missing_pct = (df.isnull().sum() / len(df)) * 100\n", + "mpct_col = missing_pct[missing_pct > 0].sort_values(ascending=False)\n", + "print(mpct_col.head(50))\n", + "\n", + "# remove columns that have waaaaaay too many missing values (over 50 percent)\n", + "for col, missing_percentage in mpct_col.items():\n", + " # fill the rest of the missing values with the mode\n", + " df[col] = df[col].fillna(df[col].mode()[0])\n", + "\n", + " #drop the cols with most values missing\n", + " if missing_percentage > 50:\n", + " df = df.drop(col,axis=1)\n", + "\n", + "\n", + "\n", + "\n", + "print(df.shape)\n", + "df.head()\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\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:\n", + "# 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", + "features = df.columns.drop(\"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", + "import matplotlib.pyplot as plt\n", + "\n", + "plt.figure(figsize=(10, 5))\n", + "df['Target'].value_counts().plot(kind='bar')\n", + "plt.title('Target Distribution')\n", + "plt.xlabel('Target')\n", + "plt.ylabel('Count')\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "X = df.drop('Target',axis=1)\n", + "y = df['Target']" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2,3,4,5: Write your code here:\n", + "!pip install catboost\n", + "from sklearn.model_selection import StratifiedKFold\n", + "from catboost import CatBoostClassifier\n", + "from sklearn.metrics import f1_score\n", + "from sklearn.metrics import accuracy_score\n", + "\n", + "model = CatBoostClassifier(n_estimators=100, max_depth=5, verbose=0)\n", + "\n", + "\n", + "skf = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)\n", + "avg_f1 = []\n", + "avg_acc = []\n", + "\n", + "for fold, (train_idx, test_idx) in enumerate(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", + " f1= f1_score(y_test, y_pred)\n", + " acc = accuracy_score(y_test, y_pred)\n", + " avg_f1.append(f1)\n", + " avg_acc.append(acc)\n", + "\n", + "print(\"\\nThe average F1-score across all 5 folds: \\n\",avg_f1)\n", + "print(\"\\nThe average Accuracy across all 5 folds: \\n\",avg_acc)\n", + "\n", + "# i would personally judge off of f1-score instead of accuracy" + ], + "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'][-10:], feature_importance['importance'][-10:])\n", + "plt.xlabel('Importance')\n", + "plt.title('Feature Importance')\n", + "plt.show()\n", + "\n", + "# to validate\n", + "print(max(feature_importance['importance']))" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "\n", + "print(\"THE GOLDEN FEATURE IS ..... *drum rolls*\\n P_2!!!!!!\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "f" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/216/Q1.ipynb b/submissions_extracted/216/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..92337bdaf37d14e7c2d44feaec23e47d75d95baa --- /dev/null +++ b/submissions_extracted/216/Q1.ipynb @@ -0,0 +1,307 @@ +{ + "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", + "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": [ + "# Task 5: Write your code here:\n", + "def check_target_distribution(df, target_column):\n", + " df[target_column].hist(bins=30, edgecolor='black')\n", + "\n", + " plt.title(f\"Target Distribution ({target_column})\")\n", + " plt.xlabel(target_column)\n", + " plt.ylabel(\"Frequency\")\n", + " plt.grid(False)\n", + "\n", + " plt.show()\n", + "\n", + "check_target_distribution(df, \"Delivery_Time\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "df = df.drop([\"Order_ID\"], axis = 1)\n", + "df.head()\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", + "#checking for missing values\n", + "check_missing_values(df)\n", + "\n", + "#handling catgorical missing values\n", + "for col in [\"Weather\", \"Traffic_Level\", \"Time_of_Day\"]:\n", + " df[col] = df[col].fillna(df[col].mode()[0])\n", + "\n", + "#handling numerical columns\n", + "for col in [\"Courier_Experience_yrs\", \"Delivery_Time\"]:\n", + " df[col] = df[col].fillna(df[col].mean())\n", + "\n", + "print(\"After handling missing data: \")\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", + "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", + "\n", + "one_hot_encoder = OneHotEncoder(sparse_output=False)\n", + "label_encoder = LabelEncoder()\n", + "\n", + "df[\"Traffic_Level\"] = label_encoder.fit_transform(df[\"Traffic_Level\"])\n", + "\n", + "df[\"Weather\"] = label_encoder.fit_transform(df[\"Weather\"])\n", + "\n", + "df[\"Vehicle_Type\"] = label_encoder.fit_transform(df[\"Vehicle_Type\"])\n", + "\n", + "df[\"Time_of_Day\"] = label_encoder.fit_transform(df[\"Time_of_Day\"])\n", + "\n", + "df.head()\n", + "\n", + "\n", + "\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "from sklearn.preprocessing import MinMaxScaler\n", + "\n", + "features = df.columns.drop(\"Delivery_Time\") # 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 6: Write your code here:\n", + "\n", + "#Since it is a countinuos variable no need for target imbalance aka we are not doing classification" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "\n", + "X = df.drop(\"Delivery_Time\", axis=1).astype(float)\n", + "y = df['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", + "from sklearn.metrics import mean_absolute_error\n", + "from sklearn.ensemble import RandomForestRegressor\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", + "maes = []\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", + " rf = RandomForestRegressor(n_estimators=200)\n", + " rf.fit(X_train, y_train)\n", + " y_pred = rf.predict(X_test)\n", + " mae = mean_absolute_error(y_test, y_pred)\n", + " print(\"The mae for this fold is \", mae)\n", + " maes.append(mae)\n", + "avg_score = 0\n", + "for mae in maes:\n", + " avg_score+=mae\n", + "print(\"The average score is \", avg_score/n_splits)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "importance = pd.DataFrame({\n", + " 'feature': [\"Courier_Experience_yrs\", \"Weather\", \"Preparation_Time_min\",\"Vehicle_Type\",\"Time_of_Day\"],\n", + " 'importance': rf.feature_importances_\n", + "}).sort_values('importance', ascending=False)\n", + "\n", + "plt.figure(figsize=(10, 6))\n", + "plt.barh(importance['feature'], importance['importance'], color='purple')\n", + "plt.xlabel('Importance')\n", + "plt.title('Feature Importance')\n", + "plt.gca().invert_yaxis()\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 2: Write your code here:\n", + "\n", + "plt.hist(y_pred,bins=30, edgecolor='black')\n", + "\n", + "plt.title(f\"Target Distribution ({\"Predicted\"})\")\n", + "plt.xlabel(\"Predicted\")\n", + "plt.ylabel(\"Frequency\")\n", + "plt.grid(False)\n", + "\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/216/Q2.ipynb b/submissions_extracted/216/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..d9a706ff50220f51ee913e44c0b3d5c93ab2d174 --- /dev/null +++ b/submissions_extracted/216/Q2.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/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.nn.functional as F\n", + "\n", + "# Load Labels\n", + "labels_df = pd.read_csv(os.path.join(path, \"labels.csv\"))\n", + "img_dir = os.path.join(path, \"images\")\n", + "\n", + "images = []\n", + "ages = []\n", + "\n", + "# Load Images and Resize\n", + "print(\"Loading images...\")\n", + "for index, row in labels_df.iterrows():\n", + " img_name = row.iloc[0]\n", + " age = row.iloc[1]\n", + " img_path = os.path.join(img_dir, img_name)\n", + "\n", + " if os.path.exists(img_path):\n", + " img = Image.open(img_path).convert('RGB')\n", + " img_array = np.array(img) / 255.0 # Normalize pixel values to [0, 1]\n", + " images.append(img_array)\n", + " ages.append(age)\n", + "\n", + "X = np.array(images)\n", + "y = np.array(ages)\n", + "\n", + "# Transpose image dimensions to match PyTorch format (N, C, H, W)\n", + "X = np.transpose(X, (0, 3, 1, 2))\n", + "\n", + "# Split Data\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n", + "\n", + "print(f\"X_train shape: {X_train.shape}\")\n", + "print(f\"X_test shape: {X_test.shape}\")\n", + "print(f\"y_train shape: {y_train.shape}\")\n", + "print(f\"y_test shape: {y_test.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 1. Convert Numpy arrays to PyTorch Tensors\n", + "import torch\n", + "X_train = torch.as_tensor(X_train,dtype=torch.float32)\n", + "X_test = torch.as_tensor(X_test, dtype=torch.float32)\n", + "y_train = torch.as_tensor(y_train, dtype=torch.float32)\n", + "y_test = torch.as_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", + "train_dataset = TensorDataset(X_train, y_train)\n", + "test_dataset = TensorDataset(X_test, y_test)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 3. Create DataLoaders\n", + "\n", + "from torch.utils.data import DataLoader\n", + "\n", + "# DataLoader for training data\n", + "train_loader = DataLoader(\n", + " train_dataset,\n", + " batch_size=32,\n", + " shuffle=True,\n", + " num_workers=2\n", + ")\n", + "# DataLoader for test/validation data\n", + "test_loader = DataLoader(\n", + " test_dataset,\n", + " batch_size=32,\n", + " shuffle=False,\n", + " num_workers=2\n", + ")\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 4. Print shape of one batch\n", + "\n", + "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": [ + "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", + "# Task 1: Write your model class here:\n", + "\n", + "class NN5Layer(nn.Module):\n", + "\n", + " def __init__(self, input_dim, hidden_dim, output_dim):\n", + " super(NN5Layer, self).__init__()\n", + "\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", + "\n", + " self.layer4 = nn.Linear(hidden_dim, hidden_dim)\n", + "\n", + "\n", + " self.layer5 = 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", + "\n", + " z1 = self.layer1(x)\n", + " a1 = self.relu(z1)\n", + "\n", + "\n", + " z2 = self.layer2(a1)\n", + " a2 = self.relu(z2)\n", + "\n", + "\n", + " z3 = self.layer3(a2)\n", + " a3 = self.relu(z3)\n", + "\n", + "\n", + " z4 = self.layer4(a3)\n", + " a4 = self.relu(z4)\n", + "\n", + " z5 = self.layer5(a4)\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", + " # 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", + "\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", + "\n", + "\n", + "\n", + "\n", + " predicted = outputs\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", + "# Device setup\n", + "device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n", + "\n", + "# Model parameters\n", + "\n", + "input_dim = 3 * 36 * 36\n", + "\n", + "\n", + "hidden_dim = 64 # Design choice\n", + "\n", + "\n", + "output_dim = 1 # Age\n", + "\n", + "\n", + "model = NN5Layer(input_dim, hidden_dim, output_dim).to(device)\n", + "\n", + "print(\"Model Architecture:\\n\")\n", + "print(model)\n", + "\n", + "# Calculate the total number of trainable parameters\n", + "total_params = sum(p.numel() for p in model.parameters() if p.requires_grad)\n", + "print(f\"\\nTotal trainable parameters: {total_params}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Start training for 20 epochs:\n", + "\n", + "\n", + "num_epochs = 20\n", + "\n", + "learning_rate = 0.001\n", + "\n", + "\n", + "criterion = nn.MSELoss()\n", + "\n", + "optimizer = AdamW(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:\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/216/Q3.ipynb b/submissions_extracted/216/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..9a512c4f5841a0cc627d7fe44ac8ddf26228f7a9 --- /dev/null +++ b/submissions_extracted/216/Q3.ipynb @@ -0,0 +1,274 @@ +{ + "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", + "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:# 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", + "#checking for missing values\n", + "check_missing_values(df)\n", + "\n", + "#handling catgorical missing values\n", + "num_cols = df.select_dtypes(include=\"number\").columns\n", + "df[num_cols] = df[num_cols].fillna(df[num_cols].mean())\n", + "\n", + "cat_cols = df.select_dtypes(exclude=\"number\").columns\n", + "for c in cat_cols:\n", + " df[c] = df[c].fillna(df[c].mode()[0])\n", + "\n", + "\n", + "print(\"After handling missing data: \")\n", + "\n", + "check_missing_values(df)" + ], + "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", + "check_duplicates(df)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "from sklearn.preprocessing import LabelEncoder\n", + "le = LabelEncoder()\n", + "cat_cols = df.select_dtypes(exclude=\"number\").columns\n", + "for c in cat_cols:\n", + " df[c] = le.fit_transform(df[c])\n", + "df.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", + "features = df.columns.drop(\"Target\") # DON'T SCALE THE TARGET\n", + "\n", + "scaler = StandardScaler()\n", + "df[features] = scaler.fit_transform(df[features])\n", + "df.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 5: Write your code here:\n", + "def check_target_imbalance(df, target_column):\n", + " print(\"Target Distribution:\")\n", + " print(df[target_column].value_counts(normalize=True))\n", + " sns.countplot(x=df[target_column])\n", + " plt.title(\"Target Distribution\")\n", + " plt.show()\n", + "\n", + "check_target_imbalance(df, \"Target\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "from sklearn.model_selection import StratifiedKFold\n", + "from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score\n", + "# Task 1: Write your code here:\n", + "X = df.drop(\"Target\", axis=1).astype(float)\n", + "y = df['Target'].astype(float)\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)" + ], + "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", + "model = CatBoostClassifier(verbose=0, n_estimators=320, max_depth=4)\n", + "scores = []\n", + "for fold_idx, (train_index, test_index) in enumerate(skf.split(X, y)):\n", + " print(f\"\\nFold {fold_idx + 1}/{n_splits}\")\n", + "\n", + " # 1. Split data\n", + " X_train, X_test = X.iloc[train_index], X.iloc[test_index]\n", + " y_train, y_test = y.iloc[train_index], y.iloc[test_index]\n", + "\n", + " # 2. Train & Validate sklearn models\n", + " model.fit(X_train, y_train) # train\n", + " y_pred = model.predict(X_test) # validate\n", + "\n", + " # 3. Save metrics for that model in this fold\n", + " f1 = f1_score(y_test, y_pred, zero_division=0)\n", + " print(\"The f1 score is \", f1)\n", + " scores.append(f1)\n", + "sum_score = 0\n", + "for score in scores:\n", + " sum_score+=score\n", + "print(\"The avg f1 score is \", sum_score/len(scores))\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 1: Write your code here:\n", + "features = df.columns.drop(\"Target\")\n", + "importance = pd.DataFrame({\n", + " 'feature': features,\n", + " 'importance': model.feature_importances_\n", + "}).sort_values('importance', ascending=False)\n", + "print(importance)\n", + "plt.figure(figsize=(10, 10))\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", + "print(\"The most important golden feature is \", \"P_2\", model.feature_importances_[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/217/Q1.ipynb b/submissions_extracted/217/Q1.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..0d09fc496a59696a7badcb21ea0370e75750e124 --- /dev/null +++ b/submissions_extracted/217/Q1.ipynb @@ -0,0 +1,266 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import pandas as pd\n", + "import numpy as np\n", + "import matplotlib.pyplot as plt\n", + "import seaborn as sns\n", + "from sklearn.preprocessing import StandardScaler, LabelEncoder\n", + "from sklearn.model_selection import train_test_split, KFold\n", + "from sklearn.ensemble import RandomForestRegressor\n", + "from sklearn.metrics import mean_squared_error\n", + "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": [ + "df_delivary_data = 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_delivary_data.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 3: Write your code here:\n", + "df_delivary_data.info()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 4: Write your code here:\n", + "df_delivary_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=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_delivary_data, \"Delivery_Time\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "df_delivary_data.drop(columns='Order_ID')" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "Missing_data = (df_delivary_data.isnull().sum() / len(df_delivary_data))\n", + "df_Missing_data = pd.DataFrame(\n", + " {\n", + " 'column':Missing_data.index,\n", + " 'Percent':Missing_data.values\n", + " }\n", + ")\n", + "df_Missing_data = df_Missing_data[df_Missing_data['Percent'] > 0].sort_values('Percent',ascending=False)\n", + "\n", + "Missing_cols = ['Delivery_Time','Weather','Traffic_Level','Time_of_Day','Courier_Experience_yrs']\n", + "print(f\"Shape before cleaning: {df_delivary_data.shape}\")\n", + "df_clean = df_delivary_data.dropna(subset=Missing_cols)\n", + "print(f\"Shape after cleaning: {df_clean.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "df_clean.drop_duplicates(inplace=True)\n", + "df_clean.shape" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "\n", + "cat_cols = ['Weather','Traffic_Level','Time_of_Day','Vehicle_Type']\n", + "le = LabelEncoder()\n", + "for cols in cat_cols:\n", + " df_clean[cols] = le.fit_transform(df_clean[cols])\n", + "df_clean.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "scaler = StandardScaler()\n", + "numerical_cols = df_clean.select_dtypes(include=[\"int64\", \"float64\"]).columns.drop(\"Delivery_Time\")\n", + "df_clean[numerical_cols] = scaler.fit_transform(df_clean[numerical_cols])\n", + "df_clean.head()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task 6: Write your code here:" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "X = df_clean.drop(\"Delivery_Time\", axis=1)\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", + "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", + "\n", + "y_pred = model.predict(X_test)\n", + "\n", + "mse_scores = []\n", + "\n", + "kf = KFold(n_splits=5, shuffle=True, random_state=42)\n", + "\n", + "for fold_idx, (train_index, test_index) in enumerate(kf.split(X)):\n", + " print(f\"\\nFold {fold_idx + 1}/{5}\")\n", + " print(f\"MAE: {mse:,.2f}\")\n", + " X_train, X_test = X.iloc[train_index], X.iloc[test_index]\n", + " y_train, y_test = y.iloc[train_index], y.iloc[test_index]\n", + "\n", + " # Train\n", + " model.fit(X_train, y_train)\n", + "\n", + " # Predict\n", + " y_pred = model.predict(X_test)\n", + "\n", + " # Calculate metrics\n", + " mse = mean_squared_error(y_test, y_pred)\n", + "\n", + " # Store results\n", + " mse_scores.append(mse)\n", + "mse_scores = np.array(mse_scores)\n", + "print(f\"5-Fold MSE Results:\")\n", + "print(f\"MAE: {mse_scores.mean():,.2f}\")\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "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.figure(figsize=(10, 5))\n", + "plt.hist(y_pred, bins=50, edgecolor='black')\n", + "plt.title('Delivery Time Distribution')\n", + "plt.xlabel('Delivery Time')\n", + "plt.ylabel('Frequency')\n", + "plt.show()" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# Task Bonus: Write your code here:" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/submissions_extracted/217/Q2.ipynb b/submissions_extracted/217/Q2.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..53435c6bb7ab6441fa5910b3ea0605441928cae4 --- /dev/null +++ b/submissions_extracted/217/Q2.ipynb @@ -0,0 +1,325 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "\n", + "# Download latest version\n", + "path = kagglehub.dataset_download(\"ANON_OWNER/q2-exam-data\")\n", + "\n", + "print(\"Path to dataset files:\", path)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import os\n", + "import pandas as pd\n", + "import numpy as np\n", + "from PIL import Image\n", + "from sklearn.model_selection import train_test_split\n", + "import torch\n", + "import torch.nn as nn\n", + "from torch.optim import Adam\n", + "import torch.nn.functional as F\n", + "from torch.utils.data import DataLoader, TensorDataset\n", + "from sklearn.preprocessing import StandardScaler, LabelEncoder\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.float32)\n", + "y_test = torch.tensor(y_test, dtype=torch.float32)\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "train_dataset = TensorDataset(X_train, y_train)\n", + "test_dataset = TensorDataset(X_test, y_test)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "train_loader = DataLoader(train_dataset, batch_size=32, shuffle=True)\n", + "test_loader = DataLoader(test_dataset, batch_size=32, shuffle=False)\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "X_batch, y_batch = next(iter(train_loader))\n", + "print(f\"Training batch input shape: {X_batch.shape}\")\n", + "print(f\"Training batch labels shape: {y_batch.shape}\")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "# 5. Display sample images\n", + "\n" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "class 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": [ + "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", + "num_epochs = 20\n", + "learning_rate = 0.001\n", + "\n", + "input_dim = 36 * 36\n", + "hidden_dim = 18\n", + "output_dim = 1\n", + "\n", + "# Instantiate model\n", + "model = NN4Layer(input_dim, hidden_dim, output_dim).to(device)\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": [ + "# 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/217/Q3.ipynb b/submissions_extracted/217/Q3.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..6000b281f07e19c2bf86bd5eba9933176cacec1e --- /dev/null +++ b/submissions_extracted/217/Q3.ipynb @@ -0,0 +1,178 @@ +{ + "cells": [ + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import kagglehub\n", + "import pandas as pd\n", + "import numpy as np\n", + "from sklearn.preprocessing import StandardScaler\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": [ + "df = pd.read_csv(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": [ + "Missing_data = (df.isnull().sum() / len(df))\n", + "df_Missing_data = pd.DataFrame(\n", + " {\n", + " 'column':Missing_data.index,\n", + " 'Percent':Missing_data.values\n", + " }\n", + ")\n", + "df_Missing_data = df_Missing_data[df_Missing_data['Percent'] > 0].sort_values('Percent',ascending=False)\n", + "missing_columns = []\n", + "for cols in df_Missing_data['column']:\n", + " missing_columns += [cols]\n", + "for col in missing_columns:\n", + " df_clean = df.dropna(subset= col).copy()\n", + "df_clean" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "df_clean.drop_duplicates()" + ], + "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", + "scaler = StandardScaler()\n", + "scaled_cols = df_clean.drop('Target')\n", + "df_clean[scaled_cols] = scaler.fit_transform(df_clean[scaled_cols])" + ], + "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